use serde::{Deserialize, Serialize};
use std::path::PathBuf;
pub trait DiskDevice: Send + Sync {
fn name(&self) -> &str;
fn disk_type(&self) -> DiskType;
fn info(&self) -> Result<DiskInfo, Error>;
fn io_stats(&self) -> Result<DiskIoStats, Error>;
fn smart_info(&self) -> Result<SmartInfo, Error> {
Err(Error::NotSupported)
}
fn nvme_info(&self) -> Result<NvmeInfo, Error> {
Err(Error::NotSupported)
}
fn filesystem_info(&self) -> Result<Vec<FilesystemInfo>, Error> {
Err(Error::NotSupported)
}
fn temperature(&self) -> Result<Option<f32>, Error> {
Ok(None)
}
fn health(&self) -> Result<DiskHealth, Error>;
fn device_path(&self) -> PathBuf;
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum DiskType {
NvmeSsd,
SataSsd,
SataHdd,
Scsi,
Usb,
Virtual,
Unknown,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DiskInfo {
pub name: String,
pub model: Option<String>,
pub serial: Option<String>,
pub firmware: Option<String>,
pub capacity: Option<u64>,
pub block_size: Option<u32>,
pub disk_type: DiskType,
pub interface_type: Option<String>,
pub physical_sector_size: Option<u32>,
pub logical_sector_size: Option<u32>,
pub rotation_rate: Option<u32>,
pub vendor: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DiskIoStats {
pub read_bytes: Option<u64>,
pub write_bytes: Option<u64>,
pub read_ops: Option<u64>,
pub write_ops: Option<u64>,
pub read_time_ms: Option<u64>,
pub write_time_ms: Option<u64>,
pub queue_depth: Option<u32>,
pub avg_latency_us: Option<f64>,
pub read_throughput: Option<u64>,
pub write_throughput: Option<u64>,
}
impl DiskIoStats {
pub fn total_ops(&self) -> Option<u64> {
Some(self.read_ops? + self.write_ops?)
}
pub fn total_bytes(&self) -> Option<u64> {
Some(self.read_bytes? + self.write_bytes?)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum SmartSource {
NvmeLogPage,
AtaAttributes,
StorageStack,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SmartInfo {
pub passed: Option<bool>,
pub attributes: Vec<SmartAttribute>,
pub temperature: Option<f32>,
pub power_on_hours: Option<u64>,
pub power_cycle_count: Option<u64>,
pub reallocated_sectors: Option<u64>,
pub pending_sectors: Option<u64>,
pub uncorrectable_sectors: Option<u64>,
pub source: SmartSource,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SmartAttribute {
pub id: u8,
pub name: String,
pub value: u8,
pub worst: u8,
pub threshold: Option<u8>,
pub raw_value: u64,
pub critical: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NvmeInfo {
pub model: String,
pub serial: String,
pub firmware: String,
pub nvme_version: Option<String>,
pub total_capacity: Option<u64>,
pub unallocated_capacity: Option<u64>,
pub controller_id: Option<u16>,
pub num_namespaces: Option<u32>,
pub temperature_sensors: Vec<f32>,
pub power_state: Option<u8>,
pub available_power_states: Vec<NvmePowerState>,
pub percentage_used: Option<u8>,
pub data_units_read: Option<u64>,
pub data_units_written: Option<u64>,
pub host_read_commands: Option<u64>,
pub host_write_commands: Option<u64>,
pub critical_warnings: Option<u8>,
pub available_spare: Option<u8>,
pub available_spare_threshold: Option<u8>,
pub controller_busy_time_minutes: Option<u64>,
pub unsafe_shutdowns: Option<u64>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NvmePowerState {
pub state: u8,
pub max_power_watts: f32,
pub entry_latency_us: u32,
pub exit_latency_us: u32,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FilesystemInfo {
pub mount_point: PathBuf,
pub fs_type: String,
pub total_size: Option<u64>,
pub used_size: Option<u64>,
pub available_size: Option<u64>,
pub total_inodes: Option<u64>,
pub used_inodes: Option<u64>,
pub read_only: Option<bool>,
}
impl FilesystemInfo {
pub fn usage_percent(&self) -> Option<f32> {
let (used, total) = (self.used_size?, self.total_size?);
if total == 0 {
return None;
}
Some((used as f64 / total as f64 * 100.0) as f32)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum DiskHealth {
Healthy,
Warning,
Critical,
Failed,
Unknown,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProcessDiskIo {
pub pid: u32,
pub read_bytes: Option<u64>,
pub write_bytes: Option<u64>,
pub read_syscalls: Option<u64>,
pub write_syscalls: Option<u64>,
pub cancelled_write_bytes: Option<u64>,
}
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("Operation not supported on this device")]
NotSupported,
#[error("No disk devices found")]
NoDevicesFound,
#[error("Device not found")]
NotFound,
#[error("Device initialization failed: {0}")]
InitializationFailed(String),
#[error("Failed to query device: {0}")]
QueryFailed(String),
#[error("Insufficient permissions: {0}")]
PermissionDenied(String),
#[error("I/O error: {0}")]
IoError(#[from] std::io::Error),
#[error("Parse error: {0}")]
ParseError(String),
#[error("Unknown error: {0}")]
Unknown(String),
}
pub mod smart_ids {
pub const READ_ERROR_RATE: u8 = 0x01;
pub const THROUGHPUT_PERFORMANCE: u8 = 0x02;
pub const SPIN_UP_TIME: u8 = 0x03;
pub const START_STOP_COUNT: u8 = 0x04;
pub const REALLOCATED_SECTORS: u8 = 0x05;
pub const SEEK_ERROR_RATE: u8 = 0x07;
pub const SEEK_TIME_PERFORMANCE: u8 = 0x08;
pub const POWER_ON_HOURS: u8 = 0x09;
pub const SPIN_RETRY_COUNT: u8 = 0x0A;
pub const CALIBRATION_RETRY_COUNT: u8 = 0x0B;
pub const POWER_CYCLE_COUNT: u8 = 0x0C;
pub const PENDING_SECTORS: u8 = 0xC5;
pub const UNCORRECTABLE_SECTORS: u8 = 0xC6;
pub const UDMA_CRC_ERROR: u8 = 0xC7;
pub const TEMPERATURE: u8 = 0xC2;
pub const HARDWARE_ECC_RECOVERED: u8 = 0xC3;
pub const REALLOCATION_EVENTS: u8 = 0xC4;
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::PathBuf;
#[test]
fn test_disk_io_total_ops() {
let stats = DiskIoStats {
read_bytes: Some(1000),
write_bytes: Some(2000),
read_ops: Some(100),
write_ops: Some(200),
read_time_ms: None,
write_time_ms: None,
queue_depth: None,
avg_latency_us: None,
read_throughput: None,
write_throughput: None,
};
assert_eq!(stats.total_ops(), Some(300));
}
#[test]
fn test_disk_io_total_bytes() {
let stats = DiskIoStats {
read_bytes: Some(1_000_000),
write_bytes: Some(2_000_000),
read_ops: Some(0),
write_ops: Some(0),
read_time_ms: None,
write_time_ms: None,
queue_depth: None,
avg_latency_us: None,
read_throughput: None,
write_throughput: None,
};
assert_eq!(stats.total_bytes(), Some(3_000_000));
}
#[test]
fn test_disk_io_zero() {
let stats = DiskIoStats {
read_bytes: Some(0),
write_bytes: Some(0),
read_ops: Some(0),
write_ops: Some(0),
read_time_ms: None,
write_time_ms: None,
queue_depth: None,
avg_latency_us: None,
read_throughput: None,
write_throughput: None,
};
assert_eq!(stats.total_ops(), Some(0));
assert_eq!(stats.total_bytes(), Some(0));
}
#[test]
fn total_over_an_unread_counter_is_absent() {
let stats = DiskIoStats {
read_bytes: Some(1_000),
write_bytes: None,
read_ops: Some(10),
write_ops: None,
read_time_ms: None,
write_time_ms: None,
queue_depth: None,
avg_latency_us: None,
read_throughput: None,
write_throughput: None,
};
assert_eq!(
stats.total_bytes(),
None,
"a total over a counter nobody read understates it silently"
);
assert_eq!(stats.total_ops(), None);
}
#[test]
fn test_filesystem_usage_percent() {
let fs = FilesystemInfo {
mount_point: PathBuf::from("/"),
fs_type: "ext4".to_string(),
total_size: Some(1_000_000_000),
used_size: Some(500_000_000),
available_size: Some(500_000_000),
total_inodes: None,
used_inodes: None,
read_only: Some(false),
};
assert!((fs.usage_percent().expect("both figures read") - 50.0).abs() < 0.01);
}
#[test]
fn test_filesystem_usage_percent_zero_total() {
let fs = FilesystemInfo {
mount_point: PathBuf::from("/"),
fs_type: "tmpfs".to_string(),
total_size: Some(0),
used_size: Some(0),
available_size: Some(0),
total_inodes: None,
used_inodes: None,
read_only: Some(false),
};
assert_eq!(fs.usage_percent(), None);
}
#[test]
fn test_filesystem_usage_percent_full() {
let fs = FilesystemInfo {
mount_point: PathBuf::from("/data"),
fs_type: "ntfs".to_string(),
total_size: Some(1_000_000),
used_size: Some(1_000_000),
available_size: Some(0),
total_inodes: None,
used_inodes: None,
read_only: Some(true),
};
assert!((fs.usage_percent().expect("both figures read") - 100.0).abs() < 0.01);
}
#[test]
fn test_disk_health_equality() {
assert_eq!(DiskHealth::Healthy, DiskHealth::Healthy);
assert_ne!(DiskHealth::Healthy, DiskHealth::Warning);
assert_ne!(DiskHealth::Warning, DiskHealth::Critical);
}
#[test]
fn test_disk_type_equality() {
assert_eq!(DiskType::NvmeSsd, DiskType::NvmeSsd);
assert_ne!(DiskType::NvmeSsd, DiskType::SataHdd);
}
#[test]
fn test_smart_ids_values() {
assert_eq!(smart_ids::POWER_ON_HOURS, 0x09);
assert_eq!(smart_ids::TEMPERATURE, 0xC2);
assert_eq!(smart_ids::REALLOCATED_SECTORS, 0x05);
assert_eq!(smart_ids::PENDING_SECTORS, 0xC5);
}
}