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

            
8
use std::fs::{File, OpenOptions};
9
use std::os::unix::fs::MetadataExt;
10
use std::path::{Path, PathBuf};
11
use std::time::{Duration, SystemTime};
12

            
13
use nix::fcntl::{Flock, FlockArg};
14

            
15
use super::CLUSTER_PREFIX;
16

            
17
const 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.
21
const GRACE: Duration = Duration::from_secs(5 * 60);
22

            
23
/// What `tempfile` appends to the prefix.
24
const SUFFIX_LEN: usize = 6;
25

            
26
/// Locks `root` for as long as the returned guard lives.
27
10
pub(super) fn hold(root: &Path) -> std::io::Result<Flock<File>> {
28
10
    let file = OpenOptions::new()
29
10
        .create(true)
30
10
        .truncate(false)
31
10
        .write(true)
32
10
        .open(root.join(LOCK_FILE))?;
33
10
    Flock::lock(file, FlockArg::LockExclusive).map_err(|(_, errno)| errno.into())
34
10
}
35

            
36
29
fn is_cluster_name(name: &str) -> bool {
37
29
    name.strip_prefix(CLUSTER_PREFIX).is_some_and(|suffix| {
38
37
        suffix.len() == SUFFIX_LEN && suffix.bytes().all(|b| b.is_ascii_alphanumeric())
39
10
    })
40
29
}
41

            
42
/// A directory without a lock file belongs to no live xtask that locks.
43
3
fn is_unlocked(root: &Path) -> bool {
44
3
    match OpenOptions::new().write(true).open(root.join(LOCK_FILE)) {
45
2
        Ok(file) => Flock::lock(file, FlockArg::LockExclusiveNonblock).is_ok(),
46
1
        Err(error) => error.kind() == std::io::ErrorKind::NotFound,
47
    }
48
3
}
49

            
50
/// Whether a cluster owned by `owner` is abandoned: ours, past the grace
51
/// period, and held by nobody.
52
9
fn is_stale(owner: u32, me: u32, age: Duration, unlocked: impl FnOnce() -> bool) -> bool {
53
9
    owner == me && age >= GRACE && unlocked()
54
9
}
55

            
56
5
fn is_stale_dir(root: &Path, me: u32) -> bool {
57
5
    let Ok(meta) = std::fs::symlink_metadata(root) else {
58
        return false;
59
    };
60
5
    let age = meta
61
5
        .modified()
62
5
        .ok()
63
5
        .and_then(|modified| SystemTime::now().duration_since(modified).ok())
64
        .unwrap_or_default();
65
5
    meta.is_dir() && is_stale(meta.uid(), me, age, || is_unlocked(root))
66
5
}
67

            
68
14
fn stale_clusters(base: &Path) -> Vec<PathBuf> {
69
14
    let Ok(me) = std::fs::metadata("/proc/self").map(|meta| meta.uid()) else {
70
        return Vec::new();
71
    };
72
14
    let Ok(entries) = std::fs::read_dir(base) else {
73
1
        return Vec::new();
74
    };
75
13
    entries
76
13
        .flatten()
77
23
        .filter(|entry| entry.file_name().to_str().is_some_and(is_cluster_name))
78
5
        .map(|entry| entry.path())
79
5
        .filter(|root| is_stale_dir(root, me))
80
        .collect()
81
14
}
82

            
83
/// Removes the abandoned clusters under `base` and returns those removed.
84
14
pub(super) fn sweep_stale_clusters(base: &Path) -> Vec<PathBuf> {
85
14
    stale_clusters(base)
86
14
        .into_iter()
87
2
        .filter(|root| match std::fs::remove_dir_all(root) {
88
            Ok(()) => {
89
2
                println!(">> postgres: removed stale cluster {}", root.display());
90
2
                true
91
            }
92
            Err(error) => {
93
                eprintln!(
94
                    ">> postgres: could not remove stale cluster {}: {error}",
95
                    root.display()
96
                );
97
                false
98
            }
99
2
        })
100
        .collect()
101
14
}
102

            
103
#[cfg(test)]
104
mod tests;