Lines
88.68 %
Functions
68.42 %
Branches
100 %
//! Removal of throwaway clusters a killed `xtask postgres` left in RAM.
//!
//! A SIGKILLed run never drops its `TempDir`, and `/dev/shm` is not cleared
//! until reboot. Parallel sessions run clusters on the same machine, so a
//! directory is removed only when no xtask holds its lock: the kernel drops the
//! lock when the holder dies, however it dies.
use std::fs::{File, OpenOptions};
use std::os::unix::fs::MetadataExt;
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime};
use nix::fcntl::{Flock, FlockArg};
use super::CLUSTER_PREFIX;
const LOCK_FILE: &str = ".xtask.lock";
/// Covers the instant between creating a cluster directory and locking it, and
/// directories of builds that took no lock.
const GRACE: Duration = Duration::from_secs(5 * 60);
/// What `tempfile` appends to the prefix.
const SUFFIX_LEN: usize = 6;
/// Locks `root` for as long as the returned guard lives.
pub(super) fn hold(root: &Path) -> std::io::Result<Flock<File>> {
let file = OpenOptions::new()
.create(true)
.truncate(false)
.write(true)
.open(root.join(LOCK_FILE))?;
Flock::lock(file, FlockArg::LockExclusive).map_err(|(_, errno)| errno.into())
}
fn is_cluster_name(name: &str) -> bool {
name.strip_prefix(CLUSTER_PREFIX).is_some_and(|suffix| {
suffix.len() == SUFFIX_LEN && suffix.bytes().all(|b| b.is_ascii_alphanumeric())
})
/// A directory without a lock file belongs to no live xtask that locks.
fn is_unlocked(root: &Path) -> bool {
match OpenOptions::new().write(true).open(root.join(LOCK_FILE)) {
Ok(file) => Flock::lock(file, FlockArg::LockExclusiveNonblock).is_ok(),
Err(error) => error.kind() == std::io::ErrorKind::NotFound,
/// Whether a cluster owned by `owner` is abandoned: ours, past the grace
/// period, and held by nobody.
fn is_stale(owner: u32, me: u32, age: Duration, unlocked: impl FnOnce() -> bool) -> bool {
owner == me && age >= GRACE && unlocked()
fn is_stale_dir(root: &Path, me: u32) -> bool {
let Ok(meta) = std::fs::symlink_metadata(root) else {
return false;
};
let age = meta
.modified()
.ok()
.and_then(|modified| SystemTime::now().duration_since(modified).ok())
.unwrap_or_default();
meta.is_dir() && is_stale(meta.uid(), me, age, || is_unlocked(root))
fn stale_clusters(base: &Path) -> Vec<PathBuf> {
let Ok(me) = std::fs::metadata("/proc/self").map(|meta| meta.uid()) else {
return Vec::new();
let Ok(entries) = std::fs::read_dir(base) else {
entries
.flatten()
.filter(|entry| entry.file_name().to_str().is_some_and(is_cluster_name))
.map(|entry| entry.path())
.filter(|root| is_stale_dir(root, me))
.collect()
/// Removes the abandoned clusters under `base` and returns those removed.
pub(super) fn sweep_stale_clusters(base: &Path) -> Vec<PathBuf> {
stale_clusters(base)
.into_iter()
.filter(|root| match std::fs::remove_dir_all(root) {
Ok(()) => {
println!(">> postgres: removed stale cluster {}", root.display());
true
Err(error) => {
eprintln!(
">> postgres: could not remove stale cluster {}: {error}",
root.display()
);
false
#[cfg(test)]
mod tests;