use std::collections::BTreeMap;
use std::convert::Infallible;
use std::fs::File;
use std::io;
use std::path::{Path, PathBuf};
use std::sync::{Mutex, PoisonError};
#[cfg(unix)]
use std::time::Duration;
pub(crate) const DIR: &str = "tools";
mod group;
mod start;
#[cfg(unix)]
use group::group_members;
use group::members_still_in_group;
pub(crate) use start::os_started_at;
use start::{os_start, recorded_start};
const TOOL: &str = "tool";
const TUNNEL: &str = "tunnel";
const SLACK: u64 = 2;
#[cfg(unix)]
const GRACE: Duration = super::stopping::GRACE;
#[cfg(unix)]
const STOP_POLL: Duration = Duration::from_millis(100);
#[cfg(unix)]
const GROUP_POLL: Duration = Duration::from_secs(2);
#[derive(Debug, Clone, PartialEq, Eq)]
enum Start {
Boot { boot: String, ticks: u64 },
At(u64),
}
impl Start {
fn entry_text(&self) -> String {
match self {
Start::Boot { boot, ticks } => format!("boot:{boot}:{ticks}"),
Start::At(secs) => format!("at:{secs}"),
}
}
fn from_entry_text(word: &str) -> Option<Start> {
if let Some(rest) = word.strip_prefix("boot:") {
let (boot, ticks) = rest.rsplit_once(':')?;
return Some(Start::Boot {
boot: boot.to_owned(),
ticks: ticks.parse().ok()?,
});
}
word.strip_prefix("at:")?.parse().ok().map(Start::At)
}
fn same_process_as(&self, now: &Start) -> bool {
match (self, now) {
(Start::At(a), Start::At(b)) => a.abs_diff(*b) <= SLACK,
(a, b) => a == b,
}
}
}
#[derive(Debug)]
pub(crate) struct Recorded {
path: PathBuf,
#[cfg(unix)]
pid: u32,
}
impl Recorded {
pub(crate) fn write(dir: &Path, pid: u32, container: Option<&str>) -> Option<Recorded> {
Recorded::entry(dir, pid, container, TOOL)
}
pub(crate) fn tunnel(dir: &Path, pid: u32) -> Option<Recorded> {
Recorded::entry(dir, pid, None, TUNNEL)
}
fn entry(dir: &Path, pid: u32, container: Option<&str>, extension: &str) -> Option<Recorded> {
let start = recorded_start(pid)?;
let written = owner_token(dir).and_then(|token| {
let path = dir.join(format!("{token}-{pid}.{extension}"));
std::fs::write(&path, entry_text(pid, &start, container))?;
Ok(path)
});
match written {
Ok(path) => Some(Recorded {
path,
#[cfg(unix)]
pid,
}),
Err(e) => {
tracing::warn!(error = %e, dir = %dir.display(), "a tool couldn't be recorded: a killed operation would leave it running");
None
}
}
}
}
impl Drop for Recorded {
fn drop(&mut self) {
remove_entry(&self.path);
}
}
pub(crate) async fn note_group(recorded: Option<&Recorded>) -> Infallible {
#[cfg(unix)]
if let Some(recorded) = recorded {
let mut noted = Vec::new();
loop {
tokio::time::sleep(GROUP_POLL).await;
note_members(&recorded.path, recorded.pid, &mut noted).await;
}
}
#[cfg(not(unix))]
let _ = recorded;
std::future::pending().await
}
#[cfg(unix)]
async fn note_members(path: &Path, leader: u32, noted: &mut Vec<(u32, Start)>) {
use std::io::Write as _;
let new: Vec<(u32, Start)> = group_members(leader).await.into_iter().filter(|m| !noted.contains(m)).collect();
if new.is_empty() {
return;
}
let lines = new
.iter()
.map(|(pid, start)| format!("{pid} {}\n", start.entry_text()))
.collect::<Vec<_>>()
.concat();
let added = File::options().append(true).open(path).and_then(|mut f| f.write_all(lines.as_bytes()));
match added {
Ok(()) => noted.extend(new),
Err(e) => {
tracing::warn!(error = %e, path = %path.display(), "the processes a tool started couldn't be recorded: a killed operation would leave them running");
}
}
}
fn remove_entry(path: &Path) {
if let Err(e) = crate::store::if_there(std::fs::remove_file(path)) {
tracing::warn!(error = %e, path = %path.display(), "a tool's entry couldn't be removed");
}
}
static OWNED: Mutex<BTreeMap<PathBuf, (String, File)>> = Mutex::new(BTreeMap::new());
fn owner_token(dir: &Path) -> io::Result<String> {
let mut owned = OWNED.lock().unwrap_or_else(PoisonError::into_inner);
if let Some((token, _)) = owned.get(dir) {
if dir.join(format!("{token}.owner")).is_file() {
return Ok(token.clone());
}
owned.remove(dir);
}
crate::store::private_dir(dir)?;
let mut bytes = [0u8; 8];
getrandom::fill(&mut bytes).map_err(|e| io::Error::other(e.to_string()))?;
let token = format!("{:016x}", u64::from_le_bytes(bytes));
let lock = File::create(dir.join(format!("{token}.owner")))?;
lock.try_lock().map_err(|e| io::Error::other(e.to_string()))?;
owned.insert(dir.to_path_buf(), (token.clone(), lock));
Ok(token)
}
fn lock_if_owner_gone(path: &Path) -> Option<File> {
let file = File::options().read(true).write(true).open(path).ok()?;
file.try_lock().ok().map(|()| file)
}
pub async fn end_orphans(dir: &Path) -> Vec<u32> {
let mut ended = Vec::new();
let read = match std::fs::read_dir(dir) {
Ok(read) => read,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return ended,
Err(e) => {
tracing::warn!(error = %e, dir = %dir.display(), "the tools' ledger couldn't be read: no orphan is ended");
return ended;
}
};
let names: Vec<String> = read.flatten().filter_map(|e| e.file_name().into_string().ok()).collect();
for token in names.iter().filter_map(|n| n.strip_suffix(".owner")) {
let owner = dir.join(format!("{token}.owner"));
let Some(lock) = lock_if_owner_gone(&owner) else { continue };
let prefix = format!("{token}-");
for entry in names.iter().filter(|n| n.starts_with(&prefix)) {
let path = dir.join(entry);
if Path::new(entry).extension().is_none_or(|x| x != TOOL && x != TUNNEL) {
continue;
}
ended.extend(end_entry(&path).await);
if let Err(e) = crate::store::if_there(std::fs::remove_file(&path)) {
tracing::warn!(error = %e, path = %path.display(), "a dead process's tool entry couldn't be removed");
}
}
drop(lock);
if let Err(e) = crate::store::if_there(std::fs::remove_file(&owner)) {
tracing::warn!(error = %e, path = %owner.display(), "a dead process's owner file couldn't be removed");
}
}
ended
}
pub async fn end_tunnels(dir: &Path) -> Vec<u32> {
let mut ended = Vec::new();
let Ok(read) = std::fs::read_dir(dir) else { return ended };
for entry in read.flatten() {
let path = entry.path();
if path.extension().is_none_or(|x| x != TUNNEL) {
continue;
}
ended.extend(end_entry(&path).await);
remove_entry(&path);
}
ended
}
fn entry_text(pid: u32, start: &Start, container: Option<&str>) -> String {
match container {
Some(name) => format!("{pid} {} {name}\n", start.entry_text()),
None => format!("{pid} {}\n", start.entry_text()),
}
}
#[derive(Debug, PartialEq, Eq)]
struct Entry {
pid: u32,
start: Start,
container: Option<String>,
members: Vec<(u32, Start)>,
}
fn parse_entry(text: &str) -> Option<Entry> {
let mut lines = text.lines();
let mut words = lines.next()?.split_whitespace();
let pid = words.next()?.parse().ok()?;
let start = Start::from_entry_text(words.next()?)?;
let container = words.next().map(str::to_owned);
let members = lines
.filter_map(|line| {
let (id, started) = line.split_once(' ')?;
Some((id.parse().ok()?, Start::from_entry_text(started.trim())?))
})
.collect();
Some(Entry {
pid,
start,
container,
members,
})
}
async fn end_entry(path: &Path) -> Option<u32> {
let text = std::fs::read_to_string(path).ok()?;
let Entry {
pid,
start,
container,
members,
} = parse_entry(&text)?;
let now = os_start(pid).await;
let ended = if now.as_ref().is_some_and(|now| start.same_process_as(now)) {
tracing::warn!(pid, "ending a tool a killed operation left running");
end_group(pid).await;
true
} else if members_still_in_group(pid, &members).await {
tracing::warn!(pid, "ending what a tool a killed operation left running started, the tool itself gone");
end_group(pid).await;
true
} else {
tracing::debug!(
pid,
"a tool a killed operation recorded is gone, or its id names another process, and nothing it started is left in its group: left alone"
);
false
};
if let Some(name) = container {
remove_container(&name).await;
}
ended.then_some(pid)
}
#[expect(
clippy::disallowed_methods,
reason = "the process module's own clean-up of what a killed operation left: it can't go through the runner it cleans up after"
)]
async fn remove_container(name: &str) {
let mut cmd = tokio::process::Command::new("docker");
cmd.args(["rm", "-f", name])
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null());
#[cfg(windows)]
headless(&mut cmd);
match cmd.status().await {
Ok(status) if status.success() => {
tracing::warn!(container = name, "removed the container of a tool a killed operation left running");
}
Ok(status) => {
tracing::debug!(container = name, code = ?status.code(), "the container of a tool a killed operation recorded wasn't removed (gone already, or no engine)");
}
Err(e) => {
tracing::warn!(container = name, error = %e, "the container of a tool a killed operation recorded couldn't be removed: it may still run");
}
}
}
#[cfg(unix)]
async fn end_group(pid: u32) {
use nix::sys::signal::{Signal, killpg};
use nix::unistd::Pid;
let Some(group) = i32::try_from(pid).ok().filter(|p| *p > 1).map(Pid::from_raw) else {
return;
};
if killpg(group, Signal::SIGINT).is_err() {
return;
}
let deadline = tokio::time::Instant::now() + GRACE;
while killpg(group, None).is_ok() && tokio::time::Instant::now() < deadline {
tokio::time::sleep(STOP_POLL).await;
}
if let Err(e) = killpg(group, Signal::SIGKILL) {
tracing::debug!(pid, error = %e, "the tool's process group had ended");
}
}
#[cfg(windows)]
#[expect(clippy::disallowed_methods, reason = "the process module's own ending of a group a killed operation left")]
async fn end_group(pid: u32) {
let mut cmd = tokio::process::Command::new("taskkill");
cmd.args(["/PID", &pid.to_string(), "/T", "/F"]).stdin(std::process::Stdio::null());
headless(&mut cmd);
if let Err(e) = cmd.output().await {
tracing::warn!(pid, error = %e, "taskkill couldn't run to end a tool a killed operation left running");
}
}
#[cfg(windows)]
fn headless(cmd: &mut tokio::process::Command) {
use windows::Win32::System::Threading::CREATE_NO_WINDOW;
cmd.creation_flags(CREATE_NO_WINDOW.0);
}
#[cfg(all(test, unix))]
pub(crate) fn left_by_a_killed_process(dir: &Path, pid: u32) -> io::Result<()> {
crate::store::private_dir(dir)?;
std::fs::write(dir.join("dead.owner"), "")?;
let start = recorded_start(pid).ok_or_else(|| io::Error::other("no such process"))?;
std::fs::write(dir.join(format!("dead-{pid}.tool")), format!("{pid} {}\n", start.entry_text()))
}
#[cfg(test)]
mod tests;