Skip to main content

xtask/postgres/
sweep.rs

1//! Removal of throwaway clusters a killed `xtask postgres` left in RAM.
2//!
3//! A SIGKILLed run never drops its `TempDir`, and `/dev/shm` is not cleared
4//! until reboot. Parallel sessions run clusters on the same machine, so a
5//! directory is removed only when no xtask holds its lock: the kernel drops the
6//! lock when the holder dies, however it dies.
7
8use std::fs::{File, OpenOptions};
9use std::os::unix::fs::MetadataExt;
10use std::path::{Path, PathBuf};
11use std::time::{Duration, SystemTime};
12
13use nix::fcntl::{Flock, FlockArg};
14
15use super::CLUSTER_PREFIX;
16
17const LOCK_FILE: &str = ".xtask.lock";
18
19/// Covers the instant between creating a cluster directory and locking it, and
20/// directories of builds that took no lock.
21const GRACE: Duration = Duration::from_secs(5 * 60);
22
23/// What `tempfile` appends to the prefix.
24const SUFFIX_LEN: usize = 6;
25
26/// Locks `root` for as long as the returned guard lives.
27pub(super) fn hold(root: &Path) -> std::io::Result<Flock<File>> {
28    let file = OpenOptions::new()
29        .create(true)
30        .truncate(false)
31        .write(true)
32        .open(root.join(LOCK_FILE))?;
33    Flock::lock(file, FlockArg::LockExclusive).map_err(|(_, errno)| errno.into())
34}
35
36fn is_cluster_name(name: &str) -> bool {
37    name.strip_prefix(CLUSTER_PREFIX).is_some_and(|suffix| {
38        suffix.len() == SUFFIX_LEN && suffix.bytes().all(|b| b.is_ascii_alphanumeric())
39    })
40}
41
42/// A directory without a lock file belongs to no live xtask that locks.
43fn is_unlocked(root: &Path) -> bool {
44    match OpenOptions::new().write(true).open(root.join(LOCK_FILE)) {
45        Ok(file) => Flock::lock(file, FlockArg::LockExclusiveNonblock).is_ok(),
46        Err(error) => error.kind() == std::io::ErrorKind::NotFound,
47    }
48}
49
50/// Whether a cluster owned by `owner` is abandoned: ours, past the grace
51/// period, and held by nobody.
52fn is_stale(owner: u32, me: u32, age: Duration, unlocked: impl FnOnce() -> bool) -> bool {
53    owner == me && age >= GRACE && unlocked()
54}
55
56fn is_stale_dir(root: &Path, me: u32) -> bool {
57    let Ok(meta) = std::fs::symlink_metadata(root) else {
58        return false;
59    };
60    let age = meta
61        .modified()
62        .ok()
63        .and_then(|modified| SystemTime::now().duration_since(modified).ok())
64        .unwrap_or_default();
65    meta.is_dir() && is_stale(meta.uid(), me, age, || is_unlocked(root))
66}
67
68fn stale_clusters(base: &Path) -> Vec<PathBuf> {
69    let Ok(me) = std::fs::metadata("/proc/self").map(|meta| meta.uid()) else {
70        return Vec::new();
71    };
72    let Ok(entries) = std::fs::read_dir(base) else {
73        return Vec::new();
74    };
75    entries
76        .flatten()
77        .filter(|entry| entry.file_name().to_str().is_some_and(is_cluster_name))
78        .map(|entry| entry.path())
79        .filter(|root| is_stale_dir(root, me))
80        .collect()
81}
82
83/// Removes the abandoned clusters under `base` and returns those removed.
84pub(super) fn sweep_stale_clusters(base: &Path) -> Vec<PathBuf> {
85    stale_clusters(base)
86        .into_iter()
87        .filter(|root| match std::fs::remove_dir_all(root) {
88            Ok(()) => {
89                println!(">> postgres: removed stale cluster {}", root.display());
90                true
91            }
92            Err(error) => {
93                eprintln!(
94                    ">> postgres: could not remove stale cluster {}: {error}",
95                    root.display()
96                );
97                false
98            }
99        })
100        .collect()
101}
102
103#[cfg(test)]
104mod tests;