1use 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
19const GRACE: Duration = Duration::from_secs(5 * 60);
22
23const SUFFIX_LEN: usize = 6;
25
26pub(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
42fn 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
50fn 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
83pub(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;