Преглед изворни кода

【新增】增强 CPU 统计信息并细化模板展示

- 引入 `CpuStats` 和 `CpuUsageBreakdown` 结构,提供更详细的 CPU 使用率分解
- 支持显示用户态、内核态、低优先级进程的 CPU 占比
- 新增多核 CPU 各核心使用率展示功能
- 更新 HTML 模板以支持新的 CPU 详细信息占位符
- 调整内存部分模板结构,使进度条展示更为紧凑
- 移除旧的 `docs/example.html` 示例文件,统一使用 `templates/index.html`
- 完善相关测试用例,覆盖新增的 CPU 统计逻辑与模板渲染内容
- 修正设计文档中对模板路径的引用为 `templates/index.html`
PJ568 пре 1 година
родитељ
комит
133ea5e19e
9 измењених фајлова са 403 додато и 170 уклоњено
  1. 1 1
      Cargo.lock
  2. 1 1
      Cargo.toml
  3. 21 1
      benches/main.rs
  4. 4 56
      docs/design.md
  5. 0 49
      docs/example.html
  6. 10 0
      src/cache.rs
  7. 62 1
      src/server.rs
  8. 295 42
      src/stats.rs
  9. 9 19
      templates/index.html

+ 1 - 1
Cargo.lock

@@ -942,7 +942,7 @@ checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
 
 [[package]]
 name = "swb-sys-monitor"
