all_smi/storage/reader.rs
1// Copyright 2025 Lablup Inc. and Jeongkyu Shin
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Storage reader trait and implementations.
16//!
17//! This module provides the [`StorageReader`] trait for reading storage/disk
18//! information and a [`LocalStorageReader`] implementation using `sysinfo::Disks`.
19
20use std::sync::{Mutex, PoisonError};
21
22use crate::storage::disk_cache::DiskCache;
23use crate::storage::info::StorageInfo;
24use crate::utils::get_hostname;
25
26/// Trait for reading storage/disk information.
27///
28/// Implementations must be thread-safe (`Send + Sync`) to allow
29/// concurrent access from multiple threads.
30///
31/// # Example
32///
33/// ```rust,no_run
34/// use all_smi::storage::StorageReader;
35///
36/// fn print_storage(reader: &dyn StorageReader) {
37/// for storage in reader.get_storage_info() {
38/// println!("{}: {} bytes available", storage.mount_point, storage.available_bytes);
39/// }
40/// }
41/// ```
42#[allow(dead_code)] // Public API trait - used by library consumers
43pub trait StorageReader: Send + Sync {
44 /// Get information about all detected storage devices.
45 ///
46 /// Returns a vector of [`StorageInfo`] structs containing metrics for each
47 /// detected storage device. The implementation filters out system directories
48 /// and Docker-specific mounts.
49 fn get_storage_info(&self) -> Vec<StorageInfo>;
50}
51
52/// Local storage reader using `sysinfo::Disks`.
53///
54/// This reader collects storage information from the local system using
55/// the `sysinfo` crate. It applies Docker-aware filtering to exclude
56/// system directories and Docker-specific bind mounts.
57///
58/// The disk list is kept between calls in a [`DiskCache`], so repeated calls
59/// (the `record` loop, a library consumer polling) enumerate the mount table
60/// at most every 30 s rather than on every call; a volume mounted in the
61/// meantime appears within 30 s.
62///
63/// The first call enumerates the mount table on the calling thread and
64/// returns the complete list however long that takes, as this reader always
65/// has. The view and API collection loops use a cache whose first call waits
66/// at most 2 s instead, so a hung mount cannot stall their first tick (see
67/// [`DiskCache::with_blocking_first_list`] and [`DiskCache::new`]).
68///
69/// # Example
70///
71/// ```rust,no_run
72/// use all_smi::storage::{LocalStorageReader, StorageReader};
73///
74/// let reader = LocalStorageReader::new();
75/// for storage in reader.get_storage_info() {
76/// let used_bytes = storage.total_bytes - storage.available_bytes;
77/// let usage_percent = if storage.total_bytes > 0 {
78/// (used_bytes as f64 / storage.total_bytes as f64) * 100.0
79/// } else {
80/// 0.0
81/// };
82/// println!("{}: {:.1}% used", storage.mount_point, usage_percent);
83/// }
84/// ```
85#[allow(dead_code)] // Public API struct - used by library consumers
86pub struct LocalStorageReader {
87 hostname: String,
88 disks: Mutex<DiskCache>,
89}
90
91impl LocalStorageReader {
92 /// Create a new local storage reader.
93 ///
94 /// The hostname is cached at creation time to avoid repeated lookups.
95 #[allow(dead_code)] // Public API constructor - used by library consumers
96 pub fn new() -> Self {
97 Self {
98 hostname: get_hostname(),
99 disks: Mutex::new(DiskCache::with_blocking_first_list()),
100 }
101 }
102}
103
104impl Default for LocalStorageReader {
105 fn default() -> Self {
106 Self::new()
107 }
108}
109
110impl StorageReader for LocalStorageReader {
111 fn get_storage_info(&self) -> Vec<StorageInfo> {
112 // The cache holds plain disk data that stays usable after a panic in
113 // another caller, so recover from poisoning instead of propagating it.
114 self.disks
115 .lock()
116 .unwrap_or_else(PoisonError::into_inner)
117 .storage_info(&self.hostname)
118 }
119}
120
121/// Create a storage reader for the local system.
122///
123/// This is a factory function that returns a boxed [`StorageReader`] trait object,
124/// allowing for future implementations of remote or mock readers.
125///
126/// # Example
127///
128/// ```rust,no_run
129/// use all_smi::storage::create_storage_reader;
130///
131/// let reader = create_storage_reader();
132/// let storage_info = reader.get_storage_info();
133/// println!("Found {} storage device(s)", storage_info.len());
134/// ```
135#[allow(dead_code)] // Public API factory function - used by library consumers
136pub fn create_storage_reader() -> Box<dyn StorageReader> {
137 Box::new(LocalStorageReader::new())
138}
139
140#[cfg(test)]
141mod tests {
142 use super::*;
143
144 #[test]
145 fn test_local_storage_reader_creation() {
146 let reader = LocalStorageReader::new();
147 // Should not panic
148 let _ = reader.get_storage_info();
149 }
150
151 #[test]
152 fn test_local_storage_reader_default() {
153 let reader = LocalStorageReader::default();
154 let _ = reader.get_storage_info();
155 }
156
157 #[test]
158 fn test_create_storage_reader() {
159 let reader = create_storage_reader();
160 // Should return at least the root filesystem on most systems
161 let info = reader.get_storage_info();
162 // We can't guarantee any specific storage on CI, but it shouldn't panic
163 for storage in &info {
164 assert!(!storage.mount_point.is_empty());
165 assert!(!storage.hostname.is_empty());
166 }
167 }
168
169 /// The first call returns the complete list, the same rows a fresh
170 /// enumeration produces, rather than whatever a bounded wait allowed.
171 #[test]
172 fn the_first_call_returns_the_complete_list() {
173 use crate::utils::filter_docker_aware_disks;
174 use sysinfo::Disks;
175
176 let reader = LocalStorageReader::new();
177 let rows: Vec<String> = reader
178 .get_storage_info()
179 .into_iter()
180 .map(|row| row.mount_point)
181 .collect();
182
183 let disks = Disks::new_with_refreshed_list().unwrap();
184 let mut expected: Vec<String> = filter_docker_aware_disks(&disks)
185 .iter()
186 .map(|disk| disk.mount_point().to_string_lossy().into_owned())
187 .collect();
188 expected.sort();
189 if rows.len() != expected.len() {
190 // The mount table changed between the two enumerations.
191 return;
192 }
193 assert_eq!(rows, expected);
194 }
195
196 #[test]
197 fn test_storage_reader_is_send_sync() {
198 fn assert_send_sync<T: Send + Sync>() {}
199 assert_send_sync::<LocalStorageReader>();
200 }
201
202 #[test]
203 fn test_storage_info_consistency() {
204 let reader = LocalStorageReader::new();
205 let info = reader.get_storage_info();
206
207 for storage in &info {
208 // available_bytes should not exceed total_bytes
209 assert!(
210 storage.available_bytes <= storage.total_bytes,
211 "available_bytes ({}) should not exceed total_bytes ({})",
212 storage.available_bytes,
213 storage.total_bytes
214 );
215
216 // Index should be sequential
217 // (this is checked implicitly by enumerate in the implementation)
218 }
219
220 // Check indices are sequential starting from 0
221 for (expected_index, storage) in info.iter().enumerate() {
222 assert_eq!(
223 storage.index, expected_index as u32,
224 "Storage index should be sequential"
225 );
226 }
227 }
228}