Compare commits

..

No commits in common. "main" and "v0.1.186" have entirely different histories.

25 changed files with 846 additions and 2521 deletions

View File

@ -327,16 +327,9 @@ Storage:
├─ ● Data_2: GGA04461 T: 28°C ├─ ● Data_2: GGA04461 T: 28°C
└─ ● Parity: WDZS8RY0 T: 29°C └─ ● Parity: WDZS8RY0 T: 29°C
Backup: Backup:
● Repo: 4
├─ getea
├─ vaultwarden
├─ mysql
└─ immich
● W800639Y W: 2%
├─ ● Backup: 2025-11-29T04:00:01.324623
└─ ● Usage: 8% 70GB/916GB
● WD-WCC7K1234567 T: 32°C W: 12% ● WD-WCC7K1234567 T: 32°C W: 12%
├─ ● Backup: 2025-11-29T04:00:01.324623 ├─ Last: 2h ago (12.3GB)
├─ Next: in 22h
└─ ● Usage: 45% 678GB/1.5TB └─ ● Usage: 45% 678GB/1.5TB
``` ```

48
Cargo.lock generated
View File

@ -279,7 +279,7 @@ checksum = "a1d728cc89cf3aee9ff92b05e62b19ee65a02b5702cff7d5a377e32c6ae29d8d"
[[package]] [[package]]
name = "cm-dashboard" name = "cm-dashboard"
version = "0.1.274" version = "0.1.185"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"chrono", "chrono",
@ -301,7 +301,7 @@ dependencies = [
[[package]] [[package]]
name = "cm-dashboard-agent" name = "cm-dashboard-agent"
version = "0.1.274" version = "0.1.185"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"async-trait", "async-trait",
@ -309,7 +309,6 @@ dependencies = [
"chrono-tz", "chrono-tz",
"clap", "clap",
"cm-dashboard-shared", "cm-dashboard-shared",
"futures",
"gethostname", "gethostname",
"lettre", "lettre",
"reqwest", "reqwest",
@ -325,7 +324,7 @@ dependencies = [
[[package]] [[package]]
name = "cm-dashboard-shared" name = "cm-dashboard-shared"
version = "0.1.274" version = "0.1.185"
dependencies = [ dependencies = [
"chrono", "chrono",
"serde", "serde",
@ -553,21 +552,6 @@ dependencies = [
"percent-encoding", "percent-encoding",
] ]
[[package]]
name = "futures"
version = "0.3.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65bc07b1a8bc7c85c5f2e110c476c7389b4554ba72af57d8445ea63a576b0876"
dependencies = [
"futures-channel",
"futures-core",
"futures-executor",
"futures-io",
"futures-sink",
"futures-task",
"futures-util",
]
[[package]] [[package]]
name = "futures-channel" name = "futures-channel"
version = "0.3.31" version = "0.3.31"
@ -575,7 +559,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2dff15bf788c671c1934e366d07e30c1814a8ef514e1af724a602e8a2fbe1b10" checksum = "2dff15bf788c671c1934e366d07e30c1814a8ef514e1af724a602e8a2fbe1b10"
dependencies = [ dependencies = [
"futures-core", "futures-core",
"futures-sink",
] ]
[[package]] [[package]]
@ -584,34 +567,12 @@ version = "0.3.31"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "05f29059c0c2090612e8d742178b0580d2dc940c837851ad723096f87af6663e" checksum = "05f29059c0c2090612e8d742178b0580d2dc940c837851ad723096f87af6663e"
[[package]]
name = "futures-executor"
version = "0.3.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e28d1d997f585e54aebc3f97d39e72338912123a67330d723fdbb564d646c9f"
dependencies = [
"futures-core",
"futures-task",
"futures-util",
]
[[package]] [[package]]
name = "futures-io" name = "futures-io"
version = "0.3.31" version = "0.3.31"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9e5c1b78ca4aae1ac06c48a526a655760685149f0d465d21f37abfe57ce075c6" checksum = "9e5c1b78ca4aae1ac06c48a526a655760685149f0d465d21f37abfe57ce075c6"
[[package]]
name = "futures-macro"
version = "0.3.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "162ee34ebcb7c64a8abebc059ce0fee27c2262618d7b60ed8faf72fef13c3650"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]] [[package]]
name = "futures-sink" name = "futures-sink"
version = "0.3.31" version = "0.3.31"
@ -630,11 +591,8 @@ version = "0.3.31"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9fa08315bb612088cc391249efdc3bc77536f16c91f6cf495e6fbe85b20a4a81" checksum = "9fa08315bb612088cc391249efdc3bc77536f16c91f6cf495e6fbe85b20a4a81"
dependencies = [ dependencies = [
"futures-channel",
"futures-core", "futures-core",
"futures-io", "futures-io",
"futures-macro",
"futures-sink",
"futures-task", "futures-task",
"memchr", "memchr",
"pin-project-lite", "pin-project-lite",

View File

@ -1,6 +1,6 @@
[package] [package]
name = "cm-dashboard-agent" name = "cm-dashboard-agent"
version = "0.1.275" version = "0.1.186"
edition = "2021" edition = "2021"
[dependencies] [dependencies]
@ -21,4 +21,3 @@ chrono-tz = "0.8"
toml = { workspace = true } toml = { workspace = true }
async-trait = "0.1" async-trait = "0.1"
reqwest = { version = "0.11", features = ["json", "blocking"] } reqwest = { version = "0.11", features = ["json", "blocking"] }
futures = "0.3"

View File

@ -1,10 +1,10 @@
use anyhow::Result; use anyhow::Result;
use gethostname::gethostname; use gethostname::gethostname;
use std::time::{Duration, Instant}; use std::time::Duration;
use tokio::time::interval; use tokio::time::interval;
use tracing::{debug, error, info}; use tracing::{debug, error, info};
use crate::communication::ZmqHandler; use crate::communication::{AgentCommand, ZmqHandler};
use crate::config::AgentConfig; use crate::config::AgentConfig;
use crate::collectors::{ use crate::collectors::{
Collector, Collector,
@ -19,22 +19,13 @@ use crate::collectors::{
use crate::notifications::NotificationManager; use crate::notifications::NotificationManager;
use cm_dashboard_shared::AgentData; use cm_dashboard_shared::AgentData;
/// Wrapper for collectors with timing information
struct TimedCollector {
collector: Box<dyn Collector>,
interval: Duration,
last_collection: Option<Instant>,
name: String,
}
pub struct Agent { pub struct Agent {
hostname: String, hostname: String,
config: AgentConfig, config: AgentConfig,
zmq_handler: ZmqHandler, zmq_handler: ZmqHandler,
collectors: Vec<TimedCollector>, collectors: Vec<Box<dyn Collector>>,
notification_manager: NotificationManager, notification_manager: NotificationManager,
previous_status: Option<SystemStatus>, previous_status: Option<SystemStatus>,
cached_agent_data: AgentData,
} }
/// Track system component status for change detection /// Track system component status for change detection
@ -64,78 +55,36 @@ impl Agent {
config.zmq.publisher_port config.zmq.publisher_port
); );
// Initialize collectors with timing information // Initialize collectors
let mut collectors: Vec<TimedCollector> = Vec::new(); let mut collectors: Vec<Box<dyn Collector>> = Vec::new();
// Add enabled collectors // Add enabled collectors
if config.collectors.cpu.enabled { if config.collectors.cpu.enabled {
collectors.push(TimedCollector { collectors.push(Box::new(CpuCollector::new(config.collectors.cpu.clone())));
collector: Box::new(CpuCollector::new(config.collectors.cpu.clone())),
interval: Duration::from_secs(config.collectors.cpu.interval_seconds),
last_collection: None,
name: "CPU".to_string(),
});
info!("CPU collector initialized with {}s interval", config.collectors.cpu.interval_seconds);
} }
if config.collectors.memory.enabled { if config.collectors.memory.enabled {
collectors.push(TimedCollector { collectors.push(Box::new(MemoryCollector::new(config.collectors.memory.clone())));
collector: Box::new(MemoryCollector::new(config.collectors.memory.clone())),
interval: Duration::from_secs(config.collectors.memory.interval_seconds),
last_collection: None,
name: "Memory".to_string(),
});
info!("Memory collector initialized with {}s interval", config.collectors.memory.interval_seconds);
} }
if config.collectors.disk.enabled { if config.collectors.disk.enabled {
collectors.push(TimedCollector { collectors.push(Box::new(DiskCollector::new(config.collectors.disk.clone())));
collector: Box::new(DiskCollector::new(config.collectors.disk.clone())),
interval: Duration::from_secs(config.collectors.disk.interval_seconds),
last_collection: None,
name: "Disk".to_string(),
});
info!("Disk collector initialized with {}s interval", config.collectors.disk.interval_seconds);
} }
if config.collectors.systemd.enabled { if config.collectors.systemd.enabled {
collectors.push(TimedCollector { collectors.push(Box::new(SystemdCollector::new(config.collectors.systemd.clone())));
collector: Box::new(SystemdCollector::new(config.collectors.systemd.clone())),
interval: Duration::from_secs(config.collectors.systemd.interval_seconds),
last_collection: None,
name: "Systemd".to_string(),
});
info!("Systemd collector initialized with {}s interval", config.collectors.systemd.interval_seconds);
} }
if config.collectors.backup.enabled { if config.collectors.backup.enabled {
collectors.push(TimedCollector { collectors.push(Box::new(BackupCollector::new()));
collector: Box::new(BackupCollector::new()),
interval: Duration::from_secs(config.collectors.backup.interval_seconds),
last_collection: None,
name: "Backup".to_string(),
});
info!("Backup collector initialized with {}s interval", config.collectors.backup.interval_seconds);
} }
if config.collectors.network.enabled { if config.collectors.network.enabled {
collectors.push(TimedCollector { collectors.push(Box::new(NetworkCollector::new(config.collectors.network.clone())));
collector: Box::new(NetworkCollector::new(config.collectors.network.clone())),
interval: Duration::from_secs(config.collectors.network.interval_seconds),
last_collection: None,
name: "Network".to_string(),
});
info!("Network collector initialized with {}s interval", config.collectors.network.interval_seconds);
} }
if config.collectors.nixos.enabled { if config.collectors.nixos.enabled {
collectors.push(TimedCollector { collectors.push(Box::new(NixOSCollector::new(config.collectors.nixos.clone())));
collector: Box::new(NixOSCollector::new(config.collectors.nixos.clone())),
interval: Duration::from_secs(config.collectors.nixos.interval_seconds),
last_collection: None,
name: "NixOS".to_string(),
});
info!("NixOS collector initialized with {}s interval", config.collectors.nixos.interval_seconds);
} }
info!("Initialized {} collectors", collectors.len()); info!("Initialized {} collectors", collectors.len());
@ -144,9 +93,6 @@ impl Agent {
let notification_manager = NotificationManager::new(&config.notifications, &hostname)?; let notification_manager = NotificationManager::new(&config.notifications, &hostname)?;
info!("Notification manager initialized"); info!("Notification manager initialized");
// Initialize cached agent data
let cached_agent_data = AgentData::new(hostname.clone(), env!("CARGO_PKG_VERSION").to_string());
Ok(Self { Ok(Self {
hostname, hostname,
config, config,
@ -154,7 +100,6 @@ impl Agent {
collectors, collectors,
notification_manager, notification_manager,
previous_status: None, previous_status: None,
cached_agent_data,
}) })
} }
@ -169,7 +114,7 @@ impl Agent {
// Set up intervals // Set up intervals
let mut transmission_interval = interval(Duration::from_secs( let mut transmission_interval = interval(Duration::from_secs(
self.config.zmq.transmission_interval_seconds, self.config.collection_interval_seconds,
)); ));
let mut notification_interval = interval(Duration::from_secs(30)); // Check notifications every 30s let mut notification_interval = interval(Duration::from_secs(30)); // Check notifications every 30s
@ -189,6 +134,12 @@ impl Agent {
// NOTE: With structured data, we might need to implement status tracking differently // NOTE: With structured data, we might need to implement status tracking differently
// For now, we skip this until status evaluation is migrated // For now, we skip this until status evaluation is migrated
} }
// Handle incoming commands (check periodically)
_ = tokio::time::sleep(Duration::from_millis(100)) => {
if let Err(e) = self.handle_commands().await {
error!("Error handling commands: {}", e);
}
}
_ = &mut shutdown_rx => { _ = &mut shutdown_rx => {
info!("Shutdown signal received, stopping agent loop"); info!("Shutdown signal received, stopping agent loop");
break; break;
@ -204,47 +155,24 @@ impl Agent {
async fn collect_and_broadcast(&mut self) -> Result<()> { async fn collect_and_broadcast(&mut self) -> Result<()> {
debug!("Starting structured data collection"); debug!("Starting structured data collection");
// Collect data from collectors whose intervals have elapsed // Initialize empty AgentData
// Update cached_agent_data with new data let mut agent_data = AgentData::new(self.hostname.clone(), env!("CARGO_PKG_VERSION").to_string());
let now = Instant::now();
for timed_collector in &mut self.collectors {
let should_collect = match timed_collector.last_collection {
None => true, // First collection
Some(last_time) => now.duration_since(last_time) >= timed_collector.interval,
};
if should_collect { // Collect data from all collectors
if let Err(e) = timed_collector.collector.collect_structured(&mut self.cached_agent_data).await { for collector in &self.collectors {
error!("Collector {} failed: {}", timed_collector.name, e); if let Err(e) = collector.collect_structured(&mut agent_data).await {
// Update last_collection time even on failure to prevent immediate retries error!("Collector failed: {}", e);
timed_collector.last_collection = Some(now); // Continue with other collectors even if one fails
} else {
timed_collector.last_collection = Some(now);
debug!(
"Collected from {} ({}s interval)",
timed_collector.name,
timed_collector.interval.as_secs()
);
}
} }
} }
// Update timestamp on cached data
self.cached_agent_data.timestamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs();
// Clone for notification check (to avoid borrow issues)
let agent_data_snapshot = self.cached_agent_data.clone();
// Check for status changes and send notifications // Check for status changes and send notifications
if let Err(e) = self.check_status_changes_and_notify(&agent_data_snapshot).await { if let Err(e) = self.check_status_changes_and_notify(&agent_data).await {
error!("Failed to check status changes: {}", e); error!("Failed to check status changes: {}", e);
} }
// Broadcast the cached structured data via ZMQ // Broadcast the structured data via ZMQ
if let Err(e) = self.zmq_handler.publish_agent_data(&agent_data_snapshot).await { if let Err(e) = self.zmq_handler.publish_agent_data(&agent_data).await {
error!("Failed to broadcast agent data: {}", e); error!("Failed to broadcast agent data: {}", e);
} else { } else {
debug!("Successfully broadcast structured agent data"); debug!("Successfully broadcast structured agent data");
@ -331,4 +259,36 @@ impl Agent {
Ok(()) Ok(())
} }
/// Handle incoming commands from dashboard
async fn handle_commands(&mut self) -> Result<()> {
// Try to receive a command (non-blocking)
if let Ok(Some(command)) = self.zmq_handler.try_receive_command() {
info!("Received command: {:?}", command);
match command {
AgentCommand::CollectNow => {
info!("Received immediate collection request");
if let Err(e) = self.collect_and_broadcast().await {
error!("Failed to collect on demand: {}", e);
}
}
AgentCommand::SetInterval { seconds } => {
info!("Received interval change request: {}s", seconds);
// Note: This would require more complex handling to update the interval
// For now, just acknowledge
}
AgentCommand::ToggleCollector { name, enabled } => {
info!("Received collector toggle request: {} -> {}", name, enabled);
// Note: This would require more complex handling to enable/disable collectors
// For now, just acknowledge
}
AgentCommand::Ping => {
info!("Received ping command");
// Maybe send back a pong or status
}
}
}
Ok(())
}
} }

View File

@ -1,51 +1,36 @@
use async_trait::async_trait; use async_trait::async_trait;
use cm_dashboard_shared::{AgentData, BackupData, BackupRepositoryData, Status}; use cm_dashboard_shared::{AgentData, BackupData, BackupDiskData};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::collections::HashMap; use std::collections::HashMap;
use std::fs; use std::fs;
use std::path::{Path, PathBuf}; use std::path::Path;
use tracing::{debug, warn}; use tracing::debug;
use super::{Collector, CollectorError}; use super::{Collector, CollectorError};
/// Backup collector that reads backup status from TOML files with structured data output /// Backup collector that reads backup status from TOML files with structured data output
pub struct BackupCollector { pub struct BackupCollector {
/// Directory containing backup status files /// Path to backup status file
status_dir: String, status_file_path: String,
} }
impl BackupCollector { impl BackupCollector {
pub fn new() -> Self { pub fn new() -> Self {
Self { Self {
status_dir: "/var/lib/backup/status".to_string(), status_file_path: "/var/lib/backup/backup-status.toml".to_string(),
} }
} }
/// Scan directory for backup status file (nfs-backup.toml) /// Read backup status from TOML file
async fn scan_status_files(&self) -> Result<Vec<PathBuf>, CollectorError> { async fn read_backup_status(&self) -> Result<Option<BackupStatusToml>, CollectorError> {
let status_path = Path::new(&self.status_dir); if !Path::new(&self.status_file_path).exists() {
debug!("Backup status file not found: {}", self.status_file_path);
if !status_path.exists() { return Ok(None);
debug!("Backup status directory not found: {}", self.status_dir);
return Ok(Vec::new());
} }
// Look for nfs-backup.toml (new NFS-based backup) let content = fs::read_to_string(&self.status_file_path)
let nfs_backup_file = status_path.join("nfs-backup.toml");
if nfs_backup_file.exists() {
return Ok(vec![nfs_backup_file]);
}
// No backup status file found
debug!("No nfs-backup.toml found in {}", self.status_dir);
Ok(Vec::new())
}
/// Read a single backup status file
async fn read_status_file(&self, path: &Path) -> Result<BackupStatusToml, CollectorError> {
let content = fs::read_to_string(path)
.map_err(|e| CollectorError::SystemRead { .map_err(|e| CollectorError::SystemRead {
path: path.to_string_lossy().to_string(), path: self.status_file_path.clone(),
error: e.to_string(), error: e.to_string(),
})?; })?;
@ -55,84 +40,66 @@ impl BackupCollector {
error: format!("Failed to parse backup status TOML: {}", e), error: format!("Failed to parse backup status TOML: {}", e),
})?; })?;
Ok(status) Ok(Some(status))
}
/// Calculate backup status from TOML status field
fn calculate_backup_status(status_str: &str) -> Status {
match status_str.to_lowercase().as_str() {
"success" | "completed" => Status::Ok,
"warning" => Status::Warning,
"failed" | "error" => Status::Critical,
_ => Status::Unknown,
}
} }
/// Convert BackupStatusToml to BackupData and populate AgentData /// Convert BackupStatusToml to BackupData and populate AgentData
async fn populate_backup_data(&self, agent_data: &mut AgentData) -> Result<(), CollectorError> { async fn populate_backup_data(&self, agent_data: &mut AgentData) -> Result<(), CollectorError> {
let status_files = self.scan_status_files().await?; if let Some(backup_status) = self.read_backup_status().await? {
// Use raw start_time string from TOML
if status_files.is_empty() { // Extract disk information
debug!("No backup status files found"); let repository_disk = if let Some(disk_space) = &backup_status.disk_space {
agent_data.backup = BackupData { Some(BackupDiskData {
last_backup_time: None, serial: backup_status.disk_serial_number.clone().unwrap_or_else(|| "Unknown".to_string()),
backup_status: Status::Unknown, usage_percent: disk_space.usage_percent as f32,
repositories: Vec::new(), used_gb: disk_space.used_gb as f32,
total_gb: disk_space.total_gb as f32,
wear_percent: backup_status.disk_wear_percent,
temperature_celsius: None, // Not available in current TOML
})
} else if let Some(serial) = &backup_status.disk_serial_number {
// Fallback: create minimal disk info if we have serial but no disk_space
Some(BackupDiskData {
serial: serial.clone(),
usage_percent: 0.0,
used_gb: 0.0,
total_gb: 0.0,
wear_percent: backup_status.disk_wear_percent,
temperature_celsius: None,
})
} else {
None
};
// Calculate total repository size from services
let total_size_gb = backup_status.services
.values()
.map(|service| service.repo_size_bytes as f32 / (1024.0 * 1024.0 * 1024.0))
.sum::<f32>();
let backup_data = BackupData {
status: backup_status.status,
total_size_gb: Some(total_size_gb),
repository_health: Some("ok".to_string()), // Derive from status if needed
repository_disk,
last_backup_size_gb: None, // Not available in current TOML format
start_time_raw: Some(backup_status.start_time),
};
agent_data.backup = backup_data;
} else {
// No backup status available - set default values
agent_data.backup = BackupData {
status: "unavailable".to_string(),
total_size_gb: None,
repository_health: None,
repository_disk: None,
last_backup_size_gb: None,
start_time_raw: None,
}; };
return Ok(());
} }
// Aggregate repository data across all backup status files
let mut repo_map: HashMap<String, BackupRepositoryData> = HashMap::new();
let mut worst_status = Status::Ok;
let mut latest_backup_time: Option<String> = None;
for status_file in status_files {
match self.read_status_file(&status_file).await {
Ok(backup_status) => {
// Calculate backup status
let backup_status_enum = Self::calculate_backup_status(&backup_status.status);
worst_status = worst_status.max(backup_status_enum);
// Track latest backup time
if latest_backup_time.is_none() || Some(&backup_status.start_time) > latest_backup_time.as_ref() {
latest_backup_time = Some(backup_status.start_time.clone());
}
// Process each service in this backup
for (service_name, service_status) in backup_status.services {
// Convert bytes to GB
let repo_size_gb = service_status.repo_size_bytes as f32 / 1_073_741_824.0;
// Calculate service status
let service_status_enum = Self::calculate_backup_status(&service_status.status);
worst_status = worst_status.max(service_status_enum);
// Update or insert repository data
repo_map.insert(service_name.clone(), BackupRepositoryData {
name: service_name,
archive_count: service_status.archive_count,
repo_size_gb,
status: service_status_enum,
});
}
}
Err(e) => {
warn!("Failed to read backup status file {:?}: {}", status_file, e);
}
}
}
// Convert HashMap to sorted Vec
let mut repositories: Vec<BackupRepositoryData> = repo_map.into_values().collect();
repositories.sort_by(|a, b| a.name.cmp(&b.name));
agent_data.backup = BackupData {
last_backup_time: latest_backup_time,
backup_status: worst_status,
repositories,
};
Ok(()) Ok(())
} }
} }

View File

@ -119,134 +119,36 @@ impl CpuCollector {
utils::parse_u64(content.trim()) utils::parse_u64(content.trim())
} }
/// Collect static CPU information from /proc/cpuinfo (only once at startup) /// Collect CPU frequency and populate AgentData
async fn collect_cpu_info(&self, agent_data: &mut AgentData) -> Result<(), CollectorError> { async fn collect_frequency(&self, agent_data: &mut AgentData) -> Result<(), CollectorError> {
let content = utils::read_proc_file("/proc/cpuinfo")?; // Try scaling frequency first (more accurate for current frequency)
if let Ok(freq) =
let mut model_name: Option<String> = None; utils::read_proc_file("/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq")
let mut core_count: u32 = 0; {
if let Ok(freq_khz) = utils::parse_u64(freq.trim()) {
for line in content.lines() { let freq_mhz = freq_khz as f32 / 1000.0;
if line.starts_with("model name") { agent_data.system.cpu.frequency_mhz = freq_mhz;
if let Some(colon_pos) = line.find(':') { return Ok(());
let full_name = line[colon_pos + 1..].trim();
// Extract just the model number (e.g., "i7-9700" from "Intel(R) Core(TM) i7-9700 CPU @ 3.00GHz")
let model = Self::extract_cpu_model(full_name);
if model_name.is_none() {
model_name = Some(model);
}
}
} else if line.starts_with("processor") {
core_count += 1;
} }
} }
agent_data.system.cpu.model_name = model_name; // Fallback: parse /proc/cpuinfo for base frequency
if core_count > 0 { if let Ok(content) = utils::read_proc_file("/proc/cpuinfo") {
agent_data.system.cpu.core_count = Some(core_count); for line in content.lines() {
} if line.starts_with("cpu MHz") {
if let Some(freq_str) = line.split(':').nth(1) {
Ok(()) if let Ok(freq_mhz) = utils::parse_f32(freq_str) {
} agent_data.system.cpu.frequency_mhz = freq_mhz;
return Ok(());
/// Extract CPU model number from full model name
/// Examples:
/// - "Intel(R) Core(TM) i7-9700 CPU @ 3.00GHz" -> "i7-9700"
/// - "12th Gen Intel(R) Core(TM) i7-12700K" -> "i7-12700K"
/// - "AMD Ryzen 9 5950X 16-Core Processor" -> "Ryzen 9 5950X"
fn extract_cpu_model(full_name: &str) -> String {
// Look for Intel Core patterns (both old and new gen): i3, i5, i7, i9
// Match pattern like "i7-12700K" or "i7-9700"
for prefix in &["i3-", "i5-", "i7-", "i9-"] {
if let Some(pos) = full_name.find(prefix) {
// Find end of model number (until space or end of string)
let after_prefix = &full_name[pos..];
let end = after_prefix.find(' ').unwrap_or(after_prefix.len());
return after_prefix[..end].to_string();
}
}
// Look for AMD Ryzen pattern
if let Some(pos) = full_name.find("Ryzen") {
// Extract "Ryzen X XXXX" pattern
let after_ryzen = &full_name[pos..];
let parts: Vec<&str> = after_ryzen.split_whitespace().collect();
if parts.len() >= 3 {
return format!("{} {} {}", parts[0], parts[1], parts[2]);
}
}
// Fallback: return first 15 characters or full name if shorter
if full_name.len() > 15 {
full_name[..15].to_string()
} else {
full_name.to_string()
}
}
/// Collect CPU C-state (idle depth) and populate AgentData with top 3 C-states by usage
async fn collect_cstate(&self, agent_data: &mut AgentData) -> Result<(), CollectorError> {
// Read C-state usage from first CPU (representative of overall system)
// C-states indicate CPU idle depth: C1=light sleep, C6=deep sleep, C10=deepest
let mut cstate_times: Vec<(String, u64)> = Vec::new();
let mut total_time: u64 = 0;
// Collect all C-state times from CPU0
for state_num in 0..=10 {
let time_path = format!("/sys/devices/system/cpu/cpu0/cpuidle/state{}/time", state_num);
let name_path = format!("/sys/devices/system/cpu/cpu0/cpuidle/state{}/name", state_num);
if let Ok(time_str) = utils::read_proc_file(&time_path) {
if let Ok(time) = utils::parse_u64(time_str.trim()) {
if let Ok(name) = utils::read_proc_file(&name_path) {
let state_name = name.trim();
// Skip POLL state (not real idle)
if state_name != "POLL" && time > 0 {
// Extract "C" + digits pattern (C3, C10, etc.) to reduce JSON size
// Handles formats like "C3_ACPI", "C10_MWAIT", etc.
let clean_name = if let Some(c_pos) = state_name.find('C') {
let rest = &state_name[c_pos + 1..];
let digit_count = rest.chars().take_while(|c| c.is_ascii_digit()).count();
if digit_count > 0 {
state_name[c_pos..c_pos + 1 + digit_count].to_string()
} else {
state_name.to_string()
}
} else {
state_name.to_string()
};
cstate_times.push((clean_name, time));
total_time += time;
} }
} }
break; // Only need first CPU entry
} }
} else {
// No more states available
break;
} }
} }
// Sort by time descending to get top 3 debug!("CPU frequency not available");
cstate_times.sort_by(|a, b| b.1.cmp(&a.1)); // Leave frequency as 0.0 if not available
// Calculate percentages for top 3 and populate AgentData
agent_data.system.cpu.cstates = cstate_times
.iter()
.take(3)
.map(|(name, time)| {
let percent = if total_time > 0 {
(*time as f32 / total_time as f32) * 100.0
} else {
0.0
};
cm_dashboard_shared::CStateInfo {
name: name.clone(),
percent,
}
})
.collect();
Ok(()) Ok(())
} }
} }
@ -257,19 +159,14 @@ impl Collector for CpuCollector {
debug!("Collecting CPU metrics"); debug!("Collecting CPU metrics");
let start = std::time::Instant::now(); let start = std::time::Instant::now();
// Collect static CPU info (only once at startup)
if agent_data.system.cpu.model_name.is_none() || agent_data.system.cpu.core_count.is_none() {
self.collect_cpu_info(agent_data).await?;
}
// Collect load averages (always available) // Collect load averages (always available)
self.collect_load_averages(agent_data).await?; self.collect_load_averages(agent_data).await?;
// Collect temperature (optional) // Collect temperature (optional)
self.collect_temperature(agent_data).await?; self.collect_temperature(agent_data).await?;
// Collect C-state (CPU idle depth) // Collect frequency (optional)
self.collect_cstate(agent_data).await?; self.collect_frequency(agent_data).await?;
let duration = start.elapsed(); let duration = start.elapsed();
debug!("CPU collection completed in {:?}", duration); debug!("CPU collection completed in {:?}", duration);
@ -282,8 +179,8 @@ impl Collector for CpuCollector {
); );
} }
// Calculate status using thresholds (use 5-minute average for stability) // Calculate status using thresholds
agent_data.system.cpu.load_status = self.calculate_load_status(agent_data.system.cpu.load_5min); agent_data.system.cpu.load_status = self.calculate_load_status(agent_data.system.cpu.load_1min);
agent_data.system.cpu.temperature_status = if let Some(temp) = agent_data.system.cpu.temperature_celsius { agent_data.system.cpu.temperature_status = if let Some(temp) = agent_data.system.cpu.temperature_celsius {
self.calculate_temperature_status(temp) self.calculate_temperature_status(temp)
} else { } else {

View File

@ -3,9 +3,10 @@ use async_trait::async_trait;
use cm_dashboard_shared::{AgentData, DriveData, FilesystemData, PoolData, HysteresisThresholds, Status}; use cm_dashboard_shared::{AgentData, DriveData, FilesystemData, PoolData, HysteresisThresholds, Status};
use crate::config::DiskConfig; use crate::config::DiskConfig;
use tokio::process::Command as TokioCommand; use std::process::Command;
use std::process::Command as StdCommand; use std::time::Instant;
use std::collections::HashMap; use std::collections::HashMap;
use tracing::debug;
use super::{Collector, CollectorError}; use super::{Collector, CollectorError};
@ -66,9 +67,8 @@ impl DiskCollector {
/// Collect all storage data and populate AgentData /// Collect all storage data and populate AgentData
async fn collect_storage_data(&self, agent_data: &mut AgentData) -> Result<(), CollectorError> { async fn collect_storage_data(&self, agent_data: &mut AgentData) -> Result<(), CollectorError> {
// Clear drives and pools to prevent duplicates when updating cached data let start_time = Instant::now();
agent_data.system.storage.drives.clear(); debug!("Starting clean storage collection");
agent_data.system.storage.pools.clear();
// Step 1: Get mount points and their backing devices // Step 1: Get mount points and their backing devices
let mount_devices = self.get_mount_devices().await?; let mount_devices = self.get_mount_devices().await?;
@ -104,17 +104,17 @@ impl DiskCollector {
self.populate_drives_data(&physical_drives, &smart_data, agent_data)?; self.populate_drives_data(&physical_drives, &smart_data, agent_data)?;
self.populate_pools_data(&mergerfs_pools, &smart_data, agent_data)?; self.populate_pools_data(&mergerfs_pools, &smart_data, agent_data)?;
let elapsed = start_time.elapsed();
debug!("Storage collection completed in {:?}", elapsed);
Ok(()) Ok(())
} }
/// Get block devices and their mount points using lsblk /// Get block devices and their mount points using lsblk
async fn get_mount_devices(&self) -> Result<HashMap<String, String>, CollectorError> { async fn get_mount_devices(&self) -> Result<HashMap<String, String>, CollectorError> {
use super::run_command_with_timeout; let output = Command::new("lsblk")
.args(&["-rn", "-o", "NAME,MOUNTPOINT"])
let mut cmd = TokioCommand::new("lsblk"); .output()
cmd.args(&["-rn", "-o", "NAME,MOUNTPOINT"]);
let output = run_command_with_timeout(cmd, 10).await
.map_err(|e| CollectorError::SystemRead { .map_err(|e| CollectorError::SystemRead {
path: "block devices".to_string(), path: "block devices".to_string(),
error: e.to_string(), error: e.to_string(),
@ -138,6 +138,7 @@ impl DiskCollector {
} }
} }
debug!("Found {} mounted block devices", mount_devices.len());
Ok(mount_devices) Ok(mount_devices)
} }
@ -150,8 +151,8 @@ impl DiskCollector {
Ok((total, used)) => { Ok((total, used)) => {
filesystem_usage.insert(mount_point.clone(), (total, used)); filesystem_usage.insert(mount_point.clone(), (total, used));
} }
Err(_e) => { Err(e) => {
// Silently skip filesystems we can't read debug!("Failed to get filesystem info for {}: {}", mount_point, e);
} }
} }
} }
@ -172,6 +173,8 @@ impl DiskCollector {
// Only add if we don't already have usage data for this mount point // Only add if we don't already have usage data for this mount point
if !filesystem_usage.contains_key(&mount_point) { if !filesystem_usage.contains_key(&mount_point) {
if let Ok((total, used)) = self.get_filesystem_info(&mount_point) { if let Ok((total, used)) = self.get_filesystem_info(&mount_point) {
debug!("Added MergerFS filesystem usage for {}: {}GB total, {}GB used",
mount_point, total as f32 / (1024.0 * 1024.0 * 1024.0), used as f32 / (1024.0 * 1024.0 * 1024.0));
filesystem_usage.insert(mount_point, (total, used)); filesystem_usage.insert(mount_point, (total, used));
} }
} }
@ -183,8 +186,8 @@ impl DiskCollector {
/// Get filesystem info for a single mount point /// Get filesystem info for a single mount point
fn get_filesystem_info(&self, mount_point: &str) -> Result<(u64, u64), CollectorError> { fn get_filesystem_info(&self, mount_point: &str) -> Result<(u64, u64), CollectorError> {
let output = StdCommand::new("timeout") let output = Command::new("df")
.args(&["10", "df", "--block-size=1", mount_point]) .args(&["--block-size=1", mount_point])
.output() .output()
.map_err(|e| CollectorError::SystemRead { .map_err(|e| CollectorError::SystemRead {
path: format!("df {}", mount_point), path: format!("df {}", mount_point),
@ -248,6 +251,7 @@ impl DiskCollector {
}; };
if pool_name.is_empty() { if pool_name.is_empty() {
debug!("Skipping mergerfs pool with empty name: {}", mount_point);
continue; continue;
} }
@ -275,7 +279,8 @@ impl DiskCollector {
// Categorize as data vs parity drives // Categorize as data vs parity drives
let (data_drives, parity_drives) = match self.categorize_pool_drives(&all_member_paths) { let (data_drives, parity_drives) = match self.categorize_pool_drives(&all_member_paths) {
Ok(drives) => drives, Ok(drives) => drives,
Err(_e) => { Err(e) => {
debug!("Failed to categorize drives for pool {}: {}. Skipping.", mount_point, e);
continue; continue;
} }
}; };
@ -291,6 +296,7 @@ impl DiskCollector {
} }
} }
debug!("Found {} mergerfs pools", pools.len());
Ok(pools) Ok(pools)
} }
@ -377,9 +383,9 @@ impl DiskCollector {
device.to_string() device.to_string()
} }
/// Get SMART data for drives in parallel /// Get SMART data for drives
async fn get_smart_data_for_drives(&self, physical_drives: &[PhysicalDrive], mergerfs_pools: &[MergerfsPool]) -> HashMap<String, SmartData> { async fn get_smart_data_for_drives(&self, physical_drives: &[PhysicalDrive], mergerfs_pools: &[MergerfsPool]) -> HashMap<String, SmartData> {
use futures::future::join_all; let mut smart_data = HashMap::new();
// Collect all drive names // Collect all drive names
let mut all_drives = std::collections::HashSet::new(); let mut all_drives = std::collections::HashSet::new();
@ -395,24 +401,9 @@ impl DiskCollector {
} }
} }
// Collect SMART data for all drives in parallel // Get SMART data for each drive
let futures: Vec<_> = all_drives for drive_name in all_drives {
.iter() if let Ok(data) = self.get_smart_data(&drive_name).await {
.map(|drive_name| {
let drive = drive_name.clone();
async move {
let result = self.get_smart_data(&drive).await;
(drive, result)
}
})
.collect();
let results = join_all(futures).await;
// Build HashMap from results
let mut smart_data = HashMap::new();
for (drive_name, result) in results {
if let Ok(data) = result {
smart_data.insert(drive_name, data); smart_data.insert(drive_name, data);
} }
} }
@ -422,18 +413,16 @@ impl DiskCollector {
/// Get SMART data for a single drive /// Get SMART data for a single drive
async fn get_smart_data(&self, drive_name: &str) -> Result<SmartData, CollectorError> { async fn get_smart_data(&self, drive_name: &str) -> Result<SmartData, CollectorError> {
use super::run_command_with_timeout;
// Use direct smartctl (no sudo) - service has CAP_SYS_RAWIO and CAP_SYS_ADMIN capabilities // Use direct smartctl (no sudo) - service has CAP_SYS_RAWIO and CAP_SYS_ADMIN capabilities
// For NVMe drives, specify device type explicitly // For NVMe drives, specify device type explicitly
let mut cmd = TokioCommand::new("smartctl"); let mut cmd = Command::new("smartctl");
if drive_name.starts_with("nvme") { if drive_name.starts_with("nvme") {
cmd.args(&["-d", "nvme", "-a", &format!("/dev/{}", drive_name)]); cmd.args(&["-d", "nvme", "-a", &format!("/dev/{}", drive_name)]);
} else { } else {
cmd.args(&["-a", &format!("/dev/{}", drive_name)]); cmd.args(&["-a", &format!("/dev/{}", drive_name)]);
} }
let output = run_command_with_timeout(cmd, 15).await let output = cmd.output()
.map_err(|e| CollectorError::SystemRead { .map_err(|e| CollectorError::SystemRead {
path: format!("SMART data for {}", drive_name), path: format!("SMART data for {}", drive_name),
error: e.to_string(), error: e.to_string(),
@ -441,10 +430,8 @@ impl DiskCollector {
let output_str = String::from_utf8_lossy(&output.stdout); let output_str = String::from_utf8_lossy(&output.stdout);
// Note: smartctl returns non-zero exit codes for warnings (like exit code 32 if !output.status.success() {
// for "temperature was high in the past"), but the output data is still valid. // Return unknown data rather than failing completely
// Only check if we got any output at all, don't reject based on exit code.
if output_str.is_empty() {
return Ok(SmartData { return Ok(SmartData {
health: "UNKNOWN".to_string(), health: "UNKNOWN".to_string(),
serial_number: None, serial_number: None,
@ -770,9 +757,9 @@ impl DiskCollector {
/// Get drive information for a mount path /// Get drive information for a mount path
fn get_drive_info_for_path(&self, path: &str) -> anyhow::Result<PoolDrive> { fn get_drive_info_for_path(&self, path: &str) -> anyhow::Result<PoolDrive> {
// Use lsblk to find the backing device with timeout // Use lsblk to find the backing device
let output = StdCommand::new("timeout") let output = Command::new("lsblk")
.args(&["10", "lsblk", "-rn", "-o", "NAME,MOUNTPOINT"]) .args(&["-rn", "-o", "NAME,MOUNTPOINT"])
.output() .output()
.map_err(|e| anyhow::anyhow!("Failed to run lsblk: {}", e))?; .map_err(|e| anyhow::anyhow!("Failed to run lsblk: {}", e))?;
@ -794,12 +781,19 @@ impl DiskCollector {
// Extract base device name (e.g., "sda1" -> "sda") // Extract base device name (e.g., "sda1" -> "sda")
let base_device = self.extract_base_device(&format!("/dev/{}", device)); let base_device = self.extract_base_device(&format!("/dev/{}", device));
// Temperature will be filled in later from parallel SMART collection // Get temperature from SMART data if available
// Don't collect it here to avoid sequential blocking with problematic async nesting let temperature = if let Ok(smart_data) = tokio::task::block_in_place(|| {
tokio::runtime::Handle::current().block_on(self.get_smart_data(&base_device))
}) {
smart_data.temperature_celsius
} else {
None
};
Ok(PoolDrive { Ok(PoolDrive {
name: base_device, name: base_device,
mount_point: path.to_string(), mount_point: path.to_string(),
temperature_celsius: None, temperature_celsius: temperature,
}) })
} }

View File

@ -105,12 +105,12 @@ impl MemoryCollector {
return Ok(()); return Ok(());
} }
// Get usage data for all tmpfs mounts at once using df (with 2 second timeout) // Get usage data for all tmpfs mounts at once using df
let mut df_args = vec!["2", "df", "--output=target,size,used", "--block-size=1"]; let mut df_args = vec!["df", "--output=target,size,used", "--block-size=1"];
df_args.extend(tmpfs_mounts.iter().map(|s| s.as_str())); df_args.extend(tmpfs_mounts.iter().map(|s| s.as_str()));
let df_output = std::process::Command::new("timeout") let df_output = std::process::Command::new(df_args[0])
.args(&df_args[..]) .args(&df_args[1..])
.output() .output()
.map_err(|e| CollectorError::SystemRead { .map_err(|e| CollectorError::SystemRead {
path: "tmpfs mounts".to_string(), path: "tmpfs mounts".to_string(),
@ -200,9 +200,6 @@ impl Collector for MemoryCollector {
debug!("Collecting memory metrics"); debug!("Collecting memory metrics");
let start = std::time::Instant::now(); let start = std::time::Instant::now();
// Clear tmpfs list to prevent duplicates when updating cached data
agent_data.system.memory.tmpfs.clear();
// Parse memory info from /proc/meminfo // Parse memory info from /proc/meminfo
let info = self.parse_meminfo().await?; let info = self.parse_meminfo().await?;

View File

@ -1,7 +1,6 @@
use async_trait::async_trait; use async_trait::async_trait;
use cm_dashboard_shared::{AgentData}; use cm_dashboard_shared::{AgentData};
use std::process::Output;
use std::time::Duration;
pub mod backup; pub mod backup;
pub mod cpu; pub mod cpu;
@ -14,38 +13,6 @@ pub mod systemd;
pub use error::CollectorError; pub use error::CollectorError;
/// Run a command with a timeout to prevent blocking
/// Properly kills the process if timeout is exceeded
pub async fn run_command_with_timeout(mut cmd: tokio::process::Command, timeout_secs: u64) -> std::io::Result<Output> {
use tokio::time::timeout;
use std::process::Stdio;
let timeout_duration = Duration::from_secs(timeout_secs);
// Configure stdio to capture output
cmd.stdout(Stdio::piped());
cmd.stderr(Stdio::piped());
let child = cmd.spawn()?;
let pid = child.id();
match timeout(timeout_duration, child.wait_with_output()).await {
Ok(result) => result,
Err(_) => {
// Timeout - force kill the process using system kill command
if let Some(process_id) = pid {
let _ = tokio::process::Command::new("kill")
.args(&["-9", &process_id.to_string()])
.output()
.await;
}
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 /// Base trait for all collectors with direct structured data output
#[async_trait] #[async_trait]

View File

@ -51,7 +51,7 @@ impl NetworkCollector {
/// Get the primary physical interface (the one with default route) /// Get the primary physical interface (the one with default route)
fn get_primary_physical_interface() -> Option<String> { fn get_primary_physical_interface() -> Option<String> {
match Command::new("timeout").args(["2", "ip", "route", "show", "default"]).output() { match Command::new("ip").args(["route", "show", "default"]).output() {
Ok(output) if output.status.success() => { Ok(output) if output.status.success() => {
let output_str = String::from_utf8_lossy(&output.stdout); let output_str = String::from_utf8_lossy(&output.stdout);
// Parse: "default via 192.168.1.1 dev eno1 ..." // Parse: "default via 192.168.1.1 dev eno1 ..."
@ -110,7 +110,7 @@ impl NetworkCollector {
// Parse VLAN configuration // Parse VLAN configuration
let vlan_map = Self::parse_vlan_config(); let vlan_map = Self::parse_vlan_config();
match Command::new("timeout").args(["2", "ip", "-j", "addr"]).output() { match Command::new("ip").args(["-j", "addr"]).output() {
Ok(output) if output.status.success() => { Ok(output) if output.status.success() => {
let json_str = String::from_utf8_lossy(&output.stdout); let json_str = String::from_utf8_lossy(&output.stdout);
@ -181,7 +181,6 @@ impl NetworkCollector {
link_status, link_status,
parent_interface, parent_interface,
vlan_id, vlan_id,
connection_method: None,
}); });
} }
} }

View File

@ -43,8 +43,8 @@ impl NixOSCollector {
match fs::read_to_string("/etc/hostname") { match fs::read_to_string("/etc/hostname") {
Ok(hostname) => Some(hostname.trim().to_string()), Ok(hostname) => Some(hostname.trim().to_string()),
Err(_) => { Err(_) => {
// Fallback to hostname command (with 2 second timeout) // Fallback to hostname command
match Command::new("timeout").args(["2", "hostname"]).output() { match Command::new("hostname").output() {
Ok(output) => Some(String::from_utf8_lossy(&output.stdout).trim().to_string()), Ok(output) => Some(String::from_utf8_lossy(&output.stdout).trim().to_string()),
Err(_) => None, Err(_) => None,
} }

View File

@ -4,7 +4,7 @@ use cm_dashboard_shared::{AgentData, ServiceData, SubServiceData, SubServiceMetr
use std::process::Command; use std::process::Command;
use std::sync::RwLock; use std::sync::RwLock;
use std::time::Instant; use std::time::Instant;
use tracing::{debug, info}; use tracing::debug;
use super::{Collector, CollectorError}; use super::{Collector, CollectorError};
use crate::config::SystemdConfig; use crate::config::SystemdConfig;
@ -43,10 +43,9 @@ struct ServiceCacheState {
/// Cached service status information from systemctl list-units /// Cached service status information from systemctl list-units
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
struct ServiceStatusInfo { struct ServiceStatusInfo {
load_state: String,
active_state: String, active_state: String,
memory_bytes: Option<u64>, sub_state: String,
restart_count: Option<u32>,
start_timestamp: Option<u64>,
} }
impl SystemdCollector { impl SystemdCollector {
@ -87,20 +86,14 @@ impl SystemdCollector {
let mut complete_service_data = Vec::new(); let mut complete_service_data = Vec::new();
for service_name in &monitored_services { for service_name in &monitored_services {
match self.get_service_status(service_name) { match self.get_service_status(service_name) {
Ok(status_info) => { Ok((active_status, _detailed_info)) => {
let memory_mb = self.get_service_memory_usage(service_name).await.unwrap_or(0.0);
let disk_gb = self.get_service_disk_usage(service_name).await.unwrap_or(0.0);
let mut sub_services = Vec::new(); let mut sub_services = Vec::new();
// Calculate uptime if we have start timestamp
let uptime_seconds = status_info.start_timestamp.and_then(|start| {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.ok()?
.as_secs();
Some(now.saturating_sub(start))
});
// Sub-service metrics for specific services (always include cached results) // Sub-service metrics for specific services (always include cached results)
if service_name.contains("nginx") && status_info.active_state == "active" { if service_name.contains("nginx") && active_status == "active" {
let nginx_sites = self.get_nginx_site_metrics(); let nginx_sites = self.get_nginx_site_metrics();
for (site_name, latency_ms) in nginx_sites { for (site_name, latency_ms) in nginx_sites {
let site_status = if latency_ms >= 0.0 && latency_ms < self.config.nginx_latency_critical_ms { let site_status = if latency_ms >= 0.0 && latency_ms < self.config.nginx_latency_critical_ms {
@ -120,12 +113,11 @@ impl SystemdCollector {
name: site_name.clone(), name: site_name.clone(),
service_status: self.calculate_service_status(&site_name, &site_status), service_status: self.calculate_service_status(&site_name, &site_status),
metrics, metrics,
service_type: "nginx_site".to_string(),
}); });
} }
} }
if service_name.contains("docker") && status_info.active_state == "active" { if service_name.contains("docker") && active_status == "active" {
let docker_containers = self.get_docker_containers(); let docker_containers = self.get_docker_containers();
for (container_name, container_status) in docker_containers { for (container_name, container_status) in docker_containers {
// For now, docker containers have no additional metrics // For now, docker containers have no additional metrics
@ -136,128 +128,23 @@ impl SystemdCollector {
name: container_name.clone(), name: container_name.clone(),
service_status: self.calculate_service_status(&container_name, &container_status), service_status: self.calculate_service_status(&container_name, &container_status),
metrics, metrics,
service_type: "container".to_string(),
}); });
} }
// Add Docker images // Add Docker images
let docker_images = self.get_docker_images(); let docker_images = self.get_docker_images();
for (image_name, _image_status, image_size_mb) in docker_images { for (image_name, image_status, image_size_str, image_size_mb) in docker_images {
let metrics = Vec::new(); let mut metrics = Vec::new();
metrics.push(SubServiceMetric {
sub_services.push(SubServiceData { label: "size".to_string(),
name: format!("{} size: {:.1} MB", image_name, image_size_mb), value: image_size_mb,
service_status: Status::Info, // Informational only, no status icon unit: Some("MB".to_string()),
metrics,
service_type: "image".to_string(),
}); });
}
}
if service_name == "openvpn-vpn-download" && status_info.active_state == "active" {
// Add VPN route
if let Some(external_ip) = self.get_vpn_external_ip() {
let metrics = Vec::new();
sub_services.push(SubServiceData { sub_services.push(SubServiceData {
name: format!("route: {}", external_ip), name: format!("{} ({})", image_name, image_size_str),
service_status: Status::Info, service_status: self.calculate_service_status(&image_name, &image_status),
metrics, metrics,
service_type: "vpn_route".to_string(),
});
}
// Add torrent stats
if let Some((active_count, download_mbps, upload_mbps)) = self.get_qbittorrent_stats() {
let metrics = Vec::new();
sub_services.push(SubServiceData {
name: format!("{} active, ↓ {:.1} MB/s, ↑ {:.1} MB/s", active_count, download_mbps, upload_mbps),
service_status: Status::Info,
metrics,
service_type: "torrent_stats".to_string(),
});
}
// Add active torrent copy status for each copy operation
for torrent_name in self.get_active_torrent_copies() {
let metrics = Vec::new();
sub_services.push(SubServiceData {
name: format!("Copy: {}", torrent_name),
service_status: Status::Info,
metrics,
service_type: "torrent_copy".to_string(),
});
}
}
if service_name == "nftables" && status_info.active_state == "active" {
let (tcp_ports, udp_ports) = self.get_nftables_open_ports();
if !tcp_ports.is_empty() {
let metrics = Vec::new();
sub_services.push(SubServiceData {
name: format!("wan tcp: {}", tcp_ports),
service_status: Status::Info,
metrics,
service_type: "firewall_port".to_string(),
});
}
if !udp_ports.is_empty() {
let metrics = Vec::new();
sub_services.push(SubServiceData {
name: format!("wan udp: {}", udp_ports),
service_status: Status::Info,
metrics,
service_type: "firewall_port".to_string(),
});
}
}
if service_name == "tailscaled" && status_info.active_state == "active" {
// Add Tailscale peers with their connection methods as sub-services
let peers = self.get_tailscale_peers();
for (peer_name, conn_method) in peers {
let metrics = Vec::new();
sub_services.push(SubServiceData {
name: format!("{}: {}", peer_name, conn_method),
service_status: Status::Info,
metrics,
service_type: "tailscale_peer".to_string(),
});
}
}
if service_name == "nfs-server" && status_info.active_state == "active" {
// Add NFS exports as sub-services
let exports = self.get_nfs_exports();
for (export_path, info) in exports {
let display = if !info.is_empty() {
format!("{} {}", export_path, info)
} else {
export_path
};
sub_services.push(SubServiceData {
name: display,
service_status: Status::Info,
metrics: Vec::new(),
service_type: "nfs_export".to_string(),
});
}
}
if (service_name == "smbd" || service_name == "samba-smbd") && status_info.active_state == "active" {
// Add SMB shares as sub-services
let shares = self.get_smb_shares();
for (share_name, share_path) in shares {
let metrics = Vec::new();
sub_services.push(SubServiceData {
name: format!("{}: {}", share_name, share_path),
service_status: Status::Info,
metrics,
service_type: "smb_share".to_string(),
}); });
} }
} }
@ -265,12 +152,11 @@ impl SystemdCollector {
// Create complete service data // Create complete service data
let service_data = ServiceData { let service_data = ServiceData {
name: service_name.clone(), name: service_name.clone(),
memory_mb,
disk_gb,
user_stopped: false, // TODO: Integrate with service tracker user_stopped: false, // TODO: Integrate with service tracker
service_status: self.calculate_service_status(service_name, &status_info.active_state), service_status: self.calculate_service_status(service_name, &active_status),
sub_services, sub_services,
memory_bytes: status_info.memory_bytes,
restart_count: status_info.restart_count,
uptime_seconds,
}; };
// Add to AgentData and cache // Add to AgentData and cache
@ -365,18 +251,18 @@ impl SystemdCollector {
/// Auto-discover interesting services to monitor /// Auto-discover interesting services to monitor
fn discover_services_internal(&self) -> Result<(Vec<String>, std::collections::HashMap<String, ServiceStatusInfo>)> { fn discover_services_internal(&self) -> Result<(Vec<String>, std::collections::HashMap<String, ServiceStatusInfo>)> {
// First: Get all service unit files (with 3 second timeout) // First: Get all service unit files
let unit_files_output = Command::new("timeout") let unit_files_output = Command::new("systemctl")
.args(&["3", "systemctl", "list-unit-files", "--type=service", "--no-pager", "--plain"]) .args(&["list-unit-files", "--type=service", "--no-pager", "--plain"])
.output()?; .output()?;
if !unit_files_output.status.success() { if !unit_files_output.status.success() {
return Err(anyhow::anyhow!("systemctl list-unit-files command failed")); return Err(anyhow::anyhow!("systemctl list-unit-files command failed"));
} }
// Second: Get runtime status of all units (with 3 second timeout) // Second: Get runtime status of all units
let units_status_output = Command::new("timeout") let units_status_output = Command::new("systemctl")
.args(&["3", "systemctl", "list-units", "--type=service", "--all", "--no-pager", "--plain"]) .args(&["list-units", "--type=service", "--all", "--no-pager", "--plain"])
.output()?; .output()?;
if !units_status_output.status.success() { if !units_status_output.status.success() {
@ -406,13 +292,14 @@ impl SystemdCollector {
let fields: Vec<&str> = line.split_whitespace().collect(); let fields: Vec<&str> = line.split_whitespace().collect();
if fields.len() >= 4 && fields[0].ends_with(".service") { if fields.len() >= 4 && fields[0].ends_with(".service") {
let service_name = fields[0].trim_end_matches(".service"); let service_name = fields[0].trim_end_matches(".service");
let load_state = fields.get(1).unwrap_or(&"unknown").to_string();
let active_state = fields.get(2).unwrap_or(&"unknown").to_string(); let active_state = fields.get(2).unwrap_or(&"unknown").to_string();
let sub_state = fields.get(3).unwrap_or(&"unknown").to_string();
status_cache.insert(service_name.to_string(), ServiceStatusInfo { status_cache.insert(service_name.to_string(), ServiceStatusInfo {
load_state,
active_state, active_state,
memory_bytes: None, sub_state,
restart_count: None,
start_timestamp: None,
}); });
} }
} }
@ -421,10 +308,9 @@ impl SystemdCollector {
for service_name in &all_service_names { for service_name in &all_service_names {
if !status_cache.contains_key(service_name) { if !status_cache.contains_key(service_name) {
status_cache.insert(service_name.to_string(), ServiceStatusInfo { status_cache.insert(service_name.to_string(), ServiceStatusInfo {
load_state: "not-loaded".to_string(),
active_state: "inactive".to_string(), active_state: "inactive".to_string(),
memory_bytes: None, sub_state: "dead".to_string(),
restart_count: None,
start_timestamp: None,
}); });
} }
} }
@ -456,60 +342,36 @@ impl SystemdCollector {
Ok((services, status_cache)) Ok((services, status_cache))
} }
/// Get service status with detailed metrics from systemctl /// Get service status from cache (if available) or fallback to systemctl
fn get_service_status(&self, service: &str) -> Result<ServiceStatusInfo> { fn get_service_status(&self, service: &str) -> Result<(String, String)> {
// Always fetch fresh data to get detailed metrics (memory, restarts, uptime) // Try to get status from cache first
// Note: Cache in service_status_cache only has basic active_state from discovery, if let Ok(state) = self.state.read() {
// with all detailed metrics set to None. We need fresh systemctl show data. if let Some(cached_info) = state.service_status_cache.get(service) {
let active_status = cached_info.active_state.clone();
let output = Command::new("timeout") let detailed_info = format!(
.args(&[ "LoadState={}\nActiveState={}\nSubState={}",
"2", cached_info.load_state,
"systemctl", cached_info.active_state,
"show", cached_info.sub_state
&format!("{}.service", service), );
"--property=LoadState,ActiveState,SubState,MemoryCurrent,NRestarts,ExecMainStartTimestamp" return Ok((active_status, detailed_info));
])
.output()?;
let output_str = String::from_utf8(output.stdout)?;
// Parse properties
let mut active_state = String::new();
let mut memory_bytes = None;
let mut restart_count = None;
let mut start_timestamp = None;
for line in output_str.lines() {
if let Some(value) = line.strip_prefix("ActiveState=") {
active_state = value.to_string();
} else if let Some(value) = line.strip_prefix("MemoryCurrent=") {
if value != "[not set]" {
memory_bytes = value.parse().ok();
}
} else if let Some(value) = line.strip_prefix("NRestarts=") {
restart_count = value.parse().ok();
} else if let Some(value) = line.strip_prefix("ExecMainStartTimestamp=") {
if value != "[not set]" && !value.is_empty() {
// Parse timestamp to seconds since epoch
if let Ok(output) = Command::new("date")
.args(&["+%s", "-d", value])
.output()
{
if let Ok(timestamp_str) = String::from_utf8(output.stdout) {
start_timestamp = timestamp_str.trim().parse().ok();
}
}
}
} }
} }
Ok(ServiceStatusInfo { // Fallback to systemctl if not in cache
active_state, let output = Command::new("systemctl")
memory_bytes, .args(&["is-active", &format!("{}.service", service)])
restart_count, .output()?;
start_timestamp,
}) 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"])
.output()?;
let detailed_info = String::from_utf8(output.stdout)?;
Ok((active_status, detailed_info))
} }
/// Check if service name matches pattern (supports wildcards like nginx*) /// Check if service name matches pattern (supports wildcards like nginx*)
@ -551,6 +413,75 @@ impl SystemdCollector {
true true
} }
/// Get disk usage for a specific service
async fn get_service_disk_usage(&self, service_name: &str) -> Result<f32, CollectorError> {
// Check if this service has configured directory paths
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) {
return Ok(size);
}
}
// If configured paths failed, return 0
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"])
.output()
.map_err(|e| CollectorError::SystemRead {
path: format!("WorkingDirectory for {}", service_name),
error: e.to_string(),
})?;
let output_str = String::from_utf8_lossy(&output.stdout);
for line in output_str.lines() {
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));
}
}
}
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()?;
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 {
debug!("Failed to get size for directory {}: {}", path, stderr);
}
return None;
}
let output_str = String::from_utf8(output.stdout).ok()?;
let size_str = output_str.split_whitespace().next()?;
if let Ok(size_bytes) = size_str.parse::<u64>() {
let size_gb = size_bytes as f32 / (1024.0 * 1024.0 * 1024.0);
// Return size even if very small (minimum 0.001 GB = 1MB for visibility)
if size_gb > 0.0 {
Some(size_gb.max(0.001))
} else {
None
}
} else {
None
}
}
/// Calculate service status, taking user-stopped services into account /// Calculate service status, taking user-stopped services into account
fn calculate_service_status(&self, service_name: &str, active_status: &str) -> Status { fn calculate_service_status(&self, service_name: &str, active_status: &str) -> Status {
match active_status.to_lowercase().as_str() { match active_status.to_lowercase().as_str() {
@ -568,6 +499,33 @@ impl SystemdCollector {
} }
} }
/// Get memory usage for a specific service
async fn get_service_memory_usage(&self, service_name: &str) -> Result<f32, CollectorError> {
let output = Command::new("systemctl")
.args(&["show", &format!("{}.service", service_name), "--property=MemoryCurrent"])
.output()
.map_err(|e| CollectorError::SystemRead {
path: format!("memory usage for {}", service_name),
error: e.to_string(),
})?;
let output_str = String::from_utf8_lossy(&output.stdout);
for line in output_str.lines() {
if line.starts_with("MemoryCurrent=") {
if let Some(mem_str) = line.strip_prefix("MemoryCurrent=") {
if mem_str != "[not set]" {
if let Ok(memory_bytes) = mem_str.parse::<u64>() {
return Ok(memory_bytes as f32 / (1024.0 * 1024.0)); // Convert to MB
}
}
}
}
}
Ok(0.0)
}
/// Check if service collection cache should be updated /// Check if service collection cache should be updated
fn should_update_cache(&self) -> bool { fn should_update_cache(&self) -> bool {
let state = self.state.read().unwrap(); let state = self.state.read().unwrap();
@ -820,9 +778,9 @@ impl SystemdCollector {
let mut containers = Vec::new(); let mut containers = Vec::new();
// Check if docker is available (cm-agent user is in docker group) // 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 // Use -a to show ALL containers (running and stopped)
let output = Command::new("timeout") let output = Command::new("docker")
.args(&["3", "docker", "ps", "-a", "--format", "{{.Names}},{{.Status}}"]) .args(&["ps", "-a", "--format", "{{.Names}},{{.Status}}"])
.output(); .output();
let output = match output { let output = match output {
@ -861,11 +819,11 @@ impl SystemdCollector {
} }
/// Get docker images as sub-services /// Get docker images as sub-services
fn get_docker_images(&self) -> Vec<(String, String, f32)> { fn get_docker_images(&self) -> Vec<(String, String, String, f32)> {
let mut images = Vec::new(); let mut images = Vec::new();
// Check if docker is available (cm-agent user is in docker group) with 3 second timeout // Check if docker is available (cm-agent user is in docker group)
let output = Command::new("timeout") let output = Command::new("docker")
.args(&["3", "docker", "images", "--format", "{{.Repository}}:{{.Tag}},{{.Size}}"]) .args(&["images", "--format", "{{.Repository}}:{{.Tag}},{{.Size}}"])
.output(); .output();
let output = match output { let output = match output {
@ -902,8 +860,9 @@ impl SystemdCollector {
let size_mb = self.parse_docker_size(size_str); let size_mb = self.parse_docker_size(size_str);
images.push(( images.push((
image_name.to_string(), format!("image_{}", image_name),
"inactive".to_string(), // Images are informational - use inactive for neutral display "active".to_string(), // Images are always "active" (present)
size_str.to_string(),
size_mb size_mb
)); ));
} }
@ -939,462 +898,11 @@ impl SystemdCollector {
_ => value, // Assume bytes if no unit _ => value, // Assume bytes if no unit
} }
} }
/// Get VPN external IP by querying through the vpn namespace
fn get_vpn_external_ip(&self) -> Option<String> {
let output = Command::new("timeout")
.args(&[
"5",
"sudo",
"ip",
"netns",
"exec",
"vpn",
"curl",
"-s",
"--max-time",
"4",
"https://ifconfig.me"
])
.output()
.ok()?;
if output.status.success() {
let ip = String::from_utf8_lossy(&output.stdout).trim().to_string();
if !ip.is_empty() && ip.contains('.') {
return Some(ip);
}
}
None
}
/// Get Tailscale connected peers with their connection methods
/// Returns a list of (device_name, connection_method) tuples
fn get_tailscale_peers(&self) -> Vec<(String, String)> {
match Command::new("timeout")
.args(["2", "tailscale", "status"])
.output()
{
Ok(output) if output.status.success() => {
let status_output = String::from_utf8_lossy(&output.stdout);
let mut peers = Vec::new();
// Get current hostname to filter it out
let current_hostname = gethostname::gethostname()
.to_string_lossy()
.to_string();
// Parse tailscale status output
// Format: IP hostname user os status
// Example: 100.110.98.3 wslbox cm@ linux active; direct 192.168.30.227:53757
// Note: First line is always the current host, skip it
for (idx, line) in status_output.lines().enumerate() {
if idx == 0 {
continue; // Skip first line (current host)
}
let parts: Vec<&str> = line.split_whitespace().collect();
if parts.len() < 5 {
continue; // Skip invalid lines
}
// parts[0] = IP
// parts[1] = hostname
// parts[2] = user
// parts[3] = OS
// parts[4+] = status (e.g., "active;", "direct", "192.168.30.227:53757" or "idle;" or "offline")
let hostname = parts[1];
// Skip if this is the current host (double-check in case format changes)
if hostname == current_hostname {
continue;
}
let status_parts = &parts[4..];
// Determine connection method from status
let connection_method = if status_parts.is_empty() {
continue; // Skip if no status
} else {
let status_str = status_parts.join(" ");
if status_str.contains("offline") {
continue; // Skip offline peers
} else if status_str.contains("direct") {
"direct"
} else if status_str.contains("relay") {
"relay"
} else if status_str.contains("idle") {
"idle"
} else if status_str.contains("active") {
"active"
} else {
continue; // Skip unknown status
}
};
peers.push((hostname.to_string(), connection_method.to_string()));
}
peers
}
_ => Vec::new(),
}
}
/// Get NFS exports from exportfs
/// Returns a list of (export_path, info_string) tuples
fn get_nfs_exports(&self) -> Vec<(String, String)> {
let output = match Command::new("timeout")
.args(["2", "exportfs", "-v"])
.output()
{
Ok(output) if output.status.success() => output,
_ => return Vec::new(),
};
let exports_output = String::from_utf8_lossy(&output.stdout);
let mut exports_map: std::collections::HashMap<String, Vec<(String, String)>> =
std::collections::HashMap::new();
let mut current_path: Option<String> = None;
for line in exports_output.lines() {
let trimmed = line.trim();
if trimmed.is_empty() || trimmed.starts_with('#') {
continue;
}
if trimmed.starts_with('/') {
// Export path line - may have network on same line or continuation
let parts: Vec<&str> = trimmed.splitn(2, char::is_whitespace).collect();
let path = parts[0].to_string();
current_path = Some(path.clone());
// Check if network info is on the same line
if parts.len() > 1 {
let rest = parts[1].trim();
if let Some(paren_pos) = rest.find('(') {
let network = rest[..paren_pos].trim();
if let Some(end_paren) = rest.find(')') {
let options = &rest[paren_pos+1..end_paren];
let mode = if options.contains(",rw,") || options.ends_with(",rw") {
"rw"
} else {
"ro"
};
exports_map.entry(path)
.or_insert_with(Vec::new)
.push((network.to_string(), mode.to_string()));
}
}
}
} else if let Some(ref path) = current_path {
// Continuation line with network and options
if let Some(paren_pos) = trimmed.find('(') {
let network = trimmed[..paren_pos].trim();
if let Some(end_paren) = trimmed.find(')') {
let options = &trimmed[paren_pos+1..end_paren];
let mode = if options.contains(",rw,") || options.ends_with(",rw") {
"rw"
} else {
"ro"
};
exports_map.entry(path.clone())
.or_insert_with(Vec::new)
.push((network.to_string(), mode.to_string()));
}
}
}
}
// Build display strings: "path: mode [networks]"
let mut exports: Vec<(String, String)> = exports_map
.into_iter()
.map(|(path, mut entries)| {
if entries.is_empty() {
return (path, String::new());
}
let mode = entries[0].1.clone();
let networks: Vec<String> = entries.drain(..).map(|(n, _)| n).collect();
let info = format!("{} [{}]", mode, networks.join(", "));
(path, info)
})
.collect();
exports.sort_by(|a, b| a.0.cmp(&b.0));
exports
}
/// Get SMB shares from smb.conf
/// Returns a list of (share_name, share_path) tuples
fn get_smb_shares(&self) -> Vec<(String, String)> {
match std::fs::read_to_string("/etc/samba/smb.conf") {
Ok(config) => {
let mut shares = Vec::new();
let mut current_share: Option<String> = None;
let mut current_path: Option<String> = None;
for line in config.lines() {
let line = line.trim();
// Skip comments and empty lines
if line.is_empty() || line.starts_with('#') || line.starts_with(';') {
continue;
}
// Detect share section [sharename]
if line.starts_with('[') && line.ends_with(']') {
// Save previous share if we have both name and path
if let (Some(name), Some(path)) = (current_share.take(), current_path.take()) {
// Skip special sections
if name != "global" && name != "homes" && name != "printers" {
shares.push((name, path));
}
}
// Start new share
let share_name = line[1..line.len()-1].trim().to_string();
current_share = Some(share_name);
current_path = None;
}
// Look for path = /some/path
else if line.starts_with("path") && line.contains('=') {
if let Some(path_value) = line.split('=').nth(1) {
current_path = Some(path_value.trim().to_string());
}
}
}
// Don't forget the last share
if let (Some(name), Some(path)) = (current_share, current_path) {
if name != "global" && name != "homes" && name != "printers" {
shares.push((name, path));
}
}
shares
}
_ => Vec::new(),
}
}
/// Get nftables open ports grouped by protocol
/// Returns: (tcp_ports_string, udp_ports_string)
fn get_nftables_open_ports(&self) -> (String, String) {
let output = Command::new("sudo")
.args(&["/run/current-system/sw/bin/nft", "list", "ruleset"])
.output();
let output = match output {
Ok(out) if out.status.success() => out,
Ok(out) => {
info!("nft command failed with status: {:?}, stderr: {}",
out.status, String::from_utf8_lossy(&out.stderr));
return (String::new(), String::new());
}
Err(e) => {
info!("Failed to execute nft command: {}", e);
return (String::new(), String::new());
}
};
let output_str = match String::from_utf8(output.stdout) {
Ok(s) => s,
Err(_) => {
info!("Failed to parse nft output as UTF-8");
return (String::new(), String::new());
}
};
let mut tcp_ports = std::collections::HashSet::new();
let mut udp_ports = std::collections::HashSet::new();
// Parse nftables output for WAN incoming accept rules with dport
// Looking for patterns like: tcp dport 22 accept or tcp dport { 22, 80, 443 } accept
// Only include rules in input_wan chain
let mut in_wan_chain = false;
for line in output_str.lines() {
let line = line.trim();
// Track if we're in the input_wan chain
if line.contains("chain input_wan") {
in_wan_chain = true;
continue;
}
// Reset when exiting chain (closing brace) or entering other chains
if line == "}" || (line.starts_with("chain ") && !line.contains("input_wan")) {
in_wan_chain = false;
continue;
}
// Only process rules in input_wan chain
if !in_wan_chain {
continue;
}
// Skip if not an accept rule
if !line.contains("accept") {
continue;
}
// Parse TCP ports
if line.contains("tcp dport") {
for port in self.extract_ports_from_nft_rule(line) {
tcp_ports.insert(port);
}
}
// Parse UDP ports
if line.contains("udp dport") {
for port in self.extract_ports_from_nft_rule(line) {
udp_ports.insert(port);
}
}
}
// Sort and format
let mut tcp_vec: Vec<u16> = tcp_ports.into_iter().collect();
let mut udp_vec: Vec<u16> = udp_ports.into_iter().collect();
tcp_vec.sort();
udp_vec.sort();
let tcp_str = tcp_vec.iter().map(|p| p.to_string()).collect::<Vec<_>>().join(", ");
let udp_str = udp_vec.iter().map(|p| p.to_string()).collect::<Vec<_>>().join(", ");
info!("nftables WAN ports - TCP: '{}', UDP: '{}'", tcp_str, udp_str);
(tcp_str, udp_str)
}
/// Extract port numbers from nftables rule line
/// Returns vector of ports (handles both single ports and sets)
fn extract_ports_from_nft_rule(&self, line: &str) -> Vec<u16> {
let mut ports = Vec::new();
// Pattern: "tcp dport 22 accept" or "tcp dport { 22, 80, 443 } accept"
if let Some(dport_pos) = line.find("dport") {
let after_dport = &line[dport_pos + 5..].trim();
// Handle port sets like { 22, 80, 443 }
if after_dport.starts_with('{') {
if let Some(end_brace) = after_dport.find('}') {
let ports_str = &after_dport[1..end_brace];
// Parse each port in the set
for port_str in ports_str.split(',') {
if let Ok(port) = port_str.trim().parse::<u16>() {
ports.push(port);
}
}
}
} else {
// Single port
if let Some(port_str) = after_dport.split_whitespace().next() {
if let Ok(port) = port_str.parse::<u16>() {
ports.push(port);
}
}
}
}
ports
}
/// Get aggregate qBittorrent torrent statistics
/// Returns: (active_count, download_mbps, upload_mbps)
fn get_qbittorrent_stats(&self) -> Option<(u32, f32, f32)> {
// Query qBittorrent API through VPN namespace
let output = Command::new("timeout")
.args(&[
"5",
"sudo",
"ip",
"netns",
"exec",
"vpn",
"curl",
"-s",
"--max-time",
"4",
"http://localhost:8080/api/v2/torrents/info"
])
.output()
.ok()?;
if !output.status.success() {
return None;
}
let output_str = String::from_utf8_lossy(&output.stdout);
let torrents: Vec<serde_json::Value> = serde_json::from_str(&output_str).ok()?;
let mut active_count = 0u32;
let mut total_download_bps = 0.0f64;
let mut total_upload_bps = 0.0f64;
for torrent in torrents {
let state = torrent["state"].as_str().unwrap_or("");
let dlspeed = torrent["dlspeed"].as_f64().unwrap_or(0.0);
let upspeed = torrent["upspeed"].as_f64().unwrap_or(0.0);
// States: downloading, uploading, stalledDL, stalledUP, queuedDL, queuedUP, pausedDL, pausedUP
// Count as active if downloading or uploading (seeding)
if state.contains("downloading") || state.contains("uploading") ||
state == "stalledDL" || state == "stalledUP" {
active_count += 1;
}
total_download_bps += dlspeed;
total_upload_bps += upspeed;
}
// qBittorrent returns bytes/s, convert to MB/s
let download_mbps = (total_download_bps / 1024.0 / 1024.0) as f32;
let upload_mbps = (total_upload_bps / 1024.0 / 1024.0) as f32;
Some((active_count, download_mbps, upload_mbps))
}
/// Check for active torrent copy operations
/// Returns: Vec of filenames currently being copied
fn get_active_torrent_copies(&self) -> Vec<String> {
let marker_dir = "/tmp/torrent-copy";
let mut active_copies = Vec::new();
// Read all marker files from directory
if let Ok(entries) = std::fs::read_dir(marker_dir) {
for entry in entries.flatten() {
if let Ok(file_type) = entry.file_type() {
if file_type.is_file() {
// Filename is the marker (sanitized torrent name)
if let Some(filename) = entry.file_name().to_str() {
// Convert sanitized name back (replace _ with /)
let display_name = filename.replace('_', "/");
active_copies.push(display_name);
}
}
}
}
}
active_copies
}
} }
#[async_trait] #[async_trait]
impl Collector for SystemdCollector { impl Collector for SystemdCollector {
async fn collect_structured(&self, agent_data: &mut AgentData) -> Result<(), CollectorError> { async fn collect_structured(&self, agent_data: &mut AgentData) -> Result<(), CollectorError> {
// Clear services to prevent duplicates when updating cached data
agent_data.services.clear();
// Use cached complete data if available and fresh // Use cached complete data if available and fresh
if let Some(cached_complete_services) = self.get_cached_complete_services() { if let Some(cached_complete_services) = self.get_cached_complete_services() {
for service_data in cached_complete_services { for service_data in cached_complete_services {

View File

@ -5,9 +5,10 @@ use zmq::{Context, Socket, SocketType};
use crate::config::ZmqConfig; use crate::config::ZmqConfig;
/// ZMQ communication handler for publishing metrics /// ZMQ communication handler for publishing metrics and receiving commands
pub struct ZmqHandler { pub struct ZmqHandler {
publisher: Socket, publisher: Socket,
command_receiver: Socket,
} }
impl ZmqHandler { impl ZmqHandler {
@ -25,8 +26,20 @@ impl ZmqHandler {
publisher.set_sndhwm(1000)?; // High water mark for outbound messages publisher.set_sndhwm(1000)?; // High water mark for outbound messages
publisher.set_linger(1000)?; // Linger time on close publisher.set_linger(1000)?; // Linger time on close
// Create command receiver socket (PULL socket to receive commands from dashboard)
let command_receiver = context.socket(SocketType::PULL)?;
let cmd_bind_address = format!("tcp://{}:{}", config.bind_address, config.command_port);
command_receiver.bind(&cmd_bind_address)?;
info!("ZMQ command receiver bound to {}", cmd_bind_address);
// Set non-blocking mode for command receiver
command_receiver.set_rcvtimeo(0)?; // Non-blocking receive
command_receiver.set_linger(1000)?;
Ok(Self { Ok(Self {
publisher, publisher,
command_receiver,
}) })
} }
@ -52,4 +65,36 @@ impl ZmqHandler {
Ok(()) Ok(())
} }
/// Try to receive a command (non-blocking)
pub fn try_receive_command(&self) -> Result<Option<AgentCommand>> {
match self.command_receiver.recv_bytes(zmq::DONTWAIT) {
Ok(bytes) => {
debug!("Received command message ({} bytes)", bytes.len());
let command: AgentCommand = serde_json::from_slice(&bytes)
.map_err(|e| anyhow::anyhow!("Failed to deserialize command: {}", e))?;
debug!("Parsed command: {:?}", command);
Ok(Some(command))
}
Err(zmq::Error::EAGAIN) => {
// No message available (non-blocking)
Ok(None)
}
Err(e) => Err(anyhow::anyhow!("ZMQ receive error: {}", e)),
}
}
}
/// Commands that can be sent to the agent
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
pub enum AgentCommand {
/// Request immediate metric collection
CollectNow,
/// Change collection interval
SetInterval { seconds: u64 },
/// Enable/disable a collector
ToggleCollector { name: String, enabled: bool },
/// Request status/health check
Ping,
} }

View File

@ -13,12 +13,14 @@ pub struct AgentConfig {
pub collectors: CollectorConfig, pub collectors: CollectorConfig,
pub cache: CacheConfig, pub cache: CacheConfig,
pub notifications: NotificationConfig, pub notifications: NotificationConfig,
pub collection_interval_seconds: u64,
} }
/// ZMQ communication configuration /// ZMQ communication configuration
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ZmqConfig { pub struct ZmqConfig {
pub publisher_port: u16, pub publisher_port: u16,
pub command_port: u16,
pub bind_address: String, pub bind_address: String,
pub transmission_interval_seconds: u64, pub transmission_interval_seconds: u64,
/// Heartbeat transmission interval in seconds for host connectivity detection /// Heartbeat transmission interval in seconds for host connectivity detection

View File

@ -7,13 +7,21 @@ pub fn validate_config(config: &AgentConfig) -> Result<()> {
bail!("ZMQ publisher port cannot be 0"); bail!("ZMQ publisher port cannot be 0");
} }
if config.zmq.command_port == 0 {
bail!("ZMQ command port cannot be 0");
}
if config.zmq.publisher_port == config.zmq.command_port {
bail!("ZMQ publisher and command ports cannot be the same");
}
if config.zmq.bind_address.is_empty() { if config.zmq.bind_address.is_empty() {
bail!("ZMQ bind address cannot be empty"); bail!("ZMQ bind address cannot be empty");
} }
// Validate ZMQ transmission interval // Validate collection interval
if config.zmq.transmission_interval_seconds == 0 { if config.collection_interval_seconds == 0 {
bail!("ZMQ transmission interval cannot be 0"); bail!("Collection interval cannot be 0");
} }
// Validate CPU thresholds // Validate CPU thresholds

View File

@ -1,6 +1,6 @@
[package] [package]
name = "cm-dashboard" name = "cm-dashboard"
version = "0.1.275" version = "0.1.186"
edition = "2021" edition = "2021"
[dependencies] [dependencies]

View File

@ -1,10 +1,10 @@
use anyhow::Result; use anyhow::Result;
use crossterm::{ use crossterm::{
event::{self, EnableMouseCapture, DisableMouseCapture, Event, MouseEvent, MouseEventKind, MouseButton}, event::{self},
execute, execute,
terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen}, terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
}; };
use ratatui::{backend::CrosstermBackend, Terminal, layout::Rect}; use ratatui::{backend::CrosstermBackend, Terminal};
use std::io; use std::io;
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
use tracing::{debug, error, info, warn}; use tracing::{debug, error, info, warn};
@ -22,9 +22,6 @@ pub struct Dashboard {
headless: bool, headless: bool,
initial_commands_sent: std::collections::HashSet<String>, initial_commands_sent: std::collections::HashSet<String>,
config: DashboardConfig, config: DashboardConfig,
title_area: Rect, // Store title area for mouse event handling
system_area: Rect, // Store system area for mouse event handling
services_area: Rect, // Store services area for mouse event handling
} }
impl Dashboard { impl Dashboard {
@ -95,7 +92,7 @@ impl Dashboard {
} }
let mut stdout = io::stdout(); let mut stdout = io::stdout();
if let Err(e) = execute!(stdout, EnterAlternateScreen, EnableMouseCapture) { if let Err(e) = execute!(stdout, EnterAlternateScreen) {
error!("Failed to enter alternate screen: {}", e); error!("Failed to enter alternate screen: {}", e);
let _ = disable_raw_mode(); let _ = disable_raw_mode();
return Err(e.into()); return Err(e.into());
@ -124,9 +121,6 @@ impl Dashboard {
headless, headless,
initial_commands_sent: std::collections::HashSet::new(), initial_commands_sent: std::collections::HashSet::new(),
config, config,
title_area: Rect::default(),
system_area: Rect::default(),
services_area: Rect::default(),
}) })
} }
@ -138,45 +132,27 @@ impl Dashboard {
let metrics_check_interval = Duration::from_millis(100); // Check for metrics every 100ms let metrics_check_interval = Duration::from_millis(100); // Check for metrics every 100ms
let mut last_heartbeat_check = Instant::now(); let mut last_heartbeat_check = Instant::now();
let heartbeat_check_interval = Duration::from_secs(1); // Check for host connectivity every 1 second let heartbeat_check_interval = Duration::from_secs(1); // Check for host connectivity every 1 second
let mut needs_render = true; // Track if we need to render
loop { loop {
// Handle terminal events (keyboard and mouse input) only if not headless // Handle terminal events (keyboard input) only if not headless
if !self.headless { if !self.headless {
match event::poll(Duration::from_millis(200)) { match event::poll(Duration::from_millis(50)) {
Ok(true) => { Ok(true) => {
match event::read() { match event::read() {
Ok(event) => { Ok(event) => {
if let Some(ref mut tui_app) = self.tui_app { if let Some(ref mut tui_app) = self.tui_app {
match event { // Handle input
Event::Key(_) => { match tui_app.handle_input(event) {
// Handle keyboard input Ok(_) => {
match tui_app.handle_input(event) { // Check if we should quit
Ok(_) => { if tui_app.should_quit() {
needs_render = true; info!("Quit requested, exiting dashboard");
// Check if we should quit break;
if tui_app.should_quit() {
info!("Quit requested, exiting dashboard");
break;
}
}
Err(e) => {
error!("Error handling input: {}", e);
}
} }
} }
Event::Mouse(mouse_event) => { Err(e) => {
// Handle mouse events error!("Error handling input: {}", e);
if let Err(e) = self.handle_mouse_event(mouse_event) {
error!("Error handling mouse event: {}", e);
}
needs_render = true;
} }
Event::Resize(_width, _height) => {
// Terminal was resized - mark for re-render
needs_render = true;
}
_ => {}
} }
} }
} }
@ -192,6 +168,17 @@ impl Dashboard {
break; break;
} }
} }
// Render UI immediately after handling input for responsive feedback
if let Some(ref mut terminal) = self.terminal {
if let Some(ref mut tui_app) = self.tui_app {
if let Err(e) = terminal.draw(|frame| {
tui_app.render(frame, &self.metric_store);
}) {
error!("Error rendering TUI after input: {}", e);
}
}
}
} }
// Check for new metrics // Check for new metrics
@ -230,8 +217,6 @@ impl Dashboard {
if let Some(ref mut tui_app) = self.tui_app { if let Some(ref mut tui_app) = self.tui_app {
tui_app.update_metrics(&mut self.metric_store); tui_app.update_metrics(&mut self.metric_store);
} }
needs_render = true; // New metrics received, need to render
} }
// Also check for command output messages // Also check for command output messages
@ -260,416 +245,31 @@ impl Dashboard {
tui_app.update_hosts(connected_hosts); tui_app.update_hosts(connected_hosts);
} }
last_heartbeat_check = Instant::now(); last_heartbeat_check = Instant::now();
needs_render = true; // Heartbeat check happened, may have changed hosts
} }
// Render TUI only when needed (not headless and something changed) // Render TUI (only if not headless)
if !self.headless && needs_render { if !self.headless {
if let Some(ref mut terminal) = self.terminal { if let Some(ref mut terminal) = self.terminal {
if let Some(ref mut tui_app) = self.tui_app { if let Some(ref mut tui_app) = self.tui_app {
// Clear and autoresize terminal to handle any resize events if let Err(e) = terminal.draw(|frame| {
if let Err(e) = terminal.autoresize() { tui_app.render(frame, &self.metric_store);
warn!("Error autoresizing terminal: {}", e);
}
// Check minimum terminal size to prevent panics
let size = terminal.size().unwrap_or_default();
if size.width < 90 || size.height < 15 {
// Terminal too small, show error message
let msg_text = format!("Terminal too small\n\nMinimum: 90x15\nCurrent: {}x{}", size.width, size.height);
let _ = terminal.draw(|frame| {
use ratatui::widgets::{Paragraph, Block, Borders};
use ratatui::layout::Alignment;
let msg = Paragraph::new(msg_text.clone())
.alignment(Alignment::Center)
.block(Block::default().borders(Borders::ALL));
frame.render_widget(msg, frame.size());
});
} else if let Err(e) = terminal.draw(|frame| {
let (title_area, system_area, services_area) = tui_app.render(frame, &self.metric_store);
self.title_area = title_area;
self.system_area = system_area;
self.services_area = services_area;
}) { }) {
error!("Error rendering TUI: {}", e); error!("Error rendering TUI: {}", e);
break; break;
} }
} }
} }
needs_render = false; // Reset flag after rendering
} }
// Small sleep to prevent excessive CPU usage
tokio::time::sleep(Duration::from_millis(10)).await;
} }
info!("Dashboard main loop ended"); info!("Dashboard main loop ended");
Ok(()) Ok(())
} }
/// Handle mouse events
fn handle_mouse_event(&mut self, mouse: MouseEvent) -> Result<()> {
let x = mouse.column;
let y = mouse.row;
// Handle popup menu if open
let popup_info = if let Some(ref tui_app) = self.tui_app {
tui_app.popup_menu.clone().map(|popup| {
let hostname = tui_app.current_host.clone();
(popup, hostname)
})
} else {
None
};
if let Some((popup, hostname)) = popup_info {
// Calculate popup bounds using screen coordinates
let popup_width = 20;
let popup_height = 5; // 3 items + 2 borders
// Get terminal size
let (screen_width, screen_height) = if let Some(ref terminal) = self.terminal {
let size = terminal.size().unwrap_or_default();
(size.width, size.height)
} else {
(80, 24) // fallback
};
let popup_x = if popup.x + popup_width < screen_width {
popup.x
} else {
screen_width.saturating_sub(popup_width)
};
let popup_y = if popup.y + popup_height < screen_height {
popup.y
} else {
screen_height.saturating_sub(popup_height)
};
let popup_area = Rect {
x: popup_x,
y: popup_y,
width: popup_width,
height: popup_height,
};
// Update selected index on mouse move
if matches!(mouse.kind, MouseEventKind::Moved) {
if is_in_area(x, y, &popup_area) {
let relative_y = y.saturating_sub(popup_y + 1) as usize; // +1 for top border
if relative_y < 3 {
if let Some(ref mut tui_app) = self.tui_app {
if let Some(ref mut popup) = tui_app.popup_menu {
popup.selected_index = relative_y;
}
}
}
}
return Ok(());
}
if matches!(mouse.kind, MouseEventKind::Down(MouseButton::Left)) {
if is_in_area(x, y, &popup_area) {
// Click inside popup - execute action
let relative_y = y.saturating_sub(popup_y + 1) as usize; // +1 for top border
if relative_y < 3 {
// Execute the selected action
self.execute_service_action(relative_y, &popup.service_name, hostname.as_deref())?;
}
// Close popup after action
if let Some(ref mut tui_app) = self.tui_app {
tui_app.popup_menu = None;
}
return Ok(());
} else {
// Click outside popup - close it
if let Some(ref mut tui_app) = self.tui_app {
tui_app.popup_menu = None;
}
return Ok(());
}
}
// Any other event while popup is open - don't process panels
return Ok(());
}
// Check for title bar clicks (host selection)
if matches!(mouse.kind, MouseEventKind::Down(MouseButton::Left)) {
if is_in_area(x, y, &self.title_area) {
// Click in title bar - check if it's on a hostname
// The title bar has "cm-dashboard vX.X.X" on the left (22 chars)
// Then hostnames start at position 22
if x >= 22 {
let hostname = self.find_hostname_at_position(x);
if let Some(host) = hostname {
if let Some(ref mut tui_app) = self.tui_app {
tui_app.switch_to_host(&host);
}
}
}
return Ok(());
}
}
// Determine which panel the mouse is over
let in_system_area = is_in_area(x, y, &self.system_area);
let in_services_area = is_in_area(x, y, &self.services_area);
if !in_system_area && !in_services_area {
return Ok(());
}
// Handle mouse events
match mouse.kind {
MouseEventKind::ScrollDown => {
if in_system_area {
// Scroll down in system panel
if let Some(ref mut tui_app) = self.tui_app {
if let Some(hostname) = tui_app.current_host.clone() {
let host_widgets = tui_app.get_or_create_host_widgets(&hostname);
let visible_height = self.system_area.height as usize;
let total_lines = host_widgets.system_widget.get_total_lines();
host_widgets.system_widget.scroll_down(visible_height, total_lines);
}
}
} else if in_services_area {
// Scroll down in services panel
if let Some(ref mut tui_app) = self.tui_app {
if let Some(hostname) = tui_app.current_host.clone() {
let host_widgets = tui_app.get_or_create_host_widgets(&hostname);
// Calculate visible height (panel height - borders and header)
let visible_height = self.services_area.height.saturating_sub(3) as usize;
host_widgets.services_widget.scroll_down(visible_height);
}
}
}
}
MouseEventKind::ScrollUp => {
if in_system_area {
// Scroll up in system panel
if let Some(ref mut tui_app) = self.tui_app {
if let Some(hostname) = tui_app.current_host.clone() {
let host_widgets = tui_app.get_or_create_host_widgets(&hostname);
host_widgets.system_widget.scroll_up();
}
}
} else if in_services_area {
// Scroll up in services panel
if let Some(ref mut tui_app) = self.tui_app {
if let Some(hostname) = tui_app.current_host.clone() {
let host_widgets = tui_app.get_or_create_host_widgets(&hostname);
host_widgets.services_widget.scroll_up();
}
}
}
}
MouseEventKind::Down(button) => {
// Only handle clicks in services area (not system area)
if !in_services_area {
return Ok(());
}
// Calculate which service was clicked
// The services area includes a border, so we need to account for that
let relative_y = y.saturating_sub(self.services_area.y + 2) as usize; // +2 for border and header
if let Some(ref mut tui_app) = self.tui_app {
if let Some(hostname) = tui_app.current_host.clone() {
let host_widgets = tui_app.get_or_create_host_widgets(&hostname);
// Account for scroll offset - the clicked line is relative to viewport
let display_line_index = host_widgets.services_widget.scroll_offset + relative_y;
// Map display line to parent service index
if let Some(parent_index) = host_widgets.services_widget.display_line_to_parent_index(display_line_index) {
// Set the selected index to the clicked parent service
host_widgets.services_widget.selected_index = parent_index;
match button {
MouseButton::Left => {
// Left click just selects the service
debug!("Left-clicked service at display line {} (parent index: {})", display_line_index, parent_index);
}
MouseButton::Right => {
// Right click opens context menu
debug!("Right-clicked service at display line {} (parent index: {})", display_line_index, parent_index);
// Get the service name for the popup
if let Some(service_name) = host_widgets.services_widget.get_selected_service() {
tui_app.popup_menu = Some(crate::ui::PopupMenu {
service_name,
x,
y,
selected_index: 0,
});
}
}
_ => {}
}
}
}
}
}
_ => {}
}
Ok(())
}
/// Execute service action from popup menu
fn execute_service_action(&self, action_index: usize, service_name: &str, hostname: Option<&str>) -> Result<()> {
let Some(hostname) = hostname else {
return Ok(());
};
let connection_ip = self.get_connection_ip(hostname);
match action_index {
0 => {
// Start Service
let service_start_command = format!(
"echo 'Starting service: {} on {}' && ssh -tt {}@{} \"bash -ic '{} start {}'\"",
service_name,
hostname,
self.config.ssh.rebuild_user,
connection_ip,
self.config.ssh.service_manage_cmd,
service_name
);
std::process::Command::new("tmux")
.arg("split-window")
.arg("-v")
.arg("-p")
.arg("30")
.arg(&service_start_command)
.spawn()
.ok();
}
1 => {
// Stop Service
let service_stop_command = format!(
"echo 'Stopping service: {} on {}' && ssh -tt {}@{} \"bash -ic '{} stop {}'\"",
service_name,
hostname,
self.config.ssh.rebuild_user,
connection_ip,
self.config.ssh.service_manage_cmd,
service_name
);
std::process::Command::new("tmux")
.arg("split-window")
.arg("-v")
.arg("-p")
.arg("30")
.arg(&service_stop_command)
.spawn()
.ok();
}
2 => {
// View Logs
let logs_command = format!(
"ssh -tt {}@{} '{} logs {}'",
self.config.ssh.rebuild_user,
connection_ip,
self.config.ssh.service_manage_cmd,
service_name
);
std::process::Command::new("tmux")
.arg("split-window")
.arg("-v")
.arg("-p")
.arg("30")
.arg(&logs_command)
.spawn()
.ok();
}
_ => {}
}
Ok(())
}
/// Get connection IP for a host
fn get_connection_ip(&self, hostname: &str) -> String {
self.config
.hosts
.get(hostname)
.and_then(|h| h.ip.clone())
.unwrap_or_else(|| hostname.to_string())
}
/// Find which hostname is at a given x position in the title bar
fn find_hostname_at_position(&self, x: u16) -> Option<String> {
if let Some(ref tui_app) = self.tui_app {
// The hosts are RIGHT-ALIGNED in chunks[1]!
// Need to calculate total width first, then right-align
// Get terminal width
let terminal_width = if let Some(ref terminal) = self.terminal {
terminal.size().unwrap_or_default().width
} else {
80
};
// Calculate total width of all host text
let mut total_width = 0_u16;
for (i, host) in tui_app.get_available_hosts().iter().enumerate() {
if i > 0 {
total_width += 1; // space between hosts
}
total_width += 2; // icon + space
let is_selected = Some(host) == tui_app.current_host.as_ref();
if is_selected {
total_width += 1 + host.len() as u16 + 1; // [hostname]
} else {
total_width += host.len() as u16;
}
}
total_width += 1; // right padding
// chunks[1] starts at 22, has width of (terminal_width - 22)
let chunk_width = terminal_width - 22;
// Right-aligned position
let hosts_start_x = if total_width < chunk_width {
22 + (chunk_width - total_width)
} else {
22
};
// Now calculate positions starting from hosts_start_x
let mut pos = hosts_start_x;
for (i, host) in tui_app.get_available_hosts().iter().enumerate() {
if i > 0 {
pos += 1; // " "
}
let host_start = pos;
pos += 2; // "● "
let is_selected = Some(host) == tui_app.current_host.as_ref();
if is_selected {
pos += 1 + host.len() as u16 + 1; // [hostname]
} else {
pos += host.len() as u16;
}
if x >= host_start && x < pos {
return Some(host.clone());
}
}
}
None
}
}
/// Check if a point is within a rectangular area
fn is_in_area(x: u16, y: u16, area: &Rect) -> bool {
x >= area.x && x < area.x + area.width
&& y >= area.y && y < area.y + area.height
} }
impl Drop for Dashboard { impl Drop for Dashboard {
@ -678,7 +278,7 @@ impl Drop for Dashboard {
if !self.headless { if !self.headless {
let _ = disable_raw_mode(); let _ = disable_raw_mode();
if let Some(ref mut terminal) = self.terminal { if let Some(ref mut terminal) = self.terminal {
let _ = execute!(terminal.backend_mut(), LeaveAlternateScreen, DisableMouseCapture); let _ = execute!(terminal.backend_mut(), LeaveAlternateScreen);
let _ = terminal.show_cursor(); let _ = terminal.show_cursor();
} }
} }

View File

@ -86,6 +86,16 @@ impl MetricStore {
self.current_agent_data.get(hostname) 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) /// Get connected hosts (hosts with recent heartbeats)
pub fn get_connected_hosts(&self, timeout: Duration) -> Vec<String> { pub fn get_connected_hosts(&self, timeout: Duration) -> Vec<String> {
let now = Instant::now(); let now = Instant::now();

View File

@ -17,7 +17,7 @@ pub mod widgets;
use crate::config::DashboardConfig; use crate::config::DashboardConfig;
use crate::metrics::MetricStore; use crate::metrics::MetricStore;
use cm_dashboard_shared::Status; use cm_dashboard_shared::Status;
use theme::{Components, Layout as ThemeLayout, Theme}; use theme::{Components, Layout as ThemeLayout, Theme, Typography};
use widgets::{ServicesWidget, SystemWidget, Widget}; use widgets::{ServicesWidget, SystemWidget, Widget};
@ -47,21 +47,12 @@ impl HostWidgets {
} }
/// Popup menu state
#[derive(Clone)]
pub struct PopupMenu {
pub service_name: String,
pub x: u16,
pub y: u16,
pub selected_index: usize,
}
/// Main TUI application /// Main TUI application
pub struct TuiApp { pub struct TuiApp {
/// Widget states per host (hostname -> HostWidgets) /// Widget states per host (hostname -> HostWidgets)
host_widgets: HashMap<String, HostWidgets>, host_widgets: HashMap<String, HostWidgets>,
/// Current active host /// Current active host
pub current_host: Option<String>, current_host: Option<String>,
/// Available hosts /// Available hosts
available_hosts: Vec<String>, available_hosts: Vec<String>,
/// Host index for navigation /// Host index for navigation
@ -74,8 +65,6 @@ pub struct TuiApp {
config: DashboardConfig, config: DashboardConfig,
/// Cached localhost hostname to avoid repeated system calls /// Cached localhost hostname to avoid repeated system calls
localhost: String, localhost: String,
/// Active popup menu (if any)
pub popup_menu: Option<PopupMenu>,
} }
impl TuiApp { impl TuiApp {
@ -90,7 +79,6 @@ impl TuiApp {
user_navigated_away: false, user_navigated_away: false,
config, config,
localhost, localhost,
popup_menu: None,
}; };
// Sort predefined hosts // Sort predefined hosts
@ -105,7 +93,7 @@ impl TuiApp {
} }
/// Get or create host widgets for the given hostname /// Get or create host widgets for the given hostname
pub fn get_or_create_host_widgets(&mut self, hostname: &str) -> &mut HostWidgets { fn get_or_create_host_widgets(&mut self, hostname: &str) -> &mut HostWidgets {
self.host_widgets self.host_widgets
.entry(hostname.to_string()) .entry(hostname.to_string())
.or_insert_with(HostWidgets::new) .or_insert_with(HostWidgets::new)
@ -122,6 +110,14 @@ impl TuiApp {
host_widgets.system_widget.update_from_agent_data(agent_data); host_widgets.system_widget.update_from_agent_data(agent_data);
host_widgets.services_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()); host_widgets.last_update = Some(Instant::now());
} }
} }
@ -171,14 +167,6 @@ impl TuiApp {
/// Handle keyboard input /// Handle keyboard input
pub fn handle_input(&mut self, event: Event) -> Result<()> { pub fn handle_input(&mut self, event: Event) -> Result<()> {
if let Event::Key(key) = event { if let Event::Key(key) = event {
// Close popup on Escape
if matches!(key.code, KeyCode::Esc) {
if self.popup_menu.is_some() {
self.popup_menu = None;
return Ok(());
}
}
match key.code { match key.code {
KeyCode::Char('q') => { KeyCode::Char('q') => {
self.should_quit = true; self.should_quit = true;
@ -383,23 +371,6 @@ impl TuiApp {
Ok(()) Ok(())
} }
/// Switch to a specific host by name
pub fn switch_to_host(&mut self, hostname: &str) {
if let Some(index) = self.available_hosts.iter().position(|h| h == hostname) {
self.host_index = index;
self.current_host = Some(hostname.to_string());
// Check if user navigated away from localhost
if hostname != &self.localhost {
self.user_navigated_away = true;
} else {
self.user_navigated_away = false; // User navigated back to localhost
}
info!("Switched to host: {}", hostname);
}
}
/// Navigate between hosts /// Navigate between hosts
fn navigate_host(&mut self, direction: i32) { fn navigate_host(&mut self, direction: i32) {
if self.available_hosts.is_empty() { if self.available_hosts.is_empty() {
@ -445,10 +416,6 @@ impl TuiApp {
None None
} }
/// Get the list of available hosts
pub fn get_available_hosts(&self) -> &Vec<String> {
&self.available_hosts
}
/// Should quit application /// Should quit application
pub fn should_quit(&self) -> bool { pub fn should_quit(&self) -> bool {
@ -462,7 +429,7 @@ impl TuiApp {
/// Render the dashboard (real btop-style multi-panel layout) /// Render the dashboard (real btop-style multi-panel layout)
pub fn render(&mut self, frame: &mut Frame, metric_store: &MetricStore) -> (Rect, Rect, Rect) { pub fn render(&mut self, frame: &mut Frame, metric_store: &MetricStore) {
let size = frame.size(); let size = frame.size();
// Clear background to true black like btop // Clear background to true black like btop
@ -502,8 +469,8 @@ impl TuiApp {
if current_host_offline { if current_host_offline {
self.render_offline_host_message(frame, main_chunks[1]); self.render_offline_host_message(frame, main_chunks[1]);
self.render_btop_title(frame, main_chunks[0], metric_store); self.render_btop_title(frame, main_chunks[0], metric_store);
self.render_statusbar(frame, main_chunks[2], metric_store); self.render_statusbar(frame, main_chunks[2]);
return (main_chunks[0], Rect::default(), Rect::default()); // Return title area and empty areas when offline return;
} }
// Left side: system panel only (full height) // Left side: system panel only (full height)
@ -516,29 +483,20 @@ impl TuiApp {
self.render_btop_title(frame, main_chunks[0], metric_store); self.render_btop_title(frame, main_chunks[0], metric_store);
// Render system panel // Render system panel
let system_area = left_chunks[0]; self.render_system_panel(frame, left_chunks[0], metric_store);
self.render_system_panel(frame, system_area, metric_store);
// Render services widget for current host // Render services widget for current host
let services_area = content_chunks[1];
if let Some(hostname) = self.current_host.clone() { if let Some(hostname) = self.current_host.clone() {
let is_focused = true; // Always show service selection let is_focused = true; // Always show service selection
let host_widgets = self.get_or_create_host_widgets(&hostname); let host_widgets = self.get_or_create_host_widgets(&hostname);
host_widgets host_widgets
.services_widget .services_widget
.render(frame, services_area, is_focused); // Services takes full right side .render(frame, content_chunks[1], is_focused); // Services takes full right side
} }
// Render statusbar at the bottom // Render statusbar at the bottom
self.render_statusbar(frame, main_chunks[2], metric_store); self.render_statusbar(frame, main_chunks[2]); // main_chunks[2] is the statusbar area
// Render popup menu on top of everything if active
if let Some(ref popup) = self.popup_menu {
self.render_popup_menu(frame, popup);
}
// Return all areas for mouse event handling
(main_chunks[0], system_area, services_area)
} }
/// Render btop-style minimal title with host status colors /// Render btop-style minimal title with host status colors
@ -606,14 +564,7 @@ impl TuiApp {
)); ));
if Some(host) == self.current_host.as_ref() { if Some(host) == self.current_host.as_ref() {
// Selected host with brackets in bold background color against status background // Selected host in bold background color against status background
host_spans.push(Span::styled(
"[",
Style::default()
.fg(Theme::background())
.bg(background_color)
.add_modifier(Modifier::BOLD),
));
host_spans.push(Span::styled( host_spans.push(Span::styled(
host.clone(), host.clone(),
Style::default() Style::default()
@ -621,13 +572,6 @@ impl TuiApp {
.bg(background_color) .bg(background_color)
.add_modifier(Modifier::BOLD), .add_modifier(Modifier::BOLD),
)); ));
host_spans.push(Span::styled(
"]",
Style::default()
.fg(Theme::background())
.bg(background_color)
.add_modifier(Modifier::BOLD),
));
} else { } else {
// Other hosts in normal background color against status background // Other hosts in normal background color against status background
host_spans.push(Span::styled( host_spans.push(Span::styled(
@ -661,137 +605,36 @@ impl TuiApp {
} }
} }
/// Render popup menu for service actions /// Render dynamic statusbar with context-aware shortcuts
fn render_popup_menu(&self, frame: &mut Frame, popup: &PopupMenu) { fn render_statusbar(&self, frame: &mut Frame, area: Rect) {
use ratatui::widgets::{Block, Borders, Clear, List, ListItem}; let shortcuts = self.get_context_shortcuts();
use ratatui::style::{Color, Modifier}; let statusbar_text = shortcuts.join("");
// Menu items let statusbar = Paragraph::new(statusbar_text)
let items = vec![ .style(Typography::secondary())
"Start Service", .alignment(ratatui::layout::Alignment::Center);
"Stop Service",
"View Logs",
];
// Calculate popup size
let width = 20;
let height = items.len() as u16 + 2; // +2 for borders
// Position popup near click location, but keep it on screen
let screen_width = frame.size().width;
let screen_height = frame.size().height;
let x = if popup.x + width < screen_width {
popup.x
} else {
screen_width.saturating_sub(width)
};
let y = if popup.y + height < screen_height {
popup.y
} else {
screen_height.saturating_sub(height)
};
let popup_area = Rect {
x,
y,
width,
height,
};
// Create menu items with selection highlight
let menu_items: Vec<ListItem> = items
.iter()
.enumerate()
.map(|(i, item)| {
let style = if i == popup.selected_index {
Style::default()
.fg(Color::Black)
.bg(Color::White)
.add_modifier(Modifier::BOLD)
} else {
Style::default().fg(Theme::primary_text())
};
ListItem::new(*item).style(style)
})
.collect();
let menu_list = List::new(menu_items)
.block(
Block::default()
.borders(Borders::ALL)
.style(Style::default().bg(Theme::background()).fg(Theme::primary_text()))
);
// Clear the area and render menu
frame.render_widget(Clear, popup_area);
frame.render_widget(menu_list, popup_area);
}
/// Render statusbar with host and client IPs
fn render_statusbar(&self, frame: &mut Frame, area: Rect, _metric_store: &MetricStore) {
use ratatui::text::{Line, Span};
use ratatui::widgets::Paragraph;
// Get current host info
let (hostname_str, host_ip, build_version, agent_version) = if let Some(hostname) = &self.current_host {
// Get the connection IP (the IP dashboard uses to connect to the agent)
let ip = if let Some(host_details) = self.config.hosts.get(hostname) {
host_details.get_connection_ip(hostname)
} else {
hostname.clone()
};
// Get build and agent versions from system widget
let (build, agent) = if let Some(host_widgets) = self.host_widgets.get(hostname) {
let build = host_widgets.system_widget.get_build_version().unwrap_or("N/A".to_string());
let agent = host_widgets.system_widget.get_agent_version().unwrap_or("N/A".to_string());
(build, agent)
} else {
("N/A".to_string(), "N/A".to_string())
};
(hostname.clone(), ip, build, agent)
} else {
("None".to_string(), "N/A".to_string(), "N/A".to_string(), "N/A".to_string())
};
let left_text = format!("Host: {} | {} | Build:{} | Agent:{}", hostname_str, host_ip, build_version, agent_version);
// Get dashboard local IP
let dashboard_ip = Self::get_local_ip();
let right_text = format!("Dashboard: {}", dashboard_ip);
// Calculate spacing to push right text to the right (accounting for 1 char left padding)
let spacing = area.width as usize - left_text.len() - right_text.len() - 2; // -2 for left padding
let spacing_str = " ".repeat(spacing.max(1));
let line = Line::from(vec![
Span::raw(" "), // 1 char left padding
Span::styled(left_text, Style::default().fg(Theme::border())),
Span::raw(spacing_str),
Span::styled(right_text, Style::default().fg(Theme::border())),
]);
let statusbar = Paragraph::new(line);
frame.render_widget(statusbar, area); frame.render_widget(statusbar, area);
} }
/// Get local IP address of the dashboard /// Get context-aware shortcuts based on focused panel
fn get_local_ip() -> String { fn get_context_shortcuts(&self) -> Vec<String> {
use std::net::UdpSocket; let mut shortcuts = Vec::new();
// Try to get local IP by creating a UDP socket // Global shortcuts
// This doesn't actually send data, just determines routing shortcuts.push("Tab: Host".to_string());
if let Ok(socket) = UdpSocket::bind("0.0.0.0:0") { shortcuts.push("↑↓/jk: Select".to_string());
if socket.connect("8.8.8.8:80").is_ok() { shortcuts.push("r: Rebuild".to_string());
if let Ok(addr) = socket.local_addr() { shortcuts.push("B: Backup".to_string());
return addr.ip().to_string(); shortcuts.push("s/S: Start/Stop".to_string());
} shortcuts.push("L: Logs".to_string());
} shortcuts.push("t: Terminal".to_string());
} shortcuts.push("w: Wake".to_string());
"N/A".to_string()
// Always show quit
shortcuts.push("q: Quit".to_string());
shortcuts
} }
fn render_system_panel(&mut self, frame: &mut Frame, area: Rect, _metric_store: &MetricStore) { fn render_system_panel(&mut self, frame: &mut Frame, area: Rect, _metric_store: &MetricStore) {

View File

@ -142,7 +142,6 @@ impl Theme {
/// Get color for status level /// Get color for status level
pub fn status_color(status: Status) -> Color { pub fn status_color(status: Status) -> Color {
match status { match status {
Status::Info => Self::muted_text(), // Gray for informational data
Status::Ok => Self::success(), Status::Ok => Self::success(),
Status::Inactive => Self::muted_text(), // Gray for inactive services in service list Status::Inactive => Self::muted_text(), // Gray for inactive services in service list
Status::Pending => Self::highlight(), // Blue for pending Status::Pending => Self::highlight(), // Blue for pending
@ -241,7 +240,6 @@ impl StatusIcons {
/// Get status icon symbol /// Get status icon symbol
pub fn get_icon(status: Status) -> &'static str { pub fn get_icon(status: Status) -> &'static str {
match status { match status {
Status::Info => "", // No icon for informational data
Status::Ok => "", Status::Ok => "",
Status::Inactive => "", // Empty circle for inactive services Status::Inactive => "", // Empty circle for inactive services
Status::Pending => "", // Hollow circle for pending Status::Pending => "", // Hollow circle for pending
@ -256,7 +254,6 @@ impl StatusIcons {
pub fn create_status_spans(status: Status, text: &str) -> Vec<ratatui::text::Span<'static>> { pub fn create_status_spans(status: Status, text: &str) -> Vec<ratatui::text::Span<'static>> {
let icon = Self::get_icon(status); let icon = Self::get_icon(status);
let status_color = match status { let status_color = match status {
Status::Info => Theme::muted_text(), // Gray for info
Status::Ok => Theme::success(), // Green Status::Ok => Theme::success(), // Green
Status::Inactive => Theme::muted_text(), // Gray for inactive services Status::Inactive => Theme::muted_text(), // Gray for inactive services
Status::Pending => Theme::highlight(), // Blue Status::Pending => Theme::highlight(), // Blue

View File

@ -11,74 +11,6 @@ use tracing::debug;
use crate::ui::theme::{Components, StatusIcons, Theme, Typography}; use crate::ui::theme::{Components, StatusIcons, Theme, Typography};
use ratatui::style::Style; use ratatui::style::Style;
/// Column visibility configuration based on terminal width
#[derive(Debug, Clone, Copy)]
struct ColumnVisibility {
show_name: bool,
show_status: bool,
show_ram: bool,
show_uptime: bool,
show_restarts: bool,
}
impl ColumnVisibility {
/// Calculate actual width needed for all columns
const NAME_WIDTH: u16 = 23;
const STATUS_WIDTH: u16 = 10;
const RAM_WIDTH: u16 = 8;
const UPTIME_WIDTH: u16 = 8;
const RESTARTS_WIDTH: u16 = 5;
const COLUMN_SPACING: u16 = 1; // Space between columns
/// Determine which columns to show based on available width
/// Priority order: Name > Status > RAM > Uptime > Restarts
fn from_width(width: u16) -> Self {
// Calculate cumulative widths for each configuration
let minimal = Self::NAME_WIDTH + Self::COLUMN_SPACING + Self::STATUS_WIDTH; // 34
let with_ram = minimal + Self::COLUMN_SPACING + Self::RAM_WIDTH; // 43
let with_uptime = with_ram + Self::COLUMN_SPACING + Self::UPTIME_WIDTH; // 52
let full = with_uptime + Self::COLUMN_SPACING + Self::RESTARTS_WIDTH; // 58
if width >= full {
// Show all columns
Self {
show_name: true,
show_status: true,
show_ram: true,
show_uptime: true,
show_restarts: true,
}
} else if width >= with_uptime {
// Hide restarts
Self {
show_name: true,
show_status: true,
show_ram: true,
show_uptime: true,
show_restarts: false,
}
} else if width >= with_ram {
// Hide uptime and restarts
Self {
show_name: true,
show_status: true,
show_ram: true,
show_uptime: false,
show_restarts: false,
}
} else {
// Minimal: Name + Status only
Self {
show_name: true,
show_status: true,
show_ram: false,
show_uptime: false,
show_restarts: false,
}
}
}
}
/// Services widget displaying hierarchical systemd service statuses /// Services widget displaying hierarchical systemd service statuses
#[derive(Clone)] #[derive(Clone)]
pub struct ServicesWidget { pub struct ServicesWidget {
@ -91,20 +23,15 @@ pub struct ServicesWidget {
/// Last update indicator /// Last update indicator
has_data: bool, has_data: bool,
/// Currently selected service index (for navigation cursor) /// Currently selected service index (for navigation cursor)
pub selected_index: usize, selected_index: usize,
/// Scroll offset for viewport (which display line is at the top)
pub scroll_offset: usize,
/// Last rendered viewport height (for accurate scroll bounds)
last_viewport_height: usize,
} }
#[derive(Clone)] #[derive(Clone)]
struct ServiceInfo { struct ServiceInfo {
memory_mb: Option<f32>,
disk_gb: Option<f32>,
metrics: Vec<(String, f32, Option<String>)>, // (label, value, unit) metrics: Vec<(String, f32, Option<String>)>, // (label, value, unit)
widget_status: Status, widget_status: Status,
memory_bytes: Option<u64>,
restart_count: Option<u32>,
uptime_seconds: Option<u64>,
} }
impl ServicesWidget { impl ServicesWidget {
@ -115,8 +42,6 @@ impl ServicesWidget {
status: Status::Unknown, status: Status::Unknown,
has_data: false, has_data: false,
selected_index: 0, selected_index: 0,
scroll_offset: 0,
last_viewport_height: 0,
} }
} }
@ -126,6 +51,8 @@ impl ServicesWidget {
if metric_name.starts_with("service_") { if metric_name.starts_with("service_") {
if let Some(end_pos) = metric_name if let Some(end_pos) = metric_name
.rfind("_status") .rfind("_status")
.or_else(|| metric_name.rfind("_memory_mb"))
.or_else(|| metric_name.rfind("_disk_gb"))
.or_else(|| metric_name.rfind("_latency_ms")) .or_else(|| metric_name.rfind("_latency_ms"))
{ {
let service_part = &metric_name[8..end_pos]; // Remove "service_" prefix let service_part = &metric_name[8..end_pos]; // Remove "service_" prefix
@ -148,20 +75,45 @@ impl ServicesWidget {
None None
} }
/// Format disk size with appropriate units (kB/MB/GB)
fn format_disk_size(size_gb: f32) -> String {
let size_mb = size_gb * 1024.0; // Convert GB to MB
if size_mb >= 1024.0 {
// Show as GB
format!("{:.1}GB", size_gb)
} else if size_mb >= 1.0 {
// Show as MB
format!("{:.0}MB", size_mb)
} else if size_mb >= 0.001 {
// Convert to kB
let size_kb = size_mb * 1024.0;
format!("{:.0}kB", size_kb)
} else {
// Show very small sizes as bytes
let size_bytes = size_mb * 1024.0 * 1024.0;
format!("{:.0}B", size_bytes)
}
}
/// Format parent service line - returns text without icon for span formatting /// Format parent service line - returns text without icon for span formatting
fn format_parent_service_line(&self, name: &str, info: &ServiceInfo, columns: ColumnVisibility) -> String { fn format_parent_service_line(&self, name: &str, info: &ServiceInfo) -> String {
// Truncate long service names to fit layout let memory_str = info
// NAME_WIDTH - 3 chars for "..." = max displayable chars .memory_mb
let max_name_len = (ColumnVisibility::NAME_WIDTH - 3) as usize; .map_or("0M".to_string(), |m| format!("{:.0}M", m));
let short_name = if name.len() > max_name_len { let disk_str = info
format!("{}...", &name[..max_name_len.saturating_sub(3)]) .disk_gb
.map_or("0".to_string(), |d| Self::format_disk_size(d));
// Truncate long service names to fit layout (account for icon space)
let short_name = if name.len() > 22 {
format!("{}...", &name[..19])
} else { } else {
name.to_string() name.to_string()
}; };
// Convert Status enum to display text // Convert Status enum to display text
let status_str = match info.widget_status { let status_str = match info.widget_status {
Status::Info => "", // Shouldn't happen for parent services
Status::Ok => "active", Status::Ok => "active",
Status::Inactive => "inactive", Status::Inactive => "inactive",
Status::Critical => "failed", Status::Critical => "failed",
@ -171,59 +123,10 @@ impl ServicesWidget {
Status::Offline => "offline", Status::Offline => "offline",
}; };
// Format memory format!(
let memory_str = info.memory_bytes.map_or("-".to_string(), |bytes| { "{:<23} {:<10} {:<8} {:<8}",
let mb = bytes as f64 / (1024.0 * 1024.0); short_name, status_str, memory_str, disk_str
if mb >= 1000.0 { )
format!("{:.1}G", mb / 1024.0)
} else {
format!("{:.0}M", mb)
}
});
// Format uptime
let uptime_str = info.uptime_seconds.map_or("-".to_string(), |secs| {
let days = secs / 86400;
let hours = (secs % 86400) / 3600;
let mins = (secs % 3600) / 60;
if days > 0 {
format!("{}d{}h", days, hours)
} else if hours > 0 {
format!("{}h{}m", hours, mins)
} else {
format!("{}m", mins)
}
});
// Format restarts (show "!" if > 0 to indicate instability)
let restart_str = info.restart_count.map_or("-".to_string(), |count| {
if count > 0 {
format!("!{}", count)
} else {
"0".to_string()
}
});
// Build format string based on column visibility
let mut parts = Vec::new();
if columns.show_name {
parts.push(format!("{:<width$}", short_name, width = ColumnVisibility::NAME_WIDTH as usize));
}
if columns.show_status {
parts.push(format!("{:<width$}", status_str, width = ColumnVisibility::STATUS_WIDTH as usize));
}
if columns.show_ram {
parts.push(format!("{:<width$}", memory_str, width = ColumnVisibility::RAM_WIDTH as usize));
}
if columns.show_uptime {
parts.push(format!("{:<width$}", uptime_str, width = ColumnVisibility::UPTIME_WIDTH as usize));
}
if columns.show_restarts {
parts.push(format!("{:<width$}", restart_str, width = ColumnVisibility::RESTARTS_WIDTH as usize));
}
parts.join(" ")
} }
@ -235,12 +138,9 @@ impl ServicesWidget {
info: &ServiceInfo, info: &ServiceInfo,
is_last: bool, is_last: bool,
) -> Vec<ratatui::text::Span<'static>> { ) -> Vec<ratatui::text::Span<'static>> {
// Informational sub-services (Status::Info) can use more width since they don't show columns
let max_width = if info.widget_status == Status::Info { 50 } else { 18 };
// Truncate long sub-service names to fit layout (accounting for indentation) // Truncate long sub-service names to fit layout (accounting for indentation)
let short_name = if name.len() > max_width { let short_name = if name.len() > 18 {
format!("{}...", &name[..(max_width.saturating_sub(3))]) format!("{}...", &name[..15])
} else { } else {
name.to_string() name.to_string()
}; };
@ -248,7 +148,6 @@ impl ServicesWidget {
// Get status icon and text // Get status icon and text
let icon = StatusIcons::get_icon(info.widget_status); let icon = StatusIcons::get_icon(info.widget_status);
let status_color = match info.widget_status { let status_color = match info.widget_status {
Status::Info => Theme::muted_text(),
Status::Ok => Theme::success(), Status::Ok => Theme::success(),
Status::Inactive => Theme::muted_text(), Status::Inactive => Theme::muted_text(),
Status::Pending => Theme::highlight(), Status::Pending => Theme::highlight(),
@ -269,7 +168,6 @@ impl ServicesWidget {
} else { } else {
// Convert Status enum to display text for sub-services // Convert Status enum to display text for sub-services
match info.widget_status { match info.widget_status {
Status::Info => "",
Status::Ok => "active", Status::Ok => "active",
Status::Inactive => "inactive", Status::Inactive => "inactive",
Status::Critical => "failed", Status::Critical => "failed",
@ -281,69 +179,38 @@ impl ServicesWidget {
}; };
let tree_symbol = if is_last { "└─" } else { "├─" }; let tree_symbol = if is_last { "└─" } else { "├─" };
if info.widget_status == Status::Info { vec![
// Informational data - no status icon, show metrics if available // Indentation and tree prefix
let mut spans = vec![ ratatui::text::Span::styled(
// Indentation and tree prefix format!(" {} ", tree_symbol),
ratatui::text::Span::styled( Typography::tree(),
format!(" {} ", tree_symbol), ),
Typography::tree(), // Status icon
), ratatui::text::Span::styled(
// Service name (no icon) - no fixed width padding for Info status format!("{} ", icon),
ratatui::text::Span::styled( Style::default().fg(status_color).bg(Theme::background()),
short_name, ),
Style::default() // Service name
.fg(Theme::secondary_text()) ratatui::text::Span::styled(
.bg(Theme::background()), format!("{:<18} ", short_name),
), Style::default()
]; .fg(Theme::secondary_text())
.bg(Theme::background()),
// Add metrics if available (e.g., Docker image size) ),
if !status_str.is_empty() { // Status/latency text
spans.push(ratatui::text::Span::styled( ratatui::text::Span::styled(
status_str, status_str,
Style::default() Style::default()
.fg(Theme::secondary_text()) .fg(Theme::secondary_text())
.bg(Theme::background()), .bg(Theme::background()),
)); ),
} ]
spans
} else {
vec![
// Indentation and tree prefix
ratatui::text::Span::styled(
format!(" {} ", tree_symbol),
Typography::tree(),
),
// Status icon
ratatui::text::Span::styled(
format!("{} ", icon),
Style::default().fg(status_color).bg(Theme::background()),
),
// Service name
ratatui::text::Span::styled(
format!("{:<18} ", short_name),
Style::default()
.fg(Theme::secondary_text())
.bg(Theme::background()),
),
// Status/latency text
ratatui::text::Span::styled(
status_str,
Style::default()
.fg(Theme::secondary_text())
.bg(Theme::background()),
),
]
}
} }
/// Move selection up /// Move selection up
pub fn select_previous(&mut self) { pub fn select_previous(&mut self) {
if self.selected_index > 0 { if self.selected_index > 0 {
self.selected_index -= 1; self.selected_index -= 1;
self.ensure_selected_visible();
} }
debug!("Service selection moved up to: {}", self.selected_index); debug!("Service selection moved up to: {}", self.selected_index);
} }
@ -352,77 +219,10 @@ impl ServicesWidget {
pub fn select_next(&mut self, total_services: usize) { pub fn select_next(&mut self, total_services: usize) {
if total_services > 0 && self.selected_index < total_services.saturating_sub(1) { if total_services > 0 && self.selected_index < total_services.saturating_sub(1) {
self.selected_index += 1; self.selected_index += 1;
self.ensure_selected_visible();
} }
debug!("Service selection: {}/{}", self.selected_index, total_services); debug!("Service selection: {}/{}", self.selected_index, total_services);
} }
/// Convert parent service index to display line index
fn parent_index_to_display_line(&self, parent_index: usize) -> usize {
let mut parent_services: Vec<_> = self.parent_services.iter().collect();
parent_services.sort_by(|(a, _), (b, _)| a.cmp(b));
let mut display_line = 0;
for (idx, (parent_name, _)) in parent_services.iter().enumerate() {
if idx == parent_index {
return display_line;
}
display_line += 1; // Parent service line
// Add sub-service lines
if let Some(sub_list) = self.sub_services.get(*parent_name) {
display_line += sub_list.len();
}
}
display_line
}
/// Ensure the currently selected service is visible in the viewport
fn ensure_selected_visible(&mut self) {
if self.last_viewport_height == 0 {
return; // Can't adjust without knowing viewport size
}
let display_line = self.parent_index_to_display_line(self.selected_index);
let total_display_lines = self.get_total_display_lines();
let viewport_height = self.last_viewport_height;
// Check if selected line is above visible area
if display_line < self.scroll_offset {
self.scroll_offset = display_line;
return;
}
// Calculate current effective viewport (accounting for "more below" if present)
let current_remaining = total_display_lines.saturating_sub(self.scroll_offset);
let current_has_more = current_remaining > viewport_height;
let current_effective = if current_has_more {
viewport_height.saturating_sub(1)
} else {
viewport_height
};
// Check if selected line is below current visible area
if display_line >= self.scroll_offset + current_effective {
// Need to scroll down. Position selected line so there's room for "more below" if needed
// Strategy: if there are lines below the selected line, don't put it at the very bottom
let has_content_below = display_line < total_display_lines - 1;
if has_content_below {
// Leave room for "... X more below" message by positioning selected line
// one position higher than the last line
let target_position = viewport_height.saturating_sub(2);
self.scroll_offset = display_line.saturating_sub(target_position);
} else {
// This is the last line, can put it at the bottom
self.scroll_offset = display_line.saturating_sub(viewport_height - 1);
}
}
debug!("Auto-scroll: selected={}, display_line={}, scroll_offset={}, viewport={}, total={}",
self.selected_index, display_line, self.scroll_offset, viewport_height, total_display_lines);
}
/// Get currently selected service name (for actions) /// Get currently selected service name (for actions)
/// Only returns parent service names since only parent services can be selected /// Only returns parent service names since only parent services can be selected
pub fn get_selected_service(&self) -> Option<String> { pub fn get_selected_service(&self) -> Option<String> {
@ -439,81 +239,6 @@ impl ServicesWidget {
self.parent_services.len() self.parent_services.len()
} }
/// Get total display lines (parent services + sub-services)
pub fn get_total_display_lines(&self) -> usize {
let mut total = self.parent_services.len();
for sub_list in self.sub_services.values() {
total += sub_list.len();
}
total
}
/// Scroll down by one line
pub fn scroll_down(&mut self, _visible_height: usize) {
let total_lines = self.get_total_display_lines();
// Use last_viewport_height if available (more accurate), otherwise can't scroll
let viewport_height = if self.last_viewport_height > 0 {
self.last_viewport_height
} else {
return; // Can't scroll without knowing viewport size
};
// Calculate exact max scroll to match render logic
// Stop scrolling when all remaining content fits in viewport
// At scroll_offset N: remaining = total_lines - N
// We can show all when: remaining <= viewport_height
// So max_scroll is when: total_lines - max_scroll = viewport_height
// Therefore: max_scroll = total_lines - viewport_height (but at least 0)
let max_scroll = total_lines.saturating_sub(viewport_height);
debug!("Scroll down: total={}, viewport={}, offset={}, max={}", total_lines, viewport_height, self.scroll_offset, max_scroll);
if self.scroll_offset < max_scroll {
self.scroll_offset += 1;
}
}
/// Scroll up by one line
pub fn scroll_up(&mut self) {
if self.scroll_offset > 0 {
self.scroll_offset -= 1;
}
}
/// Map a display line index to a parent service index (returns None if clicked on sub-service)
pub fn display_line_to_parent_index(&self, display_line_index: usize) -> Option<usize> {
// Build the same display list to map line index to parent service index
let mut parent_index = 0;
let mut line_index = 0;
let mut parent_services: Vec<_> = self.parent_services.iter().collect();
parent_services.sort_by(|(a, _), (b, _)| a.cmp(b));
for (parent_name, _) in parent_services {
// Check if this line index matches a parent service
if line_index == display_line_index {
return Some(parent_index);
}
line_index += 1;
// Add sub-services for this parent (if any)
if let Some(sub_list) = self.sub_services.get(parent_name) {
for _ in sub_list {
if line_index == display_line_index {
// Clicked on a sub-service - return None (can't select sub-services)
return None;
}
line_index += 1;
}
}
parent_index += 1;
}
None
}
/// Calculate which parent service index corresponds to a display line index /// Calculate which parent service index corresponds to a display line index
fn calculate_parent_service_index(&self, display_line_index: &usize) -> usize { fn calculate_parent_service_index(&self, display_line_index: &usize) -> usize {
@ -553,11 +278,10 @@ impl Widget for ServicesWidget {
for service in &agent_data.services { for service in &agent_data.services {
// Store parent service // Store parent service
let parent_info = ServiceInfo { let parent_info = ServiceInfo {
memory_mb: Some(service.memory_mb),
disk_gb: Some(service.disk_gb),
metrics: Vec::new(), // Parent services don't have custom metrics metrics: Vec::new(), // Parent services don't have custom metrics
widget_status: service.service_status, widget_status: service.service_status,
memory_bytes: service.memory_bytes,
restart_count: service.restart_count,
uptime_seconds: service.uptime_seconds,
}; };
self.parent_services.insert(service.name.clone(), parent_info); self.parent_services.insert(service.name.clone(), parent_info);
@ -571,11 +295,10 @@ impl Widget for ServicesWidget {
.collect(); .collect();
let sub_info = ServiceInfo { let sub_info = ServiceInfo {
memory_mb: None, // Not used for sub-services
disk_gb: None, // Not used for sub-services
metrics, metrics,
widget_status: sub_service.service_status, widget_status: sub_service.service_status,
memory_bytes: None, // Sub-services don't have individual metrics yet
restart_count: None,
uptime_seconds: None,
}; };
sub_list.push((sub_service.name.clone(), sub_info)); sub_list.push((sub_service.name.clone(), sub_info));
} }
@ -615,15 +338,22 @@ impl ServicesWidget {
self.parent_services self.parent_services
.entry(parent_service) .entry(parent_service)
.or_insert(ServiceInfo { .or_insert(ServiceInfo {
memory_mb: None,
disk_gb: None,
metrics: Vec::new(), metrics: Vec::new(),
widget_status: Status::Unknown, widget_status: Status::Unknown,
memory_bytes: None,
restart_count: None,
uptime_seconds: None,
}); });
if metric.name.ends_with("_status") { if metric.name.ends_with("_status") {
service_info.widget_status = metric.status; service_info.widget_status = metric.status;
} else if metric.name.ends_with("_memory_mb") {
if let Some(memory) = metric.value.as_f32() {
service_info.memory_mb = Some(memory);
}
} else if metric.name.ends_with("_disk_gb") {
if let Some(disk) = metric.value.as_f32() {
service_info.disk_gb = Some(disk);
}
} }
} }
Some(sub_name) => { Some(sub_name) => {
@ -643,11 +373,10 @@ impl ServicesWidget {
sub_service_list.push(( sub_service_list.push((
sub_name.clone(), sub_name.clone(),
ServiceInfo { ServiceInfo {
memory_mb: None,
disk_gb: None,
metrics: Vec::new(), metrics: Vec::new(),
widget_status: Status::Unknown, widget_status: Status::Unknown,
memory_bytes: None,
restart_count: None,
uptime_seconds: None,
}, },
)); ));
&mut sub_service_list.last_mut().unwrap().1 &mut sub_service_list.last_mut().unwrap().1
@ -655,6 +384,14 @@ impl ServicesWidget {
if metric.name.ends_with("_status") { if metric.name.ends_with("_status") {
sub_service_info.widget_status = metric.status; sub_service_info.widget_status = metric.status;
} else if metric.name.ends_with("_memory_mb") {
if let Some(memory) = metric.value.as_f32() {
sub_service_info.memory_mb = Some(memory);
}
} else if metric.name.ends_with("_disk_gb") {
if let Some(disk) = metric.value.as_f32() {
sub_service_info.disk_gb = Some(disk);
}
} }
} }
} }
@ -686,23 +423,12 @@ impl ServicesWidget {
self.selected_index = total_count - 1; self.selected_index = total_count - 1;
} }
// Clamp scroll offset to valid range after update
// This prevents scroll issues when switching between hosts or when service count changes
let total_display_lines = self.get_total_display_lines();
if total_display_lines == 0 {
self.scroll_offset = 0;
} else if self.scroll_offset >= total_display_lines {
// Clamp to max valid value, not reset to 0
self.scroll_offset = total_display_lines.saturating_sub(1);
}
debug!( debug!(
"Services widget updated: {} parent services, {} sub-service groups, total={}, selected={}, scroll={}, status={:?}", "Services widget updated: {} parent services, {} sub-service groups, total={}, selected={}, status={:?}",
self.parent_services.len(), self.parent_services.len(),
self.sub_services.len(), self.sub_services.len(),
total_count, total_count,
self.selected_index, self.selected_index,
self.scroll_offset,
self.status self.status
); );
} }
@ -722,28 +448,11 @@ impl ServicesWidget {
.constraints([Constraint::Length(1), Constraint::Min(0)]) .constraints([Constraint::Length(1), Constraint::Min(0)])
.split(inner_area); .split(inner_area);
// Determine which columns to show based on available width // Header
let columns = ColumnVisibility::from_width(inner_area.width); let header = format!(
"{:<25} {:<10} {:<8} {:<8}",
// Build header based on visible columns "Service:", "Status:", "RAM:", "Disk:"
let mut header_parts = Vec::new(); );
if columns.show_name {
header_parts.push(format!("{:<width$}", "Service:", width = ColumnVisibility::NAME_WIDTH as usize));
}
if columns.show_status {
header_parts.push(format!("{:<width$}", "Status:", width = ColumnVisibility::STATUS_WIDTH as usize));
}
if columns.show_ram {
header_parts.push(format!("{:<width$}", "RAM:", width = ColumnVisibility::RAM_WIDTH as usize));
}
if columns.show_uptime {
header_parts.push(format!("{:<width$}", "Uptime:", width = ColumnVisibility::UPTIME_WIDTH as usize));
}
if columns.show_restarts {
header_parts.push(format!("{:<width$}", "↻:", width = ColumnVisibility::RESTARTS_WIDTH as usize));
}
let header = header_parts.join(" ");
let header_para = Paragraph::new(header).style(Typography::muted()); let header_para = Paragraph::new(header).style(Typography::muted());
frame.render_widget(header_para, content_chunks[0]); frame.render_widget(header_para, content_chunks[0]);
@ -755,11 +464,11 @@ impl ServicesWidget {
} }
// Render the services list // Render the services list
self.render_services(frame, content_chunks[1], is_focused, columns); self.render_services(frame, content_chunks[1], is_focused);
} }
/// Render services list /// Render services list
fn render_services(&mut self, frame: &mut Frame, area: Rect, is_focused: bool, columns: ColumnVisibility) { fn render_services(&mut self, frame: &mut Frame, area: Rect, is_focused: bool) {
// Build hierarchical service list for display // Build hierarchical service list for display
let mut display_lines: Vec<(String, Status, bool, Option<(ServiceInfo, bool)>)> = Vec::new(); let mut display_lines: Vec<(String, Status, bool, Option<(ServiceInfo, bool)>)> = Vec::new();
@ -769,7 +478,7 @@ impl ServicesWidget {
for (parent_name, parent_info) in parent_services { for (parent_name, parent_info) in parent_services {
// Add parent service line // Add parent service line
let parent_line = self.format_parent_service_line(parent_name, parent_info, columns); let parent_line = self.format_parent_service_line(parent_name, parent_info);
display_lines.push((parent_line, parent_info.widget_status, false, None)); display_lines.push((parent_line, parent_info.widget_status, false, None));
// Add sub-services for this parent (if any) // Add sub-services for this parent (if any)
@ -795,45 +504,19 @@ impl ServicesWidget {
let available_lines = area.height as usize; let available_lines = area.height as usize;
let total_lines = display_lines.len(); let total_lines = display_lines.len();
// Store viewport height for accurate scroll calculations // Reserve one line for "X more below" if needed
self.last_viewport_height = available_lines; let lines_for_content = if total_lines > available_lines {
// Clamp scroll_offset to valid range based on current viewport and content
// This handles dynamic viewport size changes
let max_valid_scroll = total_lines.saturating_sub(available_lines);
if self.scroll_offset > max_valid_scroll {
self.scroll_offset = max_valid_scroll;
}
// Calculate how many lines remain after scroll offset
let remaining_lines = total_lines.saturating_sub(self.scroll_offset);
debug!("Render: total={}, viewport={}, offset={}, max={}, remaining={}",
total_lines, available_lines, self.scroll_offset, max_valid_scroll, remaining_lines);
// Check if all remaining content fits in viewport
let will_show_more_below = remaining_lines > available_lines;
// Reserve one line for "X more below" only if we can't fit everything
let lines_for_content = if will_show_more_below {
available_lines.saturating_sub(1) available_lines.saturating_sub(1)
} else { } else {
available_lines.min(remaining_lines) available_lines
}; };
// Apply scroll offset
let visible_lines: Vec<_> = display_lines let visible_lines: Vec<_> = display_lines
.iter() .iter()
.skip(self.scroll_offset)
.take(lines_for_content) .take(lines_for_content)
.collect(); .collect();
// Only calculate hidden_below if we actually reserved space for the message let hidden_below = total_lines.saturating_sub(lines_for_content);
let hidden_below = if will_show_more_below {
remaining_lines.saturating_sub(lines_for_content)
} else {
0
};
let lines_to_show = visible_lines.len(); let lines_to_show = visible_lines.len();
@ -847,7 +530,7 @@ impl ServicesWidget {
for (i, (line_text, line_status, is_sub, sub_info)) in visible_lines.iter().enumerate() for (i, (line_text, line_status, is_sub, sub_info)) in visible_lines.iter().enumerate()
{ {
let actual_index = self.scroll_offset + i; // Account for scroll offset let actual_index = i; // Simple index since we're not scrolling
// Only parent services can be selected - calculate parent service index // Only parent services can be selected - calculate parent service index
let is_selected = if !*is_sub { let is_selected = if !*is_sub {
@ -893,7 +576,7 @@ impl ServicesWidget {
// Show "X more below" message if content was truncated // Show "X more below" message if content was truncated
if hidden_below > 0 { if hidden_below > 0 {
let more_text = format!("... {} more below", hidden_below); let more_text = format!("... {} more below", hidden_below);
let more_para = Paragraph::new(more_text).style(Style::default().fg(Theme::border())); let more_para = Paragraph::new(more_text).style(Typography::muted());
frame.render_widget(more_para, service_chunks[lines_to_show]); frame.render_widget(more_para, service_chunks[lines_to_show]);
} }
} }

View File

@ -1,13 +1,12 @@
use cm_dashboard_shared::Status; use cm_dashboard_shared::Status;
use ratatui::{ use ratatui::{
layout::Rect, layout::Rect,
style::Style,
text::{Line, Span, Text}, text::{Line, Span, Text},
widgets::Paragraph, widgets::Paragraph,
Frame, Frame,
}; };
use crate::ui::theme::{StatusIcons, Theme, Typography}; use crate::ui::theme::{StatusIcons, Typography};
/// System widget displaying NixOS info, Network, CPU, RAM, and Storage in unified layout /// System widget displaying NixOS info, Network, CPU, RAM, and Storage in unified layout
#[derive(Clone)] #[derive(Clone)]
@ -16,6 +15,10 @@ pub struct SystemWidget {
nixos_build: Option<String>, nixos_build: Option<String>,
agent_hash: Option<String>, agent_hash: Option<String>,
// ZMQ communication stats
zmq_packets_received: Option<u64>,
zmq_last_packet_age: Option<f64>,
// Network interfaces // Network interfaces
network_interfaces: Vec<cm_dashboard_shared::NetworkInterfaceData>, network_interfaces: Vec<cm_dashboard_shared::NetworkInterfaceData>,
@ -23,9 +26,7 @@ pub struct SystemWidget {
cpu_load_1min: Option<f32>, cpu_load_1min: Option<f32>,
cpu_load_5min: Option<f32>, cpu_load_5min: Option<f32>,
cpu_load_15min: Option<f32>, cpu_load_15min: Option<f32>,
cpu_cstates: Vec<cm_dashboard_shared::CStateInfo>, cpu_frequency: Option<f32>,
cpu_model_name: Option<String>,
cpu_core_count: Option<u32>,
cpu_status: Status, cpu_status: Status,
// Memory metrics // Memory metrics
@ -44,17 +45,18 @@ pub struct SystemWidget {
storage_pools: Vec<StoragePool>, storage_pools: Vec<StoragePool>,
// Backup metrics // Backup metrics
backup_last_time: Option<String>, backup_status: String,
backup_status: Status, backup_start_time_raw: Option<String>,
backup_repositories: Vec<cm_dashboard_shared::BackupRepositoryData>, backup_disk_serial: Option<String>,
backup_disk_usage_percent: Option<f32>,
backup_disk_used_gb: Option<f32>,
backup_disk_total_gb: Option<f32>,
backup_disk_wear_percent: Option<f32>,
backup_disk_temperature: Option<f32>,
backup_last_size_gb: Option<f32>,
// Overall status // Overall status
has_data: bool, has_data: bool,
// Scroll offset for viewport
pub scroll_offset: usize,
/// Last rendered viewport height (for accurate scroll bounds)
last_viewport_height: usize,
} }
#[derive(Clone)] #[derive(Clone)]
@ -94,13 +96,13 @@ impl SystemWidget {
Self { Self {
nixos_build: None, nixos_build: None,
agent_hash: None, agent_hash: None,
zmq_packets_received: None,
zmq_last_packet_age: None,
network_interfaces: Vec::new(), network_interfaces: Vec::new(),
cpu_load_1min: None, cpu_load_1min: None,
cpu_load_5min: None, cpu_load_5min: None,
cpu_load_15min: None, cpu_load_15min: None,
cpu_cstates: Vec::new(), cpu_frequency: None,
cpu_model_name: None,
cpu_core_count: None,
cpu_status: Status::Unknown, cpu_status: Status::Unknown,
memory_usage_percent: None, memory_usage_percent: None,
memory_used_gb: None, memory_used_gb: None,
@ -112,12 +114,16 @@ impl SystemWidget {
tmp_status: Status::Unknown, tmp_status: Status::Unknown,
tmpfs_mounts: Vec::new(), tmpfs_mounts: Vec::new(),
storage_pools: Vec::new(), storage_pools: Vec::new(),
backup_last_time: None, backup_status: "unknown".to_string(),
backup_status: Status::Unknown, backup_start_time_raw: None,
backup_repositories: Vec::new(), backup_disk_serial: None,
backup_disk_usage_percent: None,
backup_disk_used_gb: None,
backup_disk_total_gb: None,
backup_disk_wear_percent: None,
backup_disk_temperature: None,
backup_last_size_gb: None,
has_data: false, has_data: false,
scroll_offset: 0,
last_viewport_height: 0,
} }
} }
@ -131,19 +137,12 @@ impl SystemWidget {
} }
} }
/// Format CPU C-states (idle depth) with percentages /// Format CPU frequency
fn format_cpu_cstate(&self) -> String { fn format_cpu_frequency(&self) -> String {
if self.cpu_cstates.is_empty() { match self.cpu_frequency {
return "".to_string(); Some(freq) => format!("{:.0} MHz", freq),
None => "— MHz".to_string(),
} }
// Format top 3 C-states with percentages: "C10:79% C8:10% C6:8%"
// Agent already sends clean names (C3, C10, etc.)
self.cpu_cstates
.iter()
.map(|cs| format!("{}:{:.0}%", cs.name, cs.percent))
.collect::<Vec<_>>()
.join(" ")
} }
/// Format memory usage /// Format memory usage
@ -162,14 +161,10 @@ impl SystemWidget {
self.agent_hash.as_ref() self.agent_hash.as_ref()
} }
/// Get the build version /// Update ZMQ communication statistics
pub fn get_build_version(&self) -> Option<String> { pub fn update_zmq_stats(&mut self, packets_received: u64, last_packet_age_secs: f64) {
self.nixos_build.clone() self.zmq_packets_received = Some(packets_received);
} self.zmq_last_packet_age = Some(last_packet_age_secs);
/// Get the agent version
pub fn get_agent_version(&self) -> Option<String> {
self.agent_hash.clone()
} }
} }
@ -193,9 +188,7 @@ impl Widget for SystemWidget {
self.cpu_load_1min = Some(cpu.load_1min); self.cpu_load_1min = Some(cpu.load_1min);
self.cpu_load_5min = Some(cpu.load_5min); self.cpu_load_5min = Some(cpu.load_5min);
self.cpu_load_15min = Some(cpu.load_15min); self.cpu_load_15min = Some(cpu.load_15min);
self.cpu_cstates = cpu.cstates.clone(); self.cpu_frequency = Some(cpu.frequency_mhz);
self.cpu_model_name = cpu.model_name.clone();
self.cpu_core_count = cpu.core_count;
self.cpu_status = Status::Ok; self.cpu_status = Status::Ok;
// Extract memory data directly // Extract memory data directly
@ -221,18 +214,24 @@ impl Widget for SystemWidget {
// Extract backup data // Extract backup data
let backup = &agent_data.backup; let backup = &agent_data.backup;
self.backup_last_time = backup.last_backup_time.clone(); self.backup_status = backup.status.clone();
self.backup_status = backup.backup_status; self.backup_start_time_raw = backup.start_time_raw.clone();
self.backup_repositories = backup.repositories.clone(); self.backup_last_size_gb = backup.last_backup_size_gb;
// Clamp scroll offset to valid range after update if let Some(disk) = &backup.repository_disk {
// This prevents scroll issues when switching between hosts self.backup_disk_serial = Some(disk.serial.clone());
let total_lines = self.get_total_lines(); self.backup_disk_usage_percent = Some(disk.usage_percent);
if total_lines == 0 { self.backup_disk_used_gb = Some(disk.used_gb);
self.scroll_offset = 0; self.backup_disk_total_gb = Some(disk.total_gb);
} else if self.scroll_offset >= total_lines { self.backup_disk_wear_percent = disk.wear_percent;
// Clamp to max valid value, not reset to 0 self.backup_disk_temperature = disk.temperature_celsius;
self.scroll_offset = total_lines.saturating_sub(1); } else {
self.backup_disk_serial = None;
self.backup_disk_usage_percent = None;
self.backup_disk_used_gb = None;
self.backup_disk_total_gb = None;
self.backup_disk_wear_percent = None;
self.backup_disk_temperature = None;
} }
} }
} }
@ -533,42 +532,61 @@ impl SystemWidget {
fn render_backup(&self) -> Vec<Line<'_>> { fn render_backup(&self) -> Vec<Line<'_>> {
let mut lines = Vec::new(); let mut lines = Vec::new();
if self.backup_repositories.is_empty() { // First line: serial number with temperature and wear
return lines; if let Some(serial) = &self.backup_disk_serial {
} let truncated_serial = truncate_serial(serial);
let mut details = Vec::new();
if let Some(temp) = self.backup_disk_temperature {
details.push(format!("T: {}°C", temp as i32));
}
if let Some(wear) = self.backup_disk_wear_percent {
details.push(format!("W: {}%", wear as i32));
}
// Format backup time (use complete timestamp) let disk_text = if !details.is_empty() {
let time_display = if let Some(ref time_str) = self.backup_last_time { format!("{} {}", truncated_serial, details.join(" "))
time_str.clone()
} else {
"unknown".to_string()
};
// Header: just the timestamp
let repo_spans = StatusIcons::create_status_spans(self.backup_status, &time_display);
lines.push(Line::from(repo_spans));
// List all repositories with archive count and size
let repo_count = self.backup_repositories.len();
for (idx, repo) in self.backup_repositories.iter().enumerate() {
let tree_char = if idx == repo_count - 1 { "└─" } else { "├─" };
// Format size: use kB for < 1MB, MB for < 1GB, otherwise GB
let size_display = if repo.repo_size_gb < 0.001 {
format!("{:.0}kB", repo.repo_size_gb * 1024.0 * 1024.0)
} else if repo.repo_size_gb < 1.0 {
format!("{:.0}MB", repo.repo_size_gb * 1024.0)
} else { } else {
format!("{:.1}GB", repo.repo_size_gb) truncated_serial
}; };
let repo_text = format!("{} ({}) {}", repo.name, repo.archive_count, size_display); let backup_status = match self.backup_status.as_str() {
"completed" | "success" => Status::Ok,
"running" => Status::Pending,
"failed" => Status::Critical,
_ => Status::Unknown,
};
let mut repo_spans = vec![ let disk_spans = StatusIcons::create_status_spans(backup_status, &disk_text);
Span::styled(format!(" {} ", tree_char), Typography::tree()), lines.push(Line::from(disk_spans));
];
repo_spans.extend(StatusIcons::create_status_spans(repo.status, &repo_text)); // Show backup time from TOML if available
lines.push(Line::from(repo_spans)); if let Some(start_time) = &self.backup_start_time_raw {
let time_text = if let Some(size) = self.backup_last_size_gb {
format!("Time: {} ({:.1}GB)", start_time, size)
} else {
format!("Time: {}", start_time)
};
lines.push(Line::from(vec![
Span::styled(" ├─ ", Typography::tree()),
Span::styled(time_text, Typography::secondary())
]));
}
// Usage information
if let (Some(used), Some(total), Some(usage_percent)) = (
self.backup_disk_used_gb,
self.backup_disk_total_gb,
self.backup_disk_usage_percent
) {
let usage_text = format!("Usage: {:.0}% {:.0}GB/{:.0}GB", usage_percent, used, total);
let usage_spans = StatusIcons::create_status_spans(Status::Ok, &usage_text);
let mut full_spans = vec![
Span::styled(" └─ ", Typography::tree()),
];
full_spans.extend(usage_spans);
lines.push(Line::from(full_spans));
}
} }
lines lines
@ -772,88 +790,36 @@ impl SystemWidget {
} }
/// Render system widget /// Render system widget
/// Scroll down by one line pub fn render(&mut self, frame: &mut Frame, area: Rect, hostname: &str, _config: Option<&crate::config::DashboardConfig>) {
pub fn scroll_down(&mut self, _visible_height: usize, _total_lines: usize) {
let total_lines = self.get_total_lines();
// Use last_viewport_height if available (more accurate), otherwise can't scroll
let viewport_height = if self.last_viewport_height > 0 {
self.last_viewport_height
} else {
return; // Can't scroll without knowing viewport size
};
// Max scroll should allow us to see all remaining content
// When scroll_offset + viewport_height >= total_lines, we can see everything
let max_scroll = if total_lines > viewport_height {
total_lines - viewport_height
} else {
0
};
if self.scroll_offset < max_scroll {
self.scroll_offset += 1;
}
}
/// Scroll up by one line
pub fn scroll_up(&mut self) {
if self.scroll_offset > 0 {
self.scroll_offset -= 1;
}
}
/// Get total line count (needs to be calculated before rendering)
pub fn get_total_lines(&self) -> usize {
let mut count = 0;
// CPU section (2+ lines for load/cstate, +1 if has model/cores)
count += 2;
if self.cpu_model_name.is_some() || self.cpu_core_count.is_some() {
count += 1;
}
// RAM section (1 + tmpfs mounts)
count += 2;
count += self.tmpfs_mounts.len();
// Network section
if !self.network_interfaces.is_empty() {
count += 1; // Header
// Count network lines (would need to mirror render_network logic)
for iface in &self.network_interfaces {
count += 1; // Interface name
count += iface.ipv4_addresses.len();
count += iface.ipv6_addresses.len();
}
}
// Storage section
count += 1; // Header
for pool in &self.storage_pools {
count += 1; // Pool header
count += pool.drives.len();
count += pool.data_drives.len();
count += pool.parity_drives.len();
count += pool.filesystems.len();
}
// Backup section
if !self.backup_repositories.is_empty() {
count += 1; // Header: "Backup:"
count += 1; // Repo count and timestamp header
count += self.backup_repositories.len(); // Individual repos
}
count
}
pub fn render(&mut self, frame: &mut Frame, area: Rect, _hostname: &str, _config: Option<&crate::config::DashboardConfig>) {
// Store viewport height for accurate scroll calculations
self.last_viewport_height = area.height as usize;
let mut lines = Vec::new(); let mut lines = Vec::new();
// NixOS section
lines.push(Line::from(vec![
Span::styled(format!("NixOS {}:", hostname), Typography::widget_title())
]));
let build_text = self.nixos_build.as_deref().unwrap_or("unknown");
lines.push(Line::from(vec![
Span::styled(format!("Build: {}", build_text), Typography::secondary())
]));
let agent_version_text = self.agent_hash.as_deref().unwrap_or("unknown");
lines.push(Line::from(vec![
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 // CPU section
lines.push(Line::from(vec![ lines.push(Line::from(vec![
Span::styled("CPU:", Typography::widget_title()) Span::styled("CPU:", Typography::widget_title())
@ -866,32 +832,12 @@ impl SystemWidget {
); );
lines.push(Line::from(cpu_spans)); lines.push(Line::from(cpu_spans));
let cstate_text = self.format_cpu_cstate(); let freq_text = self.format_cpu_frequency();
let has_cpu_info = self.cpu_model_name.is_some() || self.cpu_core_count.is_some();
let cstate_tree = if has_cpu_info { " ├─ " } else { " └─ " };
lines.push(Line::from(vec![ lines.push(Line::from(vec![
Span::styled(cstate_tree, Typography::tree()), Span::styled(" └─ ", Typography::tree()),
Span::styled(format!("C-state: {}", cstate_text), Typography::secondary()) Span::styled(format!("Freq: {}", freq_text), Typography::secondary())
])); ]));
// CPU model and core count (if available)
if let (Some(model), Some(cores)) = (&self.cpu_model_name, self.cpu_core_count) {
lines.push(Line::from(vec![
Span::styled(" └─ ", Typography::tree()),
Span::styled(format!("{} ({} cores)", model, cores), Typography::secondary())
]));
} else if let Some(model) = &self.cpu_model_name {
lines.push(Line::from(vec![
Span::styled(" └─ ", Typography::tree()),
Span::styled(model.clone(), Typography::secondary())
]));
} else if let Some(cores) = self.cpu_core_count {
lines.push(Line::from(vec![
Span::styled(" └─ ", Typography::tree()),
Span::styled(format!("{} cores", cores), Typography::secondary())
]));
}
// RAM section // RAM section
lines.push(Line::from(vec![ lines.push(Line::from(vec![
Span::styled("RAM:", Typography::widget_title()) Span::styled("RAM:", Typography::widget_title())
@ -948,7 +894,7 @@ impl SystemWidget {
lines.extend(storage_lines); lines.extend(storage_lines);
// Backup section (if available) // Backup section (if available)
if !self.backup_repositories.is_empty() { if self.backup_status != "unavailable" && self.backup_status != "unknown" {
lines.push(Line::from(vec![ lines.push(Line::from(vec![
Span::styled("Backup:", Typography::widget_title()) Span::styled("Backup:", Typography::widget_title())
])); ]));
@ -961,50 +907,28 @@ impl SystemWidget {
let total_lines = lines.len(); let total_lines = lines.len();
let available_height = area.height as usize; let available_height = area.height as usize;
// Clamp scroll_offset to valid range based on current viewport and content // Show only what fits, with "X more below" if needed
// This handles dynamic viewport size changes if total_lines > available_height {
let max_valid_scroll = total_lines.saturating_sub(available_height); let lines_for_content = available_height.saturating_sub(1); // Reserve one line for "more below"
let clamped_scroll = self.scroll_offset.min(max_valid_scroll); let mut visible_lines: Vec<Line> = lines
.into_iter()
.take(lines_for_content)
.collect();
// Calculate how many lines remain after scroll offset let hidden_below = total_lines.saturating_sub(lines_for_content);
let remaining_lines = total_lines.saturating_sub(clamped_scroll); if hidden_below > 0 {
let more_line = Line::from(vec![
Span::styled(format!("... {} more below", hidden_below), Typography::muted())
]);
visible_lines.push(more_line);
}
// Check if all remaining content fits in viewport let paragraph = Paragraph::new(Text::from(visible_lines));
let will_show_more_below = remaining_lines > available_height; frame.render_widget(paragraph, area);
// Reserve one line for "X more below" only if we can't fit everything
let lines_for_content = if will_show_more_below {
available_height.saturating_sub(1)
} else { } else {
available_height.min(remaining_lines) // All content fits and no scroll offset, render normally
}; let paragraph = Paragraph::new(Text::from(lines));
frame.render_widget(paragraph, area);
// Apply clamped scroll offset and take only what fits
let mut visible_lines: Vec<Line> = lines
.into_iter()
.skip(clamped_scroll)
.take(lines_for_content)
.collect();
// Note: we don't update self.scroll_offset here due to borrow checker constraints
// It will be clamped on next render if still out of bounds
// Only calculate hidden_below if we actually reserved space for the message
let hidden_below = if will_show_more_below {
remaining_lines.saturating_sub(lines_for_content)
} else {
0
};
// Add "more below" message if needed
if hidden_below > 0 {
let more_line = Line::from(vec![
Span::styled(format!("... {} more below", hidden_below), Style::default().fg(Theme::border()))
]);
visible_lines.push(more_line);
} }
let paragraph = Paragraph::new(Text::from(visible_lines));
frame.render_widget(paragraph, area);
} }
} }

View File

@ -1,6 +1,6 @@
[package] [package]
name = "cm-dashboard-shared" name = "cm-dashboard-shared"
version = "0.1.275" version = "0.1.186"
edition = "2021" edition = "2021"
[dependencies] [dependencies]

View File

@ -38,14 +38,6 @@ pub struct NetworkInterfaceData {
pub link_status: Status, pub link_status: Status,
pub parent_interface: Option<String>, pub parent_interface: Option<String>,
pub vlan_id: Option<u16>, pub vlan_id: Option<u16>,
pub connection_method: Option<String>, // For Tailscale: "direct", "relay", or "proxy"
}
/// CPU C-state usage information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CStateInfo {
pub name: String,
pub percent: f32,
} }
/// CPU monitoring data /// CPU monitoring data
@ -54,15 +46,10 @@ pub struct CpuData {
pub load_1min: f32, pub load_1min: f32,
pub load_5min: f32, pub load_5min: f32,
pub load_15min: f32, pub load_15min: f32,
pub cstates: Vec<CStateInfo>, // C-state usage percentages (C1, C6, C10, etc.) - indicates CPU idle depth distribution pub frequency_mhz: f32,
pub temperature_celsius: Option<f32>, pub temperature_celsius: Option<f32>,
pub load_status: Status, pub load_status: Status,
pub temperature_status: Status, pub temperature_status: Status,
// Static CPU information (collected once at startup)
#[serde(skip_serializing_if = "Option::is_none")]
pub model_name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub core_count: Option<u32>,
} }
/// Memory monitoring data /// Memory monitoring data
@ -149,15 +136,11 @@ pub struct PoolDriveData {
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServiceData { pub struct ServiceData {
pub name: String, pub name: String,
pub memory_mb: f32,
pub disk_gb: f32,
pub user_stopped: bool, pub user_stopped: bool,
pub service_status: Status, pub service_status: Status,
pub sub_services: Vec<SubServiceData>, pub sub_services: Vec<SubServiceData>,
/// Memory usage in bytes (from MemoryCurrent)
pub memory_bytes: Option<u64>,
/// Number of service restarts (from NRestarts)
pub restart_count: Option<u32>,
/// Uptime in seconds (calculated from ExecMainStartTimestamp)
pub uptime_seconds: Option<u64>,
} }
/// Sub-service data (nginx sites, docker containers, etc.) /// Sub-service data (nginx sites, docker containers, etc.)
@ -166,9 +149,6 @@ pub struct SubServiceData {
pub name: String, pub name: String,
pub service_status: Status, pub service_status: Status,
pub metrics: Vec<SubServiceMetric>, pub metrics: Vec<SubServiceMetric>,
/// Type of sub-service: "nginx_site", "container", "image"
#[serde(default)]
pub service_type: String,
} }
/// Individual metric for a sub-service /// Individual metric for a sub-service
@ -182,18 +162,23 @@ pub struct SubServiceMetric {
/// Backup system data /// Backup system data
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BackupData { pub struct BackupData {
pub last_backup_time: Option<String>, pub status: String,
pub backup_status: Status, pub total_size_gb: Option<f32>,
pub repositories: Vec<BackupRepositoryData>, pub repository_health: Option<String>,
pub repository_disk: Option<BackupDiskData>,
pub last_backup_size_gb: Option<f32>,
pub start_time_raw: Option<String>,
} }
/// Individual backup repository information /// Backup repository disk information
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BackupRepositoryData { pub struct BackupDiskData {
pub name: String, pub serial: String,
pub archive_count: i64, pub usage_percent: f32,
pub repo_size_gb: f32, pub used_gb: f32,
pub status: Status, pub total_gb: f32,
pub wear_percent: Option<f32>,
pub temperature_celsius: Option<f32>,
} }
impl AgentData { impl AgentData {
@ -212,12 +197,10 @@ impl AgentData {
load_1min: 0.0, load_1min: 0.0,
load_5min: 0.0, load_5min: 0.0,
load_15min: 0.0, load_15min: 0.0,
cstates: Vec::new(), frequency_mhz: 0.0,
temperature_celsius: None, temperature_celsius: None,
load_status: Status::Unknown, load_status: Status::Unknown,
temperature_status: Status::Unknown, temperature_status: Status::Unknown,
model_name: None,
core_count: None,
}, },
memory: MemoryData { memory: MemoryData {
usage_percent: 0.0, usage_percent: 0.0,
@ -236,9 +219,12 @@ impl AgentData {
}, },
services: Vec::new(), services: Vec::new(),
backup: BackupData { backup: BackupData {
last_backup_time: None, status: "unknown".to_string(),
backup_status: Status::Unknown, total_size_gb: None,
repositories: Vec::new(), repository_health: None,
repository_disk: None,
last_backup_size_gb: None,
start_time_raw: None,
}, },
} }
} }

View File

@ -82,12 +82,11 @@ impl MetricValue {
/// Health status for metrics /// Health status for metrics
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
pub enum Status { pub enum Status {
Info, // Lowest priority - informational data with no status (no icon) Inactive, // Lowest priority
Inactive, //
Unknown, // Unknown, //
Offline, // Offline, //
Pending, // Pending, //
Ok, // Good status has higher priority than unknown states Ok, // 5th place - good status has higher priority than unknown states
Warning, // Warning, //
Critical, // Highest priority Critical, // Highest priority
} }
@ -224,17 +223,6 @@ impl HysteresisThresholds {
Status::Ok Status::Ok
} }
} }
Status::Info => {
// Informational data shouldn't be used with hysteresis calculations
// Treat like Unknown if it somehow ends up here
if value >= self.critical_high {
Status::Critical
} else if value >= self.warning_high {
Status::Warning
} else {
Status::Ok
}
}
} }
} }
} }