-version = "0.2.1"
+version = "0.3.0"
 dependencies = [
  "anyhow",
  "clap",

+ 1 - 1
Cargo.toml

@@ -1,6 +1,6 @@
 [package]
 name = "swb-sys-monitor"
-version = "0.2.1"
+version = "0.3.0"
 authors = ["PJ568 <[email protected]>"]
 edition = "2024"
 description = "为嵌入式设备高并发监控场景设计的极简网页资源占用显示系统"

+ 21 - 1
benches/main.rs

@@ -3,13 +3,23 @@ use std::sync::Arc;
 use std::time::Duration;
 use swb_sys_monitor::cache::{SystemStatsCache, create_cache};
 use swb_sys_monitor::server::StatusServer;
-use swb_sys_monitor::stats::{SystemStats, collect_system_stats};
+use swb_sys_monitor::stats::{CpuStats, CpuUsageBreakdown, SystemStats, collect_system_stats};
 use tokio::runtime::Runtime;
 
 fn create_test_stats(hostname: &str, cpu_usage: f32) -> SystemStats {
     SystemStats {
         hostname: hostname.to_string(),
         cpu_usage,
+        cpu_stats: CpuStats {
+            overall: CpuUsageBreakdown {
+                user_percent: cpu_usage * 50.0,
+                nice_percent: cpu_usage * 10.0,
+                system_percent: cpu_usage * 40.0,
+                total_percent: cpu_usage * 100.0,
+            },
+            per_core: Vec::new(),
+            core_count: 0,
+        },
         memory_total: 1024 * 1024 * 1024,    // 1GB
         memory_used: 512 * 1024 * 1024,      // 512MB
         memory_available: 256 * 1024 * 1024, // 256MB
@@ -80,6 +90,16 @@ fn bench_html_rendering(c: &mut Criterion) {
         let large_stats = SystemStats {
             hostname: "大型测试主机名称很长很长".to_string(),
             cpu_usage: 0.95,
+            cpu_stats: CpuStats {
+                overall: CpuUsageBreakdown {
+                    user_percent: 47.5,
+                    nice_percent: 9.5,
+                    system_percent: 38.0,
+                    total_percent: 95.0,
+                },
+                per_core: Vec::new(),
+                core_count: 0,
+            },
             memory_total: 16 * 1024 * 1024 * 1024,    // 16GB
             memory_used: 8 * 1024 * 1024 * 1024,      // 8GB
             memory_available: 4 * 1024 * 1024 * 1024, // 4GB

+ 4 - 56
docs/design.md

@@ -2,7 +2,7 @@
 
 ## 项目概述
 
-本项目是一个极简的资源占用显示系统,严格按照 `docs/example.html` 设计,专为嵌入式设备监控场景设计。系统支持 200+ 高并发客户端访问,数据更新后 10 秒算过期,无 CSS 无 JS,采用服务器端渲染确保最简实现。
+本项目是一个极简的资源占用显示系统,严格按照 `templates/index.html` 设计,专为嵌入式设备监控场景设计。系统支持 200+ 高并发客户端访问,数据更新后 10 秒算过期,无 CSS 无 JS,采用服务器端渲染确保最简实现。
 
 ### 核心需求
 
@@ -13,7 +13,7 @@
 - **数据更新后 10 秒算过期**:数据未过期时无须再次获取
 - **无用户访问时无须获取**:按需更新策略
 - **无 CSS,无 JS**:纯 HTML 实现
-- **严格按照 example.html 设计**:完全遵循设计规范
+- **严格按照 templates/index.html 设计**:完全遵循设计规范
 
 ## 技术架构
 
@@ -245,59 +245,7 @@ impl StatusServer {
 
 #### HTML 模板
 
-严格按照 `docs/example.html` 设计,无 CSS,无 JS,使用 HTML 自动刷新机制:
-
-```html
-<!DOCTYPE html>
-<head lang="zh-Hans-CN">
-  <meta charset="UTF-8" />
-  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
-  <meta name="description" content="{{hostname}}的资源占用" />
-  <meta name="keywords" content="资源占用,效率工具" />
-  <meta http-equiv="refresh" content="10" />
-  <link
-    rel="icon"
-    type="image/svg+xml"
-    href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'%3E%3Ctext y='.9em' font-size='90'%3E📊%3C/text%3E%3C/svg%3E"
-  />
-  <title>{{hostname}}资源占用</title>
-</head>
-<body>
-  <fieldset>
-    <legend>{{hostname}}的资源占用</legend>
-    <fieldset>
-      <legend>处理器</legend>
-      <progress value="{{cpu_percent}}" max="100">
-        <p>{{cpu_percent}}%</p>
-      </progress>
-    </fieldset>
-    <fieldset>
-      <legend>内存</legend>
-      <p>已用:</p>
-      <progress value="{{memory_used_mb}}" max="{{memory_total_mb}}">
-        <p>{{memory_used_mb}}/{{memory_total_mb}}MB</p>
-      </progress>
-      <p>可用:</p>
-      <progress value="{{memory_available_mb}}" max="{{memory_total_mb}}">
-        <p>{{memory_available_mb}}/{{memory_total_mb}}MB</p>
-      </progress>
-      <p>缓存:</p>
-      <progress value="{{memory_cached_mb}}" max="{{memory_total_mb}}">
-        <p>{{memory_cached_mb}}/{{memory_total_mb}}MB</p>
-      </progress>
-      <p>空闲:</p>
-      <progress value="{{memory_free_mb}}" max="{{memory_total_mb}}">
-        <p>{{memory_free_mb}}/{{memory_total_mb}}MB</p>
-      </progress>
-    </fieldset>
-    <fieldset>
-      <legend>时间戳</legend>
-      <p>{{timestamp}}</p>
-    </fieldset>
-  </fieldset>
-</body>
-</html>
-```
+严格按照 `templates/index.html` 设计,无 CSS,无 JS,使用 HTML 自动刷新机制。
 
 #### 服务器端渲染
 
@@ -545,4 +493,4 @@ WantedBy=multi-user.target
 
 ## 总结
 
-本设计文档详细描述了资源占用显示系统的技术架构和实现方案。系统采用 Rust 语言,严格按照 `docs/example.html` 设计,无 CSS 无 JS,结合无锁算法和按需更新策略,实现了极简、高性能的监控解决方案。通过服务器端渲染和 10 秒数据过期机制,系统能够在嵌入式设备上稳定运行,支持 200+ 并发客户端访问,同时确保数据未过期时无须再次获取,无用户访问时无须获取。
+本设计文档详细描述了资源占用显示系统的技术架构和实现方案。系统采用 Rust 语言,严格按照 `templates/index.html` 设计,无 CSS 无 JS,结合无锁算法和按需更新策略,实现了极简、高性能的监控解决方案。通过服务器端渲染和 10 秒数据过期机制,系统能够在嵌入式设备上稳定运行,支持 200+ 并发客户端访问,同时确保数据未过期时无须再次获取,无用户访问时无须获取。

+ 0 - 49
docs/example.html

@@ -1,49 +0,0 @@
-<!DOCTYPE html>
-<head lang="zh-Hans-CN">
-  <meta charset="UTF-8" />
-  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
-  <meta name="description" content="(hostname)的资源占用" />
-  <meta name="keywords" content="资源占用,效率工具" />
-  <meta http-equiv="refresh" content="10" />
-  <link
-    rel="icon"
-    type="image/svg+xml"
-    href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'%3E%3Ctext y='.9em' font-size='90'%3E📊%3C/text%3E%3C/svg%3E"
-  />
-  <title>(hostname)资源占用</title>
-</head>
-<body>
-  <fieldset>
-    <legend>(hostname)的资源占用</legend>
-    <fieldset>
-      <legend>处理器</legend>
-      <progress value="(占用量)" max="100">
-        <p>(占用比例)%</p>
-      </progress>
-    </fieldset>
-    <fieldset>
-      <legend>内存</legend>
-      <p>已用:</p>
-      <progress value="(当前内存占用量)" max="(总内存量)">
-        <p>(当前内存占用量)/(总内存量)(单位)</p>
-      </progress>
-      <p>可用:</p>
-      <progress value="(量)" max="(总内存量)">
-        <p>(量)/(总内存量)(单位)</p>
-      </progress>
-      <p>缓存:</p>
-      <progress value="(量)" max="(总内存量)">
-        <p>(量)/(总内存量)(单位)</p>
-      </progress>
-      <p>空闲:</p>
-      <progress value="(量)" max="(总内存量)">
-        <p>(量)/(总内存量)(单位)</p>
-      </progress>
-    </fieldset>
-    <fieldset>
-      <legend>时间戳</legend>
-      <p>(数据获取时间戳)</p>
-    </fieldset>
-  </fieldset>
-</body>
-</html>

+ 10 - 0
src/cache.rs

@@ -118,6 +118,16 @@ mod tests {
         SystemStats {
             hostname: hostname.to_string(),
             cpu_usage,
+            cpu_stats: crate::stats::CpuStats {
+                overall: crate::stats::CpuUsageBreakdown {
+                    user_percent: cpu_usage * 50.0,
+                    nice_percent: cpu_usage * 10.0,
+                    system_percent: cpu_usage * 40.0,
+                    total_percent: cpu_usage * 100.0,
+                },
+                per_core: Vec::new(),
+                core_count: 0,
+            },
             memory_total: 1024 * 1024 * 1024,    // 1GB
             memory_used: 512 * 1024 * 1024,      // 512MB
             memory_available: 256 * 1024 * 1024, // 256MB

+ 62 - 1
src/server.rs

@@ -141,6 +141,24 @@ impl StatusServer {
         let free_mb = stats.memory_free / 1024 / 1024;
 
         let cpu_percent = (stats.cpu_usage * 100.0) as u32;
+        let cpu_user_percent = stats.cpu_stats.overall.user_percent as u32;
+        let cpu_system_percent = stats.cpu_stats.overall.system_percent as u32;
+        let cpu_nice_percent = stats.cpu_stats.overall.nice_percent as u32;
+
+        // 生成多核 CPU 部分
+        let cpu_cores_section = if stats.cpu_stats.core_count > 0 {
+            let mut cores_html = String::from("<fieldset><legend>处理器 - 各核心使用率</legend>");
+            for (i, core_stats) in stats.cpu_stats.per_core.iter().enumerate() {
+                cores_html.push_str(&format!(
+                    "<p>核心 {}:<progress value=\"{}\" max=\"100\">{}%</progress></p>",
+                    i, core_stats.total_percent as u32, core_stats.total_percent as u32
+                ));
+            }
+            cores_html.push_str("</fieldset>");
+            cores_html
+        } else {
+            String::new()
+        };
 
         // 格式化时间戳为可读格式
         let timestamp = format!("{:?}", stats.timestamp);
@@ -149,12 +167,16 @@ impl StatusServer {
         let template = include_str!("../templates/index.html");
 
         // 使用 String::with_capacity 预分配容量,减少重新分配
-        let mut result = String::with_capacity(template.len() + 256);
+        let mut result = String::with_capacity(template.len() + 512);
 
         // 手动替换变量,避免多次字符串分配
         result.push_str(template);
         result = result.replace("{hostname}", &stats.hostname);
         result = result.replace("{cpu_percent}", &cpu_percent.to_string());
+        result = result.replace("{cpu_user_percent}", &cpu_user_percent.to_string());
+        result = result.replace("{cpu_system_percent}", &cpu_system_percent.to_string());
+        result = result.replace("{cpu_nice_percent}", &cpu_nice_percent.to_string());
+        result = result.replace("{cpu_cores_section}", &cpu_cores_section);
         result = result.replace("{memory_total_mb}", &total_mb.to_string());
         result = result.replace("{memory_used_mb}", &used_mb.to_string());
         result = result.replace("{memory_available_mb}", &available_mb.to_string());
@@ -178,6 +200,16 @@ mod tests {
         SystemStats {
             hostname: hostname.to_string(),
             cpu_usage,
+            cpu_stats: crate::stats::CpuStats {
+                overall: crate::stats::CpuUsageBreakdown {
+                    user_percent: cpu_usage * 50.0,
+                    nice_percent: cpu_usage * 10.0,
+                    system_percent: cpu_usage * 40.0,
+                    total_percent: cpu_usage * 100.0,
+                },
+                per_core: Vec::new(),
+                core_count: 0,
+            },
             memory_total: 1024 * 1024 * 1024,    // 1GB
             memory_used: 512 * 1024 * 1024,      // 512MB
             memory_available: 256 * 1024 * 1024, // 256MB
@@ -265,6 +297,12 @@ mod tests {
         assert!(html.contains("512")); // 已用内存 MB
         assert!(html.contains("256")); // 可用内存 MB
         assert!(html.contains("128")); // 缓存内存 MB
+
+        // 检查 CPU 详细分解
+        assert!(html.contains("处理器"));
+        assert!(html.contains("用户态"));
+        assert!(html.contains("内核态"));
+        assert!(html.contains("低优先级"));
     }
 
     #[tokio::test]
@@ -282,6 +320,29 @@ mod tests {
         let stats = SystemStats {
             hostname: "test".to_string(),
             cpu_usage: 0.5,
+            cpu_stats: crate::stats::CpuStats {
+                overall: crate::stats::CpuUsageBreakdown {
+                    user_percent: 25.0,
+                    nice_percent: 5.0,
+                    system_percent: 20.0,
+                    total_percent: 50.0,
+                },
+                per_core: vec![
+                    crate::stats::CpuUsageBreakdown {
+                        user_percent: 30.0,
+                        nice_percent: 5.0,
+                        system_percent: 15.0,
+                        total_percent: 50.0,
+                    },
+                    crate::stats::CpuUsageBreakdown {
+                        user_percent: 20.0,
+                        nice_percent: 5.0,
+                        system_percent: 25.0,
+                        total_percent: 50.0,
+                    },
+                ],
+                core_count: 2,
+            },
             memory_total: 2048 * 1024 * 1024,    // 2GB
             memory_used: 1024 * 1024 * 1024,     // 1GB
             memory_available: 512 * 1024 * 1024, // 512MB

+ 295 - 42
src/stats.rs

@@ -1,28 +1,53 @@
 use std::time::Instant;
 
-/// CPU 时间统计
+/// 单个 CPU 核心的时间统计
 #[derive(Debug, Default, Clone)]
-#[allow(dead_code)] // 为未来扩展预留字段
 pub struct CpuTimes {
-    pub user: u64,
-    pub nice: u64,
-    pub system: u64,
-    pub idle: u64,
-    pub total: u64,
+    pub user: u64,   // 用户态时间
+    pub nice: u64,   // 低优先级进程时间
+    pub system: u64, // 内核态时间
+    pub idle: u64,   // 空闲时间
+    #[allow(dead_code)] // 这些字段用于完整的 CPU 时间统计,为未来功能预留
+    pub iowait: u64, // I/O 等待时间
+    #[allow(dead_code)] // 这些字段用于完整的 CPU 时间统计,为未来功能预留
+    pub irq: u64, // 硬中断时间
+    #[allow(dead_code)] // 这些字段用于完整的 CPU 时间统计,为未来功能预留
+    pub softirq: u64, // 软中断时间
+    pub total: u64,  // 总时间
 }
 
-use std::sync::atomic::{AtomicU64, Ordering};
+/// CPU 使用率分解
+#[derive(Debug, Default, Clone)]
+pub struct CpuUsageBreakdown {
+    pub user_percent: f32,   // 用户态使用率百分比
+    pub nice_percent: f32,   // 低优先级进程使用率百分比
+    pub system_percent: f32, // 内核态使用率百分比
+    pub total_percent: f32,  // 总使用率百分比
+}
+
+/// 多核 CPU 统计信息
+#[derive(Debug, Clone)]
+pub struct CpuStats {
+    pub overall: CpuUsageBreakdown,       // 总体 CPU 使用率
+    pub per_core: Vec<CpuUsageBreakdown>, // 每个 CPU 核心的使用率
+    pub core_count: usize,                // CPU 核心数量
+}
+
+use std::sync::Mutex;
+// 注意:AtomicU64 和 Ordering 导入暂时保留,为未来优化预留
+// #[allow(dead_code)] use std::sync::atomic::{AtomicU64, Ordering};
 
 /// 全局 CPU 时间缓存,用于增量计算
-static CPU_PREV_TOTAL: AtomicU64 = AtomicU64::new(0);
-static CPU_PREV_IDLE: AtomicU64 = AtomicU64::new(0);
+static CPU_PREV_OVERALL: Mutex<Option<CpuTimes>> = Mutex::new(None);
+static CPU_PREV_PER_CORE: Mutex<Vec<CpuTimes>> = Mutex::new(Vec::new());
 static CPU_TIMES_INIT: std::sync::Once = std::sync::Once::new();
 
 /// 系统资源统计数据结构
 #[derive(Debug, Clone)]
 pub struct SystemStats {
     pub hostname: String,
-    pub cpu_usage: f32,        // CPU 使用率 (0.0-1.0)
+    pub cpu_usage: f32,        // CPU 使用率 (0.0-1.0) - 保持向后兼容
+    pub cpu_stats: CpuStats,   // 详细的 CPU 统计信息
     pub memory_total: u64,     // 总内存字节数
     pub memory_used: u64,      // 已用内存字节数
     pub memory_available: u64, // 可用内存字节数
@@ -37,6 +62,11 @@ impl Default for SystemStats {
         Self {
             hostname: "未知主机".to_string(),
             cpu_usage: 0.0,
+            cpu_stats: CpuStats {
+                overall: CpuUsageBreakdown::default(),
+                per_core: Vec::new(),
+                core_count: 0,
+            },
             memory_total: 0,
             memory_used: 0,
             memory_available: 0,
@@ -94,12 +124,14 @@ pub async fn collect_system_stats() -> Result<SystemStats> {
 #[cfg(target_os = "linux")]
 async fn collect_linux_stats() -> Result<SystemStats> {
     let hostname = get_hostname()?;
-    let cpu_usage = get_cpu_usage().await?;
+    let cpu_stats = get_cpu_stats().await?;
+    let cpu_usage = cpu_stats.overall.total_percent / 100.0; // 转换为 0.0-1.0 范围
     let memory_info = get_memory_info().await?;
 
     Ok(SystemStats {
         hostname,
         cpu_usage,
+        cpu_stats,
         memory_total: memory_info.total,
         memory_used: memory_info.used,
         memory_available: memory_info.available,
@@ -159,9 +191,10 @@ async fn get_memory_info() -> Result<MemoryInfo> {
     Ok(info)
 }
 
-/// 解析 CPU 时间统计
+/// 解析 CPU 时间统计(为未来功能预留)
 #[cfg(target_os = "linux")]
 #[inline]
+#[allow(dead_code)] // 为未来功能预留
 fn parse_cpu_times(content: &str) -> Result<CpuTimes> {
     // 解析第一行 CPU 总时间
     let first_line = content
@@ -175,66 +208,162 @@ fn parse_cpu_times(content: &str) -> Result<CpuTimes> {
     let nice: u64 = parts.next().unwrap_or("0").parse().unwrap_or(0);
     let system: u64 = parts.next().unwrap_or("0").parse().unwrap_or(0);
     let idle: u64 = parts.next().unwrap_or("0").parse().unwrap_or(0);
+    let iowait: u64 = parts.next().unwrap_or("0").parse().unwrap_or(0);
+    let irq: u64 = parts.next().unwrap_or("0").parse().unwrap_or(0);
+    let softirq: u64 = parts.next().unwrap_or("0").parse().unwrap_or(0);
 
-    // 忽略其他字段 (iowait, irq, softirq, steal, guest, guest_nice)
-    let total = user + nice + system + idle;
+    // 忽略其他字段 (steal, guest, guest_nice)
+    let total = user + nice + system + idle + iowait + irq + softirq;
 
     Ok(CpuTimes {
         user,
         nice,
         system,
         idle,
+        iowait,
+        irq,
+        softirq,
         total,
     })
 }
 
-/// CPU 使用率计算(使用增量算法)
+/// 解析所有 CPU 核心的时间统计
 #[cfg(target_os = "linux")]
+#[inline]
+fn parse_all_cpu_times(content: &str) -> Result<(CpuTimes, Vec<CpuTimes>)> {
+    let lines = content.lines();
+    let mut overall_times = None;
+    let mut per_core_times = Vec::new();
+
+    for line in lines {
+        if line.starts_with("cpu") {
+            let mut parts = line.split_whitespace();
+            let cpu_label = parts.next().unwrap_or("");
+
+            let user: u64 = parts.next().unwrap_or("0").parse().unwrap_or(0);
+            let nice: u64 = parts.next().unwrap_or("0").parse().unwrap_or(0);
+            let system: u64 = parts.next().unwrap_or("0").parse().unwrap_or(0);
+            let idle: u64 = parts.next().unwrap_or("0").parse().unwrap_or(0);
+            let iowait: u64 = parts.next().unwrap_or("0").parse().unwrap_or(0);
+            let irq: u64 = parts.next().unwrap_or("0").parse().unwrap_or(0);
+            let softirq: u64 = parts.next().unwrap_or("0").parse().unwrap_or(0);
+
+            let total = user + nice + system + idle + iowait + irq + softirq;
+            let times = CpuTimes {
+                user,
+                nice,
+                system,
+                idle,
+                iowait,
+                irq,
+                softirq,
+                total,
+            };
+
+            if cpu_label == "cpu" {
+                overall_times = Some(times);
+            } else if cpu_label.starts_with("cpu") {
+                per_core_times.push(times);
+            }
+        }
+    }
+
+    match overall_times {
+        Some(overall) => Ok((overall, per_core_times)),
+        None => Err(StatsError::ParseError("无法找到 CPU 统计信息".to_string())),
+    }
+}
+
+/// CPU 使用率计算(使用增量算法)(为向后兼容预留)
+#[cfg(target_os = "linux")]
+#[allow(dead_code)] // 为向后兼容预留
 async fn get_cpu_usage() -> Result<f32> {
+    let cpu_stats = get_cpu_stats().await?;
+    Ok(cpu_stats.overall.total_percent / 100.0)
+}
+
+/// 获取详细的 CPU 统计信息
+#[cfg(target_os = "linux")]
+async fn get_cpu_stats() -> Result<CpuStats> {
     // 预估 /proc/stat 的大小,预分配容量
-    let mut content = String::with_capacity(1024);
+    let mut content = String::with_capacity(2048);
     let file_content = tokio::fs::read_to_string("/proc/stat").await?;
     content.push_str(&file_content);
 
-    let current_times = parse_cpu_times(&content)?;
+    let (current_overall, current_per_core) = parse_all_cpu_times(&content)?;
 
     // 获取之前的时间统计(线程安全)
-    let (prev_total, prev_idle) = {
+    let (prev_overall, prev_per_core) = {
+        let mut prev_overall_guard = CPU_PREV_OVERALL.lock().unwrap();
+        let mut prev_per_core_guard = CPU_PREV_PER_CORE.lock().unwrap();
+
         CPU_TIMES_INIT.call_once(|| {
-            CPU_PREV_TOTAL.store(current_times.total, Ordering::Relaxed);
-            CPU_PREV_IDLE.store(current_times.idle, Ordering::Relaxed);
+            *prev_overall_guard = Some(current_overall.clone());
+            prev_per_core_guard.clone_from(&current_per_core);
         });
-        (
-            CPU_PREV_TOTAL.load(Ordering::Relaxed),
-            CPU_PREV_IDLE.load(Ordering::Relaxed),
-        )
+
+        (prev_overall_guard.clone(), prev_per_core_guard.clone())
     };
 
     // 如果是第一次调用,返回 0 使用率
-    if prev_total == 0 && prev_idle == 0 && current_times.total != 0 {
-        CPU_PREV_TOTAL.store(current_times.total, Ordering::Relaxed);
-        CPU_PREV_IDLE.store(current_times.idle, Ordering::Relaxed);
-        return Ok(0.0);
-    }
+    let overall_usage = if let (Some(prev_overall), _) = (&prev_overall, &prev_per_core) {
+        calculate_cpu_usage_breakdown(prev_overall, &current_overall)
+    } else {
+        CpuUsageBreakdown::default()
+    };
 
-    // 计算增量
-    let total_diff = current_times.total.saturating_sub(prev_total);
-    let idle_diff = current_times.idle.saturating_sub(prev_idle);
+    // 计算每个 CPU 核心的使用率
+    let mut per_core_usage = Vec::new();
+    for (i, current_core) in current_per_core.iter().enumerate() {
+        if let Some(prev_core) = prev_per_core.get(i) {
+            per_core_usage.push(calculate_cpu_usage_breakdown(prev_core, current_core));
+        } else {
+            per_core_usage.push(CpuUsageBreakdown::default());
+        }
+    }
 
     // 更新全局缓存
-    CPU_PREV_TOTAL.store(current_times.total, Ordering::Relaxed);
-    CPU_PREV_IDLE.store(current_times.idle, Ordering::Relaxed);
+    {
+        let mut prev_overall_guard = CPU_PREV_OVERALL.lock().unwrap();
+        let mut prev_per_core_guard = CPU_PREV_PER_CORE.lock().unwrap();
+        *prev_overall_guard = Some(current_overall.clone());
+        *prev_per_core_guard = current_per_core.clone();
+    }
+
+    Ok(CpuStats {
+        overall: overall_usage,
+        per_core: per_core_usage,
+        core_count: current_per_core.len(),
+    })
+}
+
+/// 计算两个时间点之间的 CPU 使用率分解
+#[inline]
+fn calculate_cpu_usage_breakdown(prev: &CpuTimes, current: &CpuTimes) -> CpuUsageBreakdown {
+    // 计算增量
+    let total_diff = current.total.saturating_sub(prev.total);
 
-    // 如果总时间差为 0,返回 0 使用率
     if total_diff == 0 {
-        return Ok(0.0);
+        return CpuUsageBreakdown::default();
     }
 
-    // 计算使用率:1 - (空闲时间增量 / 总时间增量)
-    let usage = 1.0 - (idle_diff as f32 / total_diff as f32);
-
-    // 确保使用率在合理范围内
-    Ok(usage.clamp(0.0, 1.0))
+    let user_diff = current.user.saturating_sub(prev.user);
+    let nice_diff = current.nice.saturating_sub(prev.nice);
+    let system_diff = current.system.saturating_sub(prev.system);
+    let idle_diff = current.idle.saturating_sub(prev.idle);
+
+    // 计算各分量的使用率百分比
+    let user_percent = (user_diff as f32 / total_diff as f32) * 100.0;
+    let nice_percent = (nice_diff as f32 / total_diff as f32) * 100.0;
+    let system_percent = (system_diff as f32 / total_diff as f32) * 100.0;
+    let total_percent = (total_diff.saturating_sub(idle_diff) as f32 / total_diff as f32) * 100.0;
+
+    CpuUsageBreakdown {
+        user_percent: user_percent.clamp(0.0, 100.0),
+        nice_percent: nice_percent.clamp(0.0, 100.0),
+        system_percent: system_percent.clamp(0.0, 100.0),
+        total_percent: total_percent.clamp(0.0, 100.0),
+    }
 }
 
 #[cfg(test)]
@@ -379,4 +508,128 @@ mod tests {
             _ => panic!("应该是 UnsupportedPlatform 错误"),
         }
     }
+
+    #[test]
+    fn test_cpu_usage_breakdown_default() {
+        let breakdown = CpuUsageBreakdown::default();
+        assert_eq!(breakdown.user_percent, 0.0);
+        assert_eq!(breakdown.nice_percent, 0.0);
+        assert_eq!(breakdown.system_percent, 0.0);
+        assert_eq!(breakdown.total_percent, 0.0);
+    }
+
+    #[test]
+    fn test_parse_all_cpu_times_valid() {
+        let content = "cpu  1234 567 890 1234 100 200 300 0 0 0\n\
+                        cpu0 617 283 445 617 50 100 150\n\
+                        cpu1 617 284 445 617 50 100 150";
+        let (overall, per_core) = parse_all_cpu_times(content).unwrap();
+
+        assert_eq!(overall.user, 1234);
+        assert_eq!(overall.nice, 567);
+        assert_eq!(overall.system, 890);
+        assert_eq!(overall.idle, 1234);
+        assert_eq!(overall.iowait, 100);
+        assert_eq!(overall.irq, 200);
+        assert_eq!(overall.softirq, 300);
+
+        assert_eq!(per_core.len(), 2);
+        assert_eq!(per_core[0].user, 617);
+        assert_eq!(per_core[1].user, 617);
+    }
+
+    #[test]
+    fn test_calculate_cpu_usage_breakdown() {
+        let prev = CpuTimes {
+            user: 100,
+            nice: 20,
+            system: 50,
+            idle: 800,
+            iowait: 10,
+            irq: 5,
+            softirq: 15,
+            total: 1000,
+        };
+
+        let current = CpuTimes {
+            user: 200,
+            nice: 30,
+            system: 80,
+            idle: 1500,
+            iowait: 20,
+            irq: 10,
+            softirq: 20,
+            total: 1860,
+        };
+
+        let breakdown = calculate_cpu_usage_breakdown(&prev, &current);
+
+        // 计算增量:total_diff = 860, user_diff = 100, nice_diff = 10, system_diff = 30, idle_diff = 700
+        assert!((breakdown.user_percent - 11.63).abs() < 0.1); // 100/860 * 100
+        assert!((breakdown.nice_percent - 1.16).abs() < 0.1); // 10/860 * 100
+        assert!((breakdown.system_percent - 3.49).abs() < 0.1); // 30/860 * 100
+        assert!((breakdown.total_percent - 18.60).abs() < 0.1); // 160/860 * 100
+    }
+
+    #[test]
+    fn test_calculate_cpu_usage_breakdown_zero_diff() {
+        let prev = CpuTimes {
+            user: 100,
+            nice: 20,
+            system: 50,
+            idle: 800,
+            iowait: 10,
+            irq: 5,
+            softirq: 15,
+            total: 1000,
+        };
+
+        let current = prev.clone();
+        let breakdown = calculate_cpu_usage_breakdown(&prev, &current);
+
+        assert_eq!(breakdown.user_percent, 0.0);
+        assert_eq!(breakdown.nice_percent, 0.0);
+        assert_eq!(breakdown.system_percent, 0.0);
+        assert_eq!(breakdown.total_percent, 0.0);
+    }
+
+    #[tokio::test]
+    #[cfg(target_os = "linux")]
+    async fn test_get_cpu_stats() {
+        // 测试获取 CPU 统计信息
+        match get_cpu_stats().await {
+            Ok(stats) => {
+                assert!(stats.core_count > 0);
+                assert!(stats.per_core.len() == stats.core_count);
+                assert!(stats.overall.total_percent >= 0.0 && stats.overall.total_percent <= 100.0);
+
+                // 检查各个分量的合理性
+                assert!(stats.overall.user_percent >= 0.0 && stats.overall.user_percent <= 100.0);
+                assert!(stats.overall.nice_percent >= 0.0 && stats.overall.nice_percent <= 100.0);
+                assert!(
+                    stats.overall.system_percent >= 0.0 && stats.overall.system_percent <= 100.0
+                );
+
+                println!("CPU 统计: {:?}", stats);
+            }
+            Err(e) => {
+                // 在某些环境中可能失败
+                println!("获取 CPU 统计失败: {}", e);
+            }
+        }
+    }
+
+    #[test]
+    fn test_cpu_times_new_fields() {
+        // 更新现有的测试以包含新字段
+        let times = CpuTimes::default();
+        assert_eq!(times.user, 0);
+        assert_eq!(times.nice, 0);
+        assert_eq!(times.system, 0);
+        assert_eq!(times.idle, 0);
+        assert_eq!(times.iowait, 0); // 新字段
+        assert_eq!(times.irq, 0); // 新字段
+        assert_eq!(times.softirq, 0); // 新字段
+        assert_eq!(times.total, 0);
+    }
 }

+ 9 - 19
templates/index.html

@@ -17,28 +17,18 @@
     <legend>{hostname} 的资源占用</legend>
     <fieldset>
       <legend>处理器</legend>
-      <progress value="{cpu_percent}" max="100">
-        <p>{cpu_percent}%</p>
-      </progress>
+      <p>总体使用率:<progress value="{cpu_percent}" max="100">{cpu_percent}%</progress></p>
+      <p>用户态:<progress value="{cpu_user_percent}" max="100">{cpu_user_percent}%</p></progress></p>
+      <p>内核态:<progress value="{cpu_system_percent}" max="100">{cpu_system_percent}%</progress></p>
+      <p>低优先级:<progress value="{cpu_nice_percent}" max="100">{cpu_nice_percent}%</progress></p>
     </fieldset>
+    {cpu_cores_section}
     <fieldset>
       <legend>内存</legend>
-      <p>已用:</p>
-      <progress value="{memory_used_mb}" max="{memory_total_mb}">
-        <p>{memory_used_mb}/{memory_total_mb}MB</p>
-      </progress>
-      <p>可用:</p>
-      <progress value="{memory_available_mb}" max="{memory_total_mb}">
-        <p>{memory_available_mb}/{memory_total_mb}MB</p>
-      </progress>
-      <p>缓存:</p>
-      <progress value="{memory_cached_mb}" max="{memory_total_mb}">
-        <p>{memory_cached_mb}/{memory_total_mb}MB</p>
-      </progress>
-      <p>空闲:</p>
-      <progress value="{memory_free_mb}" max="{memory_total_mb}">
-        <p>{memory_free_mb}/{memory_total_mb}MB</p>
-      </progress>
+      <p>已用:<progress value="{memory_used_mb}" max="{memory_total_mb}">{memory_used_mb}/{memory_total_mb}MB</progress></p>
+      <p>可用:<progress value="{memory_available_mb}" max="{memory_total_mb}">{memory_available_mb}/{memory_total_mb}MB</progress></p>
+      <p>缓存:<progress value="{memory_cached_mb}" max="{memory_total_mb}">{memory_cached_mb}/{memory_total_mb}MB</progress></p>
+      <p>空闲:<progress value="{memory_free_mb}" max="{memory_total_mb}">{memory_free_mb}/{memory_total_mb}MB</progress></p>
     </fieldset>
     <fieldset>
       <legend>时间戳</legend>