all_smi/storage/disk_cache.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//! Disk list shared by every storage collection path.
16//!
17//! Enumerating the mount table is what storage collection costs. On macOS
18//! `Disks::new_with_refreshed_list` runs `getfsstat` and asks CoreFoundation
19//! for every volume's properties, network shares included, which took 20 to
20//! 37 ms per tick on an M5 Max, and `Disks::refresh` does the same work.
21//! [`DiskCache`] enumerates once up front and then at most every
22//! [`LIST_REFRESH_INTERVAL`], on a background thread whose result is swapped
23//! in when it is ready, so a hung mount never holds up a tick. Between list
24//! refreshes each tick refreshes only the capacity of the volumes it shows.
25//! A volume mounted in the meantime appears with the next list.
26//!
27//! ## Available space between list refreshes on macOS
28//!
29//! sysinfo's per-disk refresh does not work for this on macOS. It re-reads
30//! the `CFURL` it created when it built the list, CFURL caches resource
31//! values on the URL object, and so it returns the list-time value forever
32//! (a 1 GB write left it unchanged). A fresh read of the value sysinfo
33//! reports, `kCFURLVolumeAvailableCapacityForImportantUsageKey`, which counts
34//! purgeable space as free, costs 6 to 15 ms per volume. `statfs` costs about
35//! a microsecond but leaves purgeable space out (91.16 GB against 101.28 GB
36//! on the same volume).
37//!
38//! So every list refresh records an anchor per volume: the exact available
39//! space from the fresh list, and `statfs` free space taken right after it.
40//! Each tick reports the anchor moved by exactly as much as `statfs` free
41//! space has moved since, never below zero and never above the volume's total
42//! (see [`anchored_available`]). Writes and deletes show on the next tick.
43//! Changes in purgeable space, such as local snapshots or caches the system
44//! may reclaim, surface at the next anchor, at most [`LIST_REFRESH_INTERVAL`]
45//! later. At an anchor the value is exactly what a fresh list reports.
46//!
47//! On other platforms the per-disk refresh runs a live `statvfs`, so it is
48//! used on every tick as it is.
49//!
50//! ## The first list
51//!
52//! A cache has no list until its first enumeration finishes, and the two
53//! kinds of caller need different things from that first call:
54//!
55//! - [`DiskCache::new`], used by the view and API collection loops, waits at
56//! most 2 s for the first list and returns no rows if it is not ready by
57//! then, so a mount that hangs at startup cannot stall a tick. The rows
58//! appear on the first tick after the enumeration finishes.
59//! - [`DiskCache::with_blocking_first_list`], used by
60//! [`LocalStorageReader`](crate::storage::LocalStorageReader), enumerates
61//! the first list on the calling thread and returns it however long that
62//! takes, the same contract `Disks::new_with_refreshed_list` gives. A
63//! library caller's first call is never empty just because enumeration
64//! was slow.
65//!
66//! After the first list both behave the same: later lists are enumerated on
67//! a background thread and never waited for.
68//!
69//! ## Network filesystems
70//!
71//! Volumes on [`NETWORK_FILE_SYSTEMS`] keep the capacity from the last list
72//! refresh instead of being queried on the tick: a `statfs` against a hung
73//! share can block indefinitely, and a value up to 30 s old is acceptable for
74//! them. (sysinfo already leaves non-local volumes out of the list on macOS,
75//! and CIFS/NFS out of it on Linux, but other network filesystems get in.)
76//!
77//! ## The per-tick refresh is bounded (issue #414)
78//!
79//! Any other volume that stops answering would still have stalled the tick,
80//! so the per-tick capacity refresh runs on one worker thread and a tick
81//! waits at most [`CAPACITY_REFRESH_BUDGET`] for it, reporting the previous
82//! values when it does not finish in time. See [`capacity`] for the
83//! protocol, and for the Linux mount-identity check that keeps a volume
84//! unmounted between list refreshes from reporting its parent's capacity.
85
86mod capacity;
87mod volume;
88
89use std::sync::mpsc::{self, Receiver, RecvTimeoutError, TryRecvError};
90use std::time::{Duration, Instant};
91
92use sysinfo::{DiskRefreshKind, Disks};
93
94use crate::storage::info::StorageInfo;
95use crate::utils::filter_docker_aware_disks;
96
97pub use capacity::CAPACITY_REFRESH_BUDGET;
98use capacity::{CapacityJob, CapacityRequest, CapacityResult, CapacityWorker, refresh_capacities};
99use volume::{Anchor, anchor_for, device_for, is_network_file_system};
100
101/// How often the mount table is enumerated again.
102pub const LIST_REFRESH_INTERVAL: Duration = Duration::from_secs(30);
103
104/// How long the first call of a [`DiskCache::new`] cache waits for the
105/// initial list. Enumeration normally takes tens of milliseconds; a volume
106/// that hangs longer than this leaves the first rows empty until the
107/// background enumeration finishes, instead of stalling the caller.
108/// [`DiskCache::with_blocking_first_list`] does not use this bound.
109const INITIAL_LIST_WAIT: Duration = Duration::from_secs(2);
110
111/// One row the storage panel shows, in display order.
112struct Volume {
113 /// Position of the volume in the listing's `Disks`.
114 index: usize,
115 mount_point: String,
116 network: bool,
117 total_bytes: u64,
118 available_bytes: u64,
119 /// `None` when `statfs` failed at list time; the list value then stands
120 /// until the next list refresh.
121 #[cfg_attr(not(target_os = "macos"), allow(dead_code))]
122 anchor: Option<Anchor>,
123 /// On Linux, the device the mount point was on at list time (see
124 /// [`capacity`]); `None` elsewhere or when it could not be read.
125 #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
126 device: Option<u64>,
127}
128
129/// One enumeration of the mount table and the rows it produces.
130struct Listing {
131 /// `None` while the capacity worker holds them for a refresh.
132 disks: Option<Disks>,
133 volumes: Vec<Volume>,
134 /// Assigned when the listing is installed in a cache; a capacity result
135 /// carrying another generation belongs to a replaced list.
136 generation: u64,
137}
138
139impl Listing {
140 /// Enumerate the mount table and work out the rows shown from it.
141 ///
142 /// Storage capacity is the only refresh kind requested: nothing reads a
143 /// disk's kind or I/O counters, and both cost extra IOKit calls.
144 fn enumerate() -> Self {
145 let disks =
146 Disks::new_with_refreshed_list_specifics(DiskRefreshKind::nothing().with_storage())
147 .ok();
148 let volumes = disks.as_ref().map(shown_volumes).unwrap_or_default();
149 Self {
150 disks,
151 volumes,
152 generation: 0,
153 }
154 }
155
156 /// What the worker needs for each volume whose capacity is refreshed on
157 /// the tick.
158 fn capacity_requests(&self) -> Vec<CapacityRequest> {
159 self.volumes
160 .iter()
161 .enumerate()
162 .filter(|(_, volume)| !volume.network)
163 .map(|(position, volume)| CapacityRequest {
164 volume: position,
165 disk: volume.index,
166 total_bytes: volume.total_bytes,
167 anchor: volume.anchor,
168 device: volume.device,
169 })
170 .collect()
171 }
172
173 /// Take the capacities of a finished refresh into the rows.
174 fn apply_capacities(&mut self, capacities: &[(usize, u64, u64)]) {
175 for &(position, total_bytes, available_bytes) in capacities {
176 if let Some(volume) = self.volumes.get_mut(position) {
177 volume.total_bytes = total_bytes;
178 volume.available_bytes = available_bytes;
179 }
180 }
181 }
182}
183
184/// The rows shown from `disks`: Docker-aware filtered, sorted by mount point,
185/// exactly as storage collection has always selected them.
186fn shown_volumes(disks: &Disks) -> Vec<Volume> {
187 let mut shown = filter_docker_aware_disks(disks);
188 shown.sort_by(|a, b| {
189 a.mount_point()
190 .to_string_lossy()
191 .cmp(&b.mount_point().to_string_lossy())
192 });
193
194 shown
195 .into_iter()
196 .filter_map(|disk| {
197 let index = disks.iter().position(|d| std::ptr::eq(d, disk))?;
198 let network = is_network_file_system(&disk.file_system().to_string_lossy());
199 Some(Volume {
200 index,
201 mount_point: disk.mount_point().to_string_lossy().into_owned(),
202 network,
203 total_bytes: disk.total_space(),
204 available_bytes: disk.available_space(),
205 anchor: if network { None } else { anchor_for(disk) },
206 device: if network { None } else { device_for(disk) },
207 })
208 })
209 .collect()
210}
211
212/// Start enumerating on a background thread. `None` when no thread could be
213/// started.
214fn spawn_enumeration() -> Option<Receiver<Listing>> {
215 let (sender, receiver) = mpsc::channel();
216 std::thread::Builder::new()
217 .name("all-smi-disk-list".to_string())
218 .spawn(move || {
219 // The receiver may be gone by the time a slow enumeration ends.
220 let _ = sender.send(Listing::enumerate());
221 })
222 .ok()?;
223 Some(receiver)
224}
225
226/// Disk list and per-tick capacity for one storage collection path.
227///
228/// The view and API collection loops and [`LocalStorageReader`] each own one
229/// and call [`storage_info`](Self::storage_info) once per tick. Rows are
230/// selected, ordered and numbered exactly as `Disks::new_with_refreshed_list`
231/// plus `filter_docker_aware_disks` always did; see the module docs for how
232/// fresh each field is and how the two constructors differ on the first call.
233///
234/// [`LocalStorageReader`]: crate::storage::LocalStorageReader
235pub struct DiskCache {
236 listing: Option<Listing>,
237 /// A list refresh running on a background thread.
238 pending: Option<Receiver<Listing>>,
239 /// The per-tick capacity refresh's worker, started on first use.
240 capacity: Option<CapacityWorker>,
241 /// The generation the next installed listing gets.
242 next_generation: u64,
243 /// When the most recent enumeration started, moved to when its list
244 /// arrived once it does, so the next enumeration is due
245 /// [`LIST_REFRESH_INTERVAL`] after the last list arrived, however long
246 /// enumerating took.
247 enumerated_at: Option<Instant>,
248 /// Whether the bounded wait for the first list has been spent.
249 waited_for_first_list: bool,
250 /// How long the first call may wait for the first list, or `None` to
251 /// build it on the calling thread however long that takes.
252 first_list_wait: Option<Duration>,
253}
254
255impl Default for DiskCache {
256 fn default() -> Self {
257 Self::new()
258 }
259}
260
261impl DiskCache {
262 /// An empty cache for a collection loop. The first
263 /// [`storage_info`](Self::storage_info) call starts enumerating the mount
264 /// table in the background and waits at most 2 s for it; if the list is
265 /// not ready by then that call returns no rows, and the rows appear on
266 /// the first call after it is.
267 pub fn new() -> Self {
268 Self::with_first_list_wait(Some(INITIAL_LIST_WAIT))
269 }
270
271 /// An empty cache whose first [`storage_info`](Self::storage_info) call
272 /// enumerates the mount table on the calling thread and returns the
273 /// complete list, however long that takes, as
274 /// `Disks::new_with_refreshed_list` does. Later calls behave as with
275 /// [`new`](Self::new). [`LocalStorageReader`] uses this so a library
276 /// caller never gets an empty first list from a slow enumeration.
277 ///
278 /// [`LocalStorageReader`]: crate::storage::LocalStorageReader
279 pub fn with_blocking_first_list() -> Self {
280 Self::with_first_list_wait(None)
281 }
282
283 fn with_first_list_wait(first_list_wait: Option<Duration>) -> Self {
284 Self {
285 listing: None,
286 pending: None,
287 capacity: None,
288 next_generation: 0,
289 enumerated_at: None,
290 waited_for_first_list: false,
291 first_list_wait,
292 }
293 }
294
295 /// Storage rows for this tick.
296 pub fn storage_info(&mut self, hostname: &str) -> Vec<StorageInfo> {
297 self.update_listing();
298 self.refresh_capacity();
299 let Some(listing) = self.listing.as_ref() else {
300 return Vec::new();
301 };
302
303 listing
304 .volumes
305 .iter()
306 .enumerate()
307 .map(|(index, volume)| StorageInfo {
308 mount_point: volume.mount_point.clone(),
309 total_bytes: volume.total_bytes,
310 available_bytes: volume.available_bytes,
311 host_id: hostname.to_string(),
312 hostname: hostname.to_string(),
313 index: index as u32,
314 })
315 .collect()
316 }
317
318 /// Make `listing` the one shown, under a new generation.
319 fn install_listing(&mut self, mut listing: Listing) {
320 listing.generation = self.next_generation;
321 self.next_generation = self.next_generation.wrapping_add(1);
322 self.listing = Some(listing);
323 self.enumerated_at = Some(Instant::now());
324 }
325
326 /// Bring the shown volumes' capacity up to date, within
327 /// [`CAPACITY_REFRESH_BUDGET`] (module docs and [`capacity`]).
328 ///
329 /// One job per tick at most: a tick that finds the previous job still
330 /// running only checks whether it has finished, and a tick that receives
331 /// a late result does not start another. After an overrun no tick waits
332 /// until a refresh has completed within the budget again.
333 fn refresh_capacity(&mut self) {
334 let Some(listing) = self.listing.as_mut() else {
335 return;
336 };
337 let deadline = Instant::now() + CAPACITY_REFRESH_BUDGET;
338
339 let worker = match self.capacity.as_mut() {
340 Some(worker) => worker,
341 None => match CapacityWorker::spawn() {
342 Some(worker) => self.capacity.insert(worker),
343 None => {
344 // No thread to run it on: refresh here, unbounded, as
345 // before the worker existed.
346 let requests = listing.capacity_requests();
347 if let Some(disks) = listing.disks.as_mut() {
348 let capacities = refresh_capacities(disks, &requests);
349 listing.apply_capacities(&capacities);
350 }
351 return;
352 }
353 },
354 };
355
356 if !worker.in_flight {
357 let Some(disks) = listing.disks.take() else {
358 // The `Disks` are with a job that never came back; the next
359 // list brings new ones.
360 return;
361 };
362 let job = CapacityJob {
363 generation: listing.generation,
364 disks,
365 requests: listing.capacity_requests(),
366 };
367 if worker.jobs.send(job).is_err() {
368 // The worker thread is gone; start a fresh one next tick.
369 self.capacity = None;
370 return;
371 }
372 worker.in_flight = true;
373 }
374
375 // After an overrun, ticks only check for results until a refresh
376 // completes within the budget again (`capacity` module docs), so a
377 // hung or slow volume costs the wait once.
378 let wait = if worker.overran {
379 Duration::ZERO
380 } else {
381 deadline.saturating_duration_since(Instant::now())
382 };
383 worker.last_wait = wait;
384 match worker.results.recv_timeout(wait) {
385 Ok(result) => {
386 worker.in_flight = false;
387 if result.took <= CAPACITY_REFRESH_BUDGET {
388 worker.overran = false;
389 }
390 Self::take_capacity_result(listing, result);
391 }
392 Err(RecvTimeoutError::Timeout) => {
393 if !worker.overran {
394 tracing::debug!(
395 budget_ms = CAPACITY_REFRESH_BUDGET.as_millis() as u64,
396 "storage capacity refresh exceeded its budget; reporting the previous values"
397 );
398 }
399 worker.overran = true;
400 }
401 Err(RecvTimeoutError::Disconnected) => {
402 // The worker thread died with the job. The `Disks` it held
403 // are lost until the next list; a fresh worker serves it.
404 self.capacity = None;
405 }
406 }
407 }
408
409 /// Apply a finished refresh to `listing`, or discard it when it belongs
410 /// to a list that has since been replaced.
411 fn take_capacity_result(listing: &mut Listing, result: CapacityResult) {
412 if result.generation != listing.generation {
413 return;
414 }
415 listing.disks = Some(result.disks);
416 listing.apply_capacities(&result.capacities);
417 }
418
419 /// Start a list refresh when one is due and swap in one that finished.
420 fn update_listing(&mut self) {
421 if self.listing.is_none() && self.first_list_wait.is_none() {
422 // No bound on the first list: build it here, as a direct
423 // enumeration would. Later lists come from the background.
424 self.install_listing(Listing::enumerate());
425 return;
426 }
427
428 let due = self
429 .enumerated_at
430 .is_none_or(|started| started.elapsed() >= LIST_REFRESH_INTERVAL);
431 if self.pending.is_none() && due {
432 self.enumerated_at = Some(Instant::now());
433 self.pending = spawn_enumeration();
434 if self.pending.is_none() && self.listing.is_none() {
435 // No thread to run it on, and no list to show meanwhile.
436 self.install_listing(Listing::enumerate());
437 }
438 }
439
440 let Some(receiver) = self.pending.as_ref() else {
441 return;
442 };
443 let received = match self.first_list_wait {
444 // Nothing to show until the first list exists, so wait for it,
445 // but only once and only for a bounded time.
446 Some(limit) if self.listing.is_none() && !self.waited_for_first_list => {
447 self.waited_for_first_list = true;
448 receiver.recv_timeout(limit).map_err(|err| match err {
449 RecvTimeoutError::Timeout => TryRecvError::Empty,
450 RecvTimeoutError::Disconnected => TryRecvError::Disconnected,
451 })
452 }
453 _ => receiver.try_recv(),
454 };
455
456 match received {
457 Ok(listing) => {
458 self.pending = None;
459 self.install_listing(listing);
460 }
461 // Still enumerating: keep showing the previous list.
462 Err(TryRecvError::Empty) => {}
463 // The enumeration thread died. Keep the previous list; the next
464 // refresh is due on the usual schedule.
465 Err(TryRecvError::Disconnected) => self.pending = None,
466 }
467 }
468}
469
470#[cfg(test)]
471#[path = "disk_cache/tests.rs"]
472mod tests;