use std::collections::BTreeMap;
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";
const SLACK: u64 = 2;
#[cfg(unix)]
const GRACE: Duration = super::stopping::GRACE;
#[derive(Debug, Clone, PartialEq, Eq)]
enum Start {
Boot { boot: String, ticks: u64 },
At(u64),
}
impl Start {
fn word(&self) -> String {
match self {
Start::Boot { boot, ticks } => format!("boot:{boot}:{ticks}"),
Start::At(secs) => format!("at:{secs}"),
}
}
fn parse(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 is(&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(PathBuf);
impl Recorded {
pub(crate) fn write(dir: &Path, pid: u32) -> Option<Recorded> {
let start = recorded_start(pid)?;
let written = owner_token(dir).and_then(|token| {
let path = dir.join(format!("{token}-{pid}.tool"));
std::fs::write(&path, format!("{pid} {}\n", start.word()))?;
Ok(path)
});
match written {
Ok(path) => Some(Recorded(path)),
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) {
if let Err(e) = crate::store::if_there(std::fs::remove_file(&self.0)) {
tracing::warn!(error = %e, path = %self.0.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 owner_gone(path: &Path) -> Option<File> {
let file = File::options().read(true).write(true).open(path).ok()?;
file.try_lock().ok().map(|()| file)
}
pub(crate) async fn end_orphans(dir: &Path) -> Vec<u32> {
let mut ended = Vec::new();
let Ok(read) = std::fs::read_dir(dir) else { 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) = owner_gone(&owner) else { continue };
let prefix = format!("{token}-");
for entry in names
.iter()
.filter(|n| n.starts_with(&prefix) && Path::new(n).extension().is_some_and(|x| x == "tool"))
{
let path = dir.join(entry);
if let Some(pid) = end_entry(&path).await {
ended.push(pid);
}
drop(crate::store::if_there(std::fs::remove_file(&path)));
}
drop(lock);
drop(crate::store::if_there(std::fs::remove_file(&owner)));
}
ended
}
async fn end_entry(path: &Path) -> Option<u32> {
let text = std::fs::read_to_string(path).ok()?;
let (pid, start) = text.trim().split_once(' ')?;
let (pid, start): (u32, Start) = (pid.parse().ok()?, Start::parse(start)?);
let now = os_start(pid).await;
if !now.as_ref().is_some_and(|now| start.is(now)) {
tracing::debug!(pid, "a tool a killed operation recorded is gone, or its id names another process: left alone");
return None;
}
tracing::warn!(pid, "ending a tool a killed operation left running");
end_group(pid).await;
Some(pid)
}
fn recorded_start(pid: u32) -> Option<Start> {
if cfg!(target_os = "linux") {
return proc_start(pid);
}
Some(Start::At(std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).ok()?.as_secs()))
}
fn proc_start(pid: u32) -> Option<Start> {
let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
let boot = std::fs::read_to_string("/proc/sys/kernel/random/boot_id").ok()?;
Some(Start::Boot {
boot: boot.trim().to_owned(),
ticks: stat_ticks(&stat)?,
})
}
fn stat_ticks(stat: &str) -> Option<u64> {
stat.rsplit_once(')')?.1.split_whitespace().nth(19)?.parse().ok()
}
async fn os_start(pid: u32) -> Option<Start> {
if cfg!(target_os = "linux") {
return proc_start(pid);
}
os_started_at(pid).await.map(Start::At)
}
#[cfg(unix)]
async fn os_started_at(pid: u32) -> Option<u64> {
let out = tokio::process::Command::new("ps")
.args(["-o", "lstart=", "-p", &pid.to_string()])
.env("TZ", "UTC")
.env("LC_ALL", "C")
.stdin(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.output()
.await
.ok()?;
out.status.success().then(|| lstart(&String::from_utf8_lossy(&out.stdout))).flatten()
}
#[cfg(windows)]
async fn os_started_at(pid: u32) -> Option<u64> {
let script = format!("[DateTimeOffset]::new((Get-Process -Id {pid} -ErrorAction Stop).StartTime).ToUnixTimeSeconds()");
let mut cmd = tokio::process::Command::new("powershell");
cmd.args(["-NoProfile", "-NonInteractive", "-Command", &script])
.stdin(std::process::Stdio::null());
headless(&mut cmd);
let out = cmd.output().await.ok()?;
out.status.success().then(|| String::from_utf8_lossy(&out.stdout).trim().parse().ok()).flatten()
}
#[cfg(any(unix, test))]
fn lstart(text: &str) -> Option<u64> {
const MONTHS: [&str; 12] = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
let words: Vec<&str> = text.split_whitespace().collect();
let [_, month, day, time, year] = words.as_slice() else { return None };
let month = u64::try_from(MONTHS.iter().position(|m| m == month)? + 1).ok()?;
let (day, year): (u64, u64) = (day.parse().ok()?, year.parse().ok()?);
let mut hms = time.split(':').map(|p| p.parse::<u64>().ok());
let (h, m, s) = (hms.next()??, hms.next()??, hms.next()??);
Some(days_since_epoch(year, month, day)? * 86_400 + h * 3600 + m * 60 + s)
}
#[cfg(any(unix, test))]
fn days_since_epoch(year: u64, month: u64, day: u64) -> Option<u64> {
let leap = |y: u64| (y.is_multiple_of(4) && !y.is_multiple_of(100)) || y.is_multiple_of(400);
let before_year: u64 = (1970..year).map(|y| if leap(y) { 366 } else { 365 }).sum();
let lengths = [31, if leap(year) { 29 } else { 28 }, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
let before_month: u64 = lengths.iter().take(usize::try_from(month.checked_sub(1)?).ok()?).sum();
Some(before_year + before_month + day.checked_sub(1)?)
}
#[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(Duration::from_millis(100)).await;
}
if let Err(e) = killpg(group, Signal::SIGKILL) {
tracing::debug!(pid, error = %e, "the tool's process group had ended");
}
}
#[cfg(windows)]
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.word()))
}
#[cfg(test)]
#[path = "ledger_tests.rs"]
mod tests;