use std::{
fs, io,
path::{Path, PathBuf},
time::Duration,
};
use subc_control::disk::{self, DiskStatus};
use subc_os::host::{self, DiskSpace};
use tokio::{sync::watch, task::JoinHandle, time::MissedTickBehavior};
use tracing::{debug, info, warn};
const SAMPLE_INTERVAL: Duration = Duration::from_secs(60);
pub(crate) type StatusReceiver = watch::Receiver<Option<DiskStatus>>;
pub(crate) fn spawn(path: PathBuf) -> (StatusReceiver, JoinHandle<()>) {
spawn_with_reader(path, host::disk_space)
}
pub(crate) fn spawn_with_reader(
path: PathBuf,
read: impl Fn(&Path) -> Option<DiskSpace> + Clone + Send + 'static,
) -> (StatusReceiver, JoinHandle<()>) {
let (tx, rx) = watch::channel(None);
let task = tokio::spawn(async move {
let mut tick = tokio::time::interval(SAMPLE_INTERVAL);
tick.set_missed_tick_behavior(MissedTickBehavior::Delay);
let mut low = false;
let mut read_failed = false;
loop {
tick.tick().await;
let (sample_path, read) = (path.clone(), read.clone());
let result = tokio::task::spawn_blocking(move || read_space(&sample_path, &read))
.await
.map_err(io::Error::other)
.and_then(|result| result);
let space = match result {
Ok(space) => space,
Err(error) => {
if !read_failed {
debug!(path = %path.display(), %error, "could not read data volume space");
}
read_failed = true;
tx.send_replace(None);
continue;
}
};
read_failed = false;
let status = DiskStatus {
path: path.to_string_lossy().into_owned(),
available_bytes: space.free_bytes,
total_bytes: space.total_bytes,
low: disk::is_low(space.free_bytes, space.total_bytes, low),
checked_at_ms: crate::clock::wall_now_ms(),
};
match (low, status.low) {
(false, true) => warn!(
path = %path.display(), available_bytes = space.free_bytes,
total_bytes = space.total_bytes, "CortexKit data volume is low on disk space"
),
(true, false) => info!(
path = %path.display(), available_bytes = space.free_bytes,
total_bytes = space.total_bytes, "CortexKit data volume has recovered disk space"
),
_ => (),
}
low = status.low;
tx.send_replace(Some(status));
}
});
(rx, task)
}
fn read_space(path: &Path, read: &impl Fn(&Path) -> Option<DiskSpace>) -> io::Result<DiskSpace> {
for ancestor in path.ancestors() {
let ancestor = if ancestor.as_os_str().is_empty() {
Path::new(".")
} else {
ancestor
};
match fs::metadata(ancestor) {
Ok(_) => {
return read(ancestor).ok_or_else(|| {
io::Error::other(format!("could not read volume at {}", ancestor.display()))
})
}
Err(error) if error.kind() == io::ErrorKind::NotFound => (),
Err(error) => return Err(error),
}
}
Err(io::Error::new(
io::ErrorKind::NotFound,
"no existing ancestor",
))
}