فهرست منبع

【修复,缓存】修复缓存并发读取内存安全问题

Merge pull request #1 from xidongbot/fix/cache-concurrency-uaf
PJ568 2 ماه پیش
والد
کامیت
09ff0be22c
6فایلهای تغییر یافته به همراه90 افزوده شده و 68 حذف شده
  1. 11 1
      Cargo.lock
  2. 2 1
      Cargo.toml
  3. 1 1
      README.en.md
  4. 1 1
      README.md
  5. 22 26
      docs/design.md
  6. 53 38
      src/cache.rs

+ 11 - 1
Cargo.lock

@@ -88,6 +88,15 @@ version = "1.0.100"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "a23eb6b1614318a8071c9b2521f36b424b2c83db5eb3a0fead4a6c0809af6e61"
 
+[[package]]
+name = "arc-swap"
+version = "1.9.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c049c0be4daef0b145cb3555416b3b8ef5b7888a38aea1a3a155801fe7b0810b"
+dependencies = [
+ "rustversion",
+]
+
 [[package]]
 name = "async-stream"
 version = "0.3.6"
@@ -942,9 +951,10 @@ checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
 
 [[package]]
 name = "swb-sys-monitor"
-version = "0.6.0"
+version = "0.7.0"
 dependencies = [
  "anyhow",
+ "arc-swap",
  "clap",
  "criterion",
  "env_logger",

+ 2 - 1
Cargo.toml

@@ -1,6 +1,6 @@
 [package]
 name = "swb-sys-monitor"
-version = "0.6.0"
+version = "0.7.0"
 authors = ["PJ568 <[email protected]>"]
 edition = "2024"
 description = "为嵌入式设备高并发监控场景设计的极简网页资源占用显示系统"
@@ -18,6 +18,7 @@ clap = { version = "4.5", features = ["derive"] }
 log = "0.4"
 env_logger = "0.11"
 anyhow = "1.0"
+arc-swap = "1"
 
 [dev-dependencies]
 criterion = { version = "0.5", features = ["html_reports"] }

+ 1 - 1
README.en.md

@@ -87,7 +87,7 @@ curl http://localhost:8080/health
 ### Core Components
 
 1. **System Resource Acquisition Module**: Directly reads `/proc/stat` and `/proc/meminfo` to obtain system information
-2. **Lock-free Data Caching Mechanism**: Uses `AtomicPtr` and `AtomicU64` to implement thread-safe caching
+2. **Lock-free Data Caching Mechanism**: Uses `arc-swap` (ArcSwap) and `AtomicU64` to implement thread-safe caching
 3. **High-concurrency Web Server**: High-performance HTTP server based on tokio + hyper
 4. **Server-side HTML Rendering**: Pure HTML implementation, no CSS, no JS
 

+ 1 - 1
README.md

@@ -87,7 +87,7 @@ curl http://localhost:8080/health
 ### 核心组件
 
 1. **系统资源获取模块**:直接读取 `/proc/stat` 和 `/proc/meminfo` 获取系统信息
-2. **无锁数据缓存机制**:使用 `AtomicPtr` 和 `AtomicU64` 实现线程安全缓存
+2. **无锁数据缓存机制**:使用 `arc-swap`(ArcSwap)和 `AtomicU64` 实现线程安全缓存
 3. **高并发 Web 服务器**:基于 tokio + hyper 实现高性能 HTTP 服务器
 4. **服务器端 HTML 渲染**:纯 HTML 实现,无 CSS 无 JS
 

+ 22 - 26
docs/design.md

@@ -89,11 +89,13 @@ pub struct SystemStats {
 #### 核心设计
 
 ```rust
-use std::sync::atomic::{AtomicPtr, AtomicU64, Ordering};
-use std::time::{Duration, Instant};
+use arc_swap::ArcSwap;
+use std::sync::Arc;
+use std::sync::atomic::{AtomicU64, Ordering};
+use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
 
 pub struct SystemStatsCache {
-    current_stats: AtomicPtr<SystemStats>,
+    current_stats: ArcSwap<SystemStats>,
     last_update: AtomicU64,
     ttl: Duration,
 }
@@ -101,50 +103,44 @@ pub struct SystemStatsCache {
 impl SystemStatsCache {
     pub fn new(ttl: Duration) -> Self {
         Self {
-            current_stats: AtomicPtr::new(Box::into_raw(Box::new(SystemStats::default()))),
+            current_stats: ArcSwap::from_pointee(SystemStats::default()),
             last_update: AtomicU64::new(0),
             ttl,
         }
     }
 
     // 无锁读取
-    pub fn get(&self) -> Option<SystemStats> {
-        let ptr = self.current_stats.load(Ordering::Acquire);
-        if ptr.is_null() {
-            return None;
+    pub fn get(&self) -> Option<Arc<SystemStats>> {
+        let last_update = self.last_update.load(Ordering::Acquire);
+        if last_update == 0 {
+            return None; // 未初始化
         }
 
-        let stats = unsafe { &*ptr };
         let now = SystemTime::now()
             .duration_since(UNIX_EPOCH)
             .unwrap()
-            .as_secs();
-        let last_update = self.last_update.load(Ordering::Acquire);
+            .as_millis() as u64;
 
-        if now - last_update > self.ttl.as_secs() {
+        // saturating_sub 防止时钟回拨导致整数下溢
+        if now.saturating_sub(last_update) > self.ttl.as_millis() as u64 {
             return None; // 数据过期
         }
 
-        Some(stats.clone())
+        Some(self.current_stats.load_full())
     }
 
     // 原子更新
     pub fn update(&self, new_stats: SystemStats) {
-        let boxed_stats = Box::into_raw(Box::new(new_stats));
-        let old_ptr = self.current_stats.swap(boxed_stats, Ordering::Release);
+        let now = SystemTime::now()
+            .duration_since(UNIX_EPOCH)
+            .unwrap()
+            .as_millis() as u64;
 
-        // 安全释放旧数据
-        if !old_ptr.is_null() {
-            let _ = unsafe { Box::from_raw(old_ptr) };
-        }
+        // 原子替换数据(旧值由 Arc 引用计数自动释放)
+        self.current_stats.store(Arc::new(new_stats));
 
-        self.last_update.store(
-            SystemTime::now()
-                .duration_since(UNIX_EPOCH)
-                .unwrap()
-                .as_secs(),
-            Ordering::Release
-        );
+        // 最后更新时间戳,确保数据先于时间戳可见
+        self.last_update.store(now, Ordering::Release);
     }
 }
 ```

+ 53 - 38
src/cache.rs

@@ -1,11 +1,12 @@
 use crate::stats::{Result, SystemStats, collect_system_stats};
+use arc_swap::ArcSwap;
 use std::sync::Arc;
-use std::sync::atomic::{AtomicPtr, AtomicU64, Ordering};
+use std::sync::atomic::{AtomicU64, Ordering};
 use std::time::{Duration, SystemTime, UNIX_EPOCH};
 
 /// 无锁系统统计数据缓存
 pub struct SystemStatsCache {
-    current_stats: AtomicPtr<SystemStats>,
+    current_stats: ArcSwap<SystemStats>,
     last_update: AtomicU64,
     ttl: Duration,
 }
@@ -15,14 +16,14 @@ impl SystemStatsCache {
     #[inline]
     pub fn new(ttl: Duration) -> Self {
         Self {
-            current_stats: AtomicPtr::new(Box::into_raw(Box::new(SystemStats::default()))),
+            current_stats: ArcSwap::from_pointee(SystemStats::default()),
             last_update: AtomicU64::new(0),
             ttl,
         }
     }
 
     /// 无锁读取缓存数据
-    pub fn get(&self) -> Option<SystemStats> {
+    pub fn get(&self) -> Option<Arc<SystemStats>> {
         // 先加载时间戳,避免 ABA 问题
         let last_update = self.last_update.load(Ordering::Acquire);
         if last_update == 0 {
@@ -35,20 +36,13 @@ impl SystemStatsCache {
             .unwrap()
             .as_millis() as u64;
 
-        // 检查数据是否过期(使用毫秒精度)
-        if now - last_update > self.ttl.as_millis() as u64 {
+        // 检查数据是否过期(使用毫秒精度,saturating_sub 防止时钟回拨导致下溢 panic)
+        if now.saturating_sub(last_update) > self.ttl.as_millis() as u64 {
             return None; // 数据过期
         }
 
-        // 加载数据指针
-        let ptr = self.current_stats.load(Ordering::Acquire);
-        if ptr.is_null() {
-            return None;
-        }
-
-        // 安全读取数据
-        let stats = unsafe { &*ptr };
-        Some(stats.clone())
+        // 无锁加载数据快照(ArcSwap 自动管理生命周期,无 use-after-free 风险)
+        Some(self.current_stats.load_full())
     }
 
     /// 原子更新缓存数据
@@ -59,23 +53,15 @@ impl SystemStatsCache {
             .unwrap()
             .as_millis() as u64;
 
-        // 创建新数据
-        let boxed_stats = Box::into_raw(Box::new(new_stats));
-
-        // 原子替换数据指针
-        let old_ptr = self.current_stats.swap(boxed_stats, Ordering::Release);
-
-        // 安全释放旧数据
-        if !old_ptr.is_null() {
-            let _ = unsafe { Box::from_raw(old_ptr) };
-        }
+        // 原子替换数据(旧值由 Arc 引用计数自动释放,并发读者仍可安全持有)
+        self.current_stats.store(Arc::new(new_stats));
 
         // 最后更新时间戳,确保数据先于时间戳可见
         self.last_update.store(now, Ordering::Release);
     }
 
     /// 按需更新策略:只有在数据过期且有请求时才更新
-    pub async fn get_or_update(&self) -> Result<SystemStats> {
+    pub async fn get_or_update(&self) -> Result<Arc<SystemStats>> {
         // 先尝试获取缓存
         if let Some(stats) = self.get() {
             return Ok(stats);
@@ -86,16 +72,7 @@ impl SystemStatsCache {
 
         // 更新缓存
         self.update(new_stats.clone());
-        Ok(new_stats)
-    }
-}
-
-impl Drop for SystemStatsCache {
-    fn drop(&mut self) {
-        let ptr = self.current_stats.load(Ordering::Acquire);
-        if !ptr.is_null() {
-            let _ = unsafe { Box::from_raw(ptr) };
-        }
+        Ok(Arc::new(new_stats))
     }
 }
 
@@ -224,10 +201,10 @@ mod tests {
         // 验证数据存在
         assert!(cache.get().is_some());
 
-        // Drop 缓存(测试 Drop 实现)
+        // Drop 缓存(ArcSwap 自动管理内存,无需手动释放)
         drop(cache);
 
-        // 如果没有 panic,说明 Drop 实现正确
+        // 如果没有 panic,说明资源释放正确
     }
 
     #[tokio::test]
@@ -304,4 +281,42 @@ mod tests {
         sleep(Duration::from_millis(100)).await;
         assert!(cache.get().is_some());
     }
+
+    /// 并发冒烟测试:多线程同时读写不崩溃、不出现内存安全问题
+    #[test]
+    fn test_cache_concurrent_smoke() {
+        let cache = Arc::new(SystemStatsCache::new(Duration::from_secs(10)));
+        let mut handles = vec![];
+
+        // 多个读者线程循环 get / get_or_update
+        for _ in 0..4 {
+            let cache = cache.clone();
+            handles.push(std::thread::spawn(move || {
+                let rt = tokio::runtime::Builder::new_current_thread()
+                    .enable_all()
+                    .build()
+                    .expect("创建运行时失败");
+                for _ in 0..200 {
+                    if let Some(stats) = cache.get() {
+                        assert!(!stats.hostname.is_empty() || stats.cpu_usage >= 0.0);
+                    }
+                    let _ = rt.block_on(cache.get_or_update());
+                }
+            }));
+        }
+
+        // 一个写者线程循环 update
+        {
+            let cache = cache.clone();
+            handles.push(std::thread::spawn(move || {
+                for i in 0..400 {
+                    cache.update(create_test_stats("writer", i as f32 / 100.0));
+                }
+            }));
+        }
+
+        for handle in handles {
+            handle.join().expect("线程不应 panic");
+        }
+    }
 }