use std::{
process::Command,
time::{Duration, SystemTime, UNIX_EPOCH},
};
pub const CONTAINER_LABEL: &str = "io.sql-values.harness";
pub const STARTED_LABEL: &str = "io.sql-values.harness.started";
const STALE_AFTER: Duration = Duration::from_secs(2 * 60 * 60);
pub fn now_secs() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |since| since.as_secs())
}
pub fn labels(role: &str) -> [(String, String); 2] {
[
(CONTAINER_LABEL.to_owned(), role.to_owned()),
(STARTED_LABEL.to_owned(), now_secs().to_string()),
]
}
pub fn sweep_abandoned() {
let Ok(listed) = Command::new("docker")
.args([
"ps",
"-a",
"--filter",
&format!("label={CONTAINER_LABEL}"),
"--format",
"{{.ID}} {{.Labels}}",
])
.output()
else {
return;
};
let now = now_secs();
for line in String::from_utf8_lossy(&listed.stdout).lines() {
let Some((id, labels)) = line.split_once(' ') else {
continue;
};
let started = labels
.split(',')
.find_map(|label| label.strip_prefix(STARTED_LABEL)?.strip_prefix('='))
.and_then(|stamp| stamp.parse::<u64>().ok())
.unwrap_or(0);
if now.saturating_sub(started) < STALE_AFTER.as_secs() {
continue;
}
let _ = Command::new("docker").args(["rm", "-f", "-v", id]).output();
}
}