use std::fmt;
use std::future::Future;
use std::path::{Path, PathBuf};
use std::pin::Pin;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use aither_sandbox::ContainerProbe;
use serde::{Deserialize, Serialize};
use crate::host_load::{HostLoadEvent, ReadError};
use crate::pressure::{LevelTracker, Shift};
#[cfg(test)]
mod tests;
const GIB: u64 = 1024 * 1024 * 1024;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub enum DiskPressure {
Normal,
Yellow,
Red,
Final,
}
impl fmt::Display for DiskPressure {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::Normal => "normal",
Self::Yellow => "yellow",
Self::Red => "red",
Self::Final => "final",
})
}
}
#[derive(Debug, Clone)]
pub struct DiskThresholds(Arc<Shared>);
#[derive(Debug)]
struct Shared {
yellow: AtomicU64,
red: AtomicU64,
last: AtomicU64,
}
impl DiskThresholds {
#[must_use]
pub fn new(yellow: u64, red: u64, last: u64) -> Self {
Self(Arc::new(Shared {
yellow: AtomicU64::new(yellow),
red: AtomicU64::new(red),
last: AtomicU64::new(last),
}))
}
pub fn set(&self, yellow: u64, red: u64, last: u64) {
self.0.yellow.store(yellow, Ordering::Relaxed);
self.0.red.store(red, Ordering::Relaxed);
self.0.last.store(last, Ordering::Relaxed);
}
#[must_use]
pub fn level(&self, free: u64) -> DiskPressure {
if free < self.0.last.load(Ordering::Relaxed) {
DiskPressure::Final
} else if free < self.0.red.load(Ordering::Relaxed) {
DiskPressure::Red
} else if free < self.0.yellow.load(Ordering::Relaxed) {
DiskPressure::Yellow
} else {
DiskPressure::Normal
}
}
}
impl Default for DiskThresholds {
fn default() -> Self {
Self::new(10 * GIB, 5 * GIB, 3 * GIB)
}
}
pub trait DiskReader: Send + Sync + 'static {
fn volume(&self) -> String;
fn free_bytes(&self) -> impl Future<Output = Result<u64, ReadError>> + Send;
}
pub trait DiskReaderImpl: Send + Sync {
fn volume_name(&self) -> String;
fn free_bytes_boxed(&self)
-> Pin<Box<dyn Future<Output = Result<u64, ReadError>> + Send + '_>>;
}
impl<T: DiskReader> DiskReaderImpl for T {
fn volume_name(&self) -> String {
self.volume()
}
fn free_bytes_boxed(
&self,
) -> Pin<Box<dyn Future<Output = Result<u64, ReadError>> + Send + '_>> {
Box::pin(self.free_bytes())
}
}
#[derive(Clone)]
pub struct AnyDiskReader(Arc<dyn DiskReaderImpl>);
impl AnyDiskReader {
#[must_use]
pub fn new(reader: impl DiskReader) -> Self {
Self(Arc::new(reader))
}
}
impl DiskReader for AnyDiskReader {
fn volume(&self) -> String {
self.0.volume_name()
}
async fn free_bytes(&self) -> Result<u64, ReadError> {
self.0.free_bytes_boxed().await
}
}
impl fmt::Debug for AnyDiskReader {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("AnyDiskReader")
}
}
#[derive(Debug, Clone)]
pub struct SystemDisk {
path: PathBuf,
}
impl SystemDisk {
#[must_use]
pub fn new(path: impl AsRef<Path>) -> Self {
Self {
path: path.as_ref().to_path_buf(),
}
}
}
impl DiskReader for SystemDisk {
fn volume(&self) -> String {
self.path.display().to_string()
}
async fn free_bytes(&self) -> Result<u64, ReadError> {
let path = self.path.clone();
blocking::unblock(move || system_free_bytes(&path)).await
}
}
#[cfg(unix)]
fn system_free_bytes(path: &Path) -> Result<u64, ReadError> {
use std::os::unix::ffi::OsStrExt as _;
let path_c =
std::ffi::CString::new(path.as_os_str().as_bytes()).map_err(|_| ReadError::Malformed {
what: "the volume path",
content: path.display().to_string(),
})?;
let mut stat = std::mem::MaybeUninit::<libc::statvfs>::uninit();
let status = unsafe { libc::statvfs(path_c.as_ptr(), stat.as_mut_ptr()) };
if status != 0 {
return Err(ReadError::Io {
what: "the free space of the volume",
source: std::io::Error::last_os_error(),
});
}
let stat = unsafe { stat.assume_init() };
#[allow(clippy::useless_conversion, clippy::unnecessary_cast)]
Ok(u64::from(stat.f_bavail) * stat.f_frsize as u64)
}
#[cfg(windows)]
fn system_free_bytes(path: &Path) -> Result<u64, ReadError> {
use std::os::windows::ffi::OsStrExt as _;
use windows_sys::Win32::Storage::FileSystem::GetDiskFreeSpaceExW;
let wide: Vec<u16> = path
.as_os_str()
.encode_wide()
.chain(std::iter::once(0))
.collect();
let mut available = 0_u64;
let ok = unsafe {
GetDiskFreeSpaceExW(
wide.as_ptr(),
&raw mut available,
std::ptr::null_mut(),
std::ptr::null_mut(),
)
};
if ok == 0 {
return Err(ReadError::Io {
what: "the free space of the volume",
source: std::io::Error::last_os_error(),
});
}
Ok(available)
}
#[cfg(not(any(unix, windows)))]
fn system_free_bytes(_: &Path) -> Result<u64, ReadError> {
Err(ReadError::Unsupported {
what: "the free space of the volume",
})
}
#[derive(Debug, Clone)]
pub struct ContainerDisk {
probe: ContainerProbe,
}
impl ContainerDisk {
#[must_use]
pub const fn new(probe: ContainerProbe) -> Self {
Self { probe }
}
}
#[derive(askama::Template)]
#[template(path = "container_volume.txt", escape = "none")]
struct ContainerVolume<'a> {
home: &'a aither_sandbox::ContainerPath,
}
impl DiskReader for ContainerDisk {
fn volume(&self) -> String {
askama::Template::render(&ContainerVolume {
home: self.probe.home(),
})
.expect("the container volume template renders")
}
async fn free_bytes(&self) -> Result<u64, ReadError> {
Ok(self.probe.free_bytes().await?)
}
}
#[must_use]
pub fn home_volumes(local: AnyDiskReader, container: Option<ContainerProbe>) -> Vec<AnyDiskReader> {
let mut volumes = vec![local];
volumes.extend(container.map(|probe| AnyDiskReader::new(ContainerDisk::new(probe))));
volumes
}
pub async fn read_free_bytes(readers: Vec<AnyDiskReader>) -> Vec<Option<u64>> {
futures::future::join_all(readers.iter().map(|reader| async {
reader
.free_bytes()
.await
.inspect_err(|error| {
tracing::warn!(%error, volume = reader.volume(), "disk free space could not be read");
})
.ok()
}))
.await
}
#[derive(Debug)]
struct Watched {
reader: AnyDiskReader,
level: LevelTracker<DiskPressure>,
}
#[derive(Debug)]
pub struct DiskWatch {
thresholds: DiskThresholds,
volumes: Vec<Watched>,
}
impl DiskWatch {
pub(crate) fn new(
thresholds: DiskThresholds,
readers: impl IntoIterator<Item = AnyDiskReader>,
) -> Self {
Self {
thresholds,
volumes: readers
.into_iter()
.map(|reader| Watched {
reader,
level: LevelTracker::new(DiskPressure::Normal),
})
.collect(),
}
}
pub(crate) fn readers(&self) -> Vec<AnyDiskReader> {
self.volumes
.iter()
.map(|volume| volume.reader.clone())
.collect()
}
pub(crate) fn observe(&mut self, free: &[Option<u64>]) -> Vec<HostLoadEvent> {
let thresholds = &self.thresholds;
self.volumes
.iter_mut()
.zip(free)
.filter_map(|(volume, free)| {
let free = (*free)?;
let level = thresholds.level(free);
let volume_name = volume.reader.volume();
let free = aither_sandbox::MemorySize(free);
Some(match volume.level.observe(level)? {
Shift::Rose(level) => HostLoadEvent::DiskPressureRose {
volume: volume_name,
level,
free,
},
Shift::Fell(level) => HostLoadEvent::DiskPressureDroppedBack {
volume: volume_name,
level,
free,
},
})
})
.collect()
}
}