All checks were successful
Rust Cross-Platform Build / Detect Rust Project (push) Successful in 5s
Rust Cross-Platform Build / Set Tag Name (push) Successful in 5s
Rust Cross-Platform Build / Run Tests (push) Successful in 1m8s
Rust Cross-Platform Build / Build (x86_64-unknown-linux-gnu) (push) Successful in 3m5s
Rust Cross-Platform Build / Build (x86_64-pc-windows-gnu) (push) Successful in 3m56s
Rust Cross-Platform Build / Build and Push Docker Image (push) Successful in 2m24s
Rust Cross-Platform Build / Create Tag (push) Successful in 6s
Rust Cross-Platform Build / Workflow Summary (push) Successful in 1s
59 lines
1.8 KiB
Rust
59 lines
1.8 KiB
Rust
use std::error::Error;
|
|
|
|
use anyhow::Result;
|
|
use sysinfo::System;
|
|
|
|
/// # Memory Hardware Module
|
|
///
|
|
/// This module provides memory information collection for WatcherAgent, including total, used, and free RAM.
|
|
///
|
|
/// ## Responsibilities
|
|
/// - **Memory Detection:** Queries system for total, used, and free RAM.
|
|
/// - **Usage Calculation:** Computes memory usage percentage.
|
|
/// - **Error Handling:** Graceful fallback if metrics are unavailable.
|
|
///
|
|
/// ## Units
|
|
/// - `total`, `used`, `free`: RAM in **bytes**
|
|
///
|
|
/// Memory statistics for the host system.
|
|
///
|
|
/// # Fields
|
|
/// - `total`: Total RAM in **bytes**
|
|
/// - `used`: Used RAM in **bytes**
|
|
/// - `free`: Free RAM in **bytes**
|
|
#[derive(Debug)]
|
|
pub struct MemoryInfo {
|
|
pub total_size: Option<f64>,
|
|
pub used: Option<f64>,
|
|
pub free: Option<f64>,
|
|
pub current_load: Option<f64>,
|
|
}
|
|
|
|
/// Collects memory information (total, used, free RAM).
|
|
///
|
|
/// # Returns
|
|
/// * `Result<MemoryInfo>` - Memory statistics or error if unavailable.
|
|
pub async fn get_memory_info() -> Result<MemoryInfo, Box<dyn Error + Send + Sync>> {
|
|
let mut sys = System::new();
|
|
sys.refresh_memory();
|
|
|
|
Ok(MemoryInfo {
|
|
total_size: Some(sys.total_memory() as f64),
|
|
used: Some(sys.used_memory() as f64),
|
|
free: Some(sys.free_memory() as f64),
|
|
current_load: Some(get_memory_usage(&mut sys).unwrap() as f64)
|
|
})
|
|
}
|
|
|
|
/// Computes memory usage percentage from sysinfo::System.
|
|
///
|
|
/// # Arguments
|
|
/// * `sys` - Mutable reference to sysinfo::System
|
|
///
|
|
/// # Returns
|
|
/// * `Result<f64, Box<dyn Error + Send + Sync>>` - Memory usage as percentage.
|
|
pub fn get_memory_usage(sys: &mut System) -> Result<f64, Box<dyn Error + Send + Sync>> {
|
|
sys.refresh_memory();
|
|
Ok((sys.used_memory() as f64 / sys.total_memory() as f64) * 100.0)
|
|
}
|