use std::path::Path;
use std::time::{SystemTime, UNIX_EPOCH};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ProcessIdentity {
pub pid: u32,
pub started_at: i64,
}
impl ProcessIdentity {
pub fn current() -> Self {
let pid = std::process::id();
Self {
pid,
started_at: process_start_time(pid).unwrap_or(0),
}
}
const START_TIME_TOLERANCE_SECS: i64 = 2;
pub fn check(recorded: &ProcessIdentity) -> ProcessLiveness {
match pid_alive(recorded.pid) {
Some(false) => return ProcessLiveness::Dead,
None => return ProcessLiveness::Unknown,
Some(true) => {}
}
if recorded.started_at == 0 {
return ProcessLiveness::Unknown;
}
match process_start_time(recorded.pid) {
Some(current_start)
if (current_start - recorded.started_at).abs()
<= Self::START_TIME_TOLERANCE_SECS =>
{
ProcessLiveness::Alive
}
Some(_) => ProcessLiveness::Reused,
None => ProcessLiveness::Unknown,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ProcessLiveness {
Alive,
Reused,
Dead,
Unknown,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StaleLockDecision {
KeepExisting,
Reclaim,
}
pub fn decide_stale_lock(
recorded: &ProcessIdentity,
subject: &str,
path: &Path,
) -> StaleLockDecision {
match ProcessIdentity::check(recorded) {
ProcessLiveness::Alive => StaleLockDecision::KeepExisting,
ProcessLiveness::Unknown => {
tracing::warn!(
pid = recorded.pid,
path = %path.display(),
"could not confirm whether {subject}'s recorded pid is still alive \
(no reliable liveness probe on this platform/environment, or its \
start time was never captured); conservatively treating it as still held"
);
StaleLockDecision::KeepExisting
}
ProcessLiveness::Reused => {
tracing::warn!(
stale_pid = recorded.pid,
path = %path.display(),
"{subject}'s pid was reused by an unrelated process (start time mismatch); overwriting"
);
StaleLockDecision::Reclaim
}
ProcessLiveness::Dead => {
tracing::info!(
stale_pid = recorded.pid,
path = %path.display(),
"stale {subject} from dead pid; overwriting"
);
StaleLockDecision::Reclaim
}
}
}
#[cfg(unix)]
#[allow(unsafe_code)]
fn pid_alive(pid: u32) -> Option<bool> {
let r = unsafe { libc::kill(pid as libc::pid_t, 0) };
if r == 0 {
return Some(true);
}
let err = std::io::Error::last_os_error();
Some(err.raw_os_error() != Some(libc::ESRCH))
}
#[cfg(not(unix))]
fn pid_alive(_pid: u32) -> Option<bool> {
None
}
#[cfg(unix)]
pub fn process_start_time(pid: u32) -> Option<i64> {
let output = std::process::Command::new("ps")
.args(["-o", "etime=", "-p", &pid.to_string()])
.output()
.ok()?;
if !output.status.success() {
return None;
}
let elapsed_secs = parse_elapsed(String::from_utf8(output.stdout).ok()?.trim())?;
let now = SystemTime::now().duration_since(UNIX_EPOCH).ok()?.as_secs() as i64;
plausible(now - elapsed_secs)
}
#[cfg(unix)]
fn plausible(start: i64) -> Option<i64> {
const FLOOR: i64 = 946_684_800;
let now = SystemTime::now().duration_since(UNIX_EPOCH).ok()?.as_secs() as i64;
(FLOOR..=now + 60).contains(&start).then_some(start)
}
#[cfg(not(unix))]
pub fn process_start_time(_pid: u32) -> Option<i64> {
None
}
#[cfg(unix)]
fn parse_elapsed(s: &str) -> Option<i64> {
let (days, rest) = match s.split_once('-') {
Some((d, r)) => (d.parse::<i64>().ok()?, r),
None => (0, s),
};
let parts: Vec<&str> = rest.split(':').collect();
let (hours, minutes, seconds) = match parts.as_slice() {
[h, m, s] => (
h.parse::<i64>().ok()?,
m.parse::<i64>().ok()?,
s.parse::<i64>().ok()?,
),
[m, s] => (0, m.parse::<i64>().ok()?, s.parse::<i64>().ok()?),
_ => return None,
};
Some(days * 86400 + hours * 3600 + minutes * 60 + seconds)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_start_time_that_could_not_be_one_is_not_a_reading() {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs() as i64;
assert_eq!(
plausible(now - 3600),
Some(now - 3600),
"an hour ago is fine"
);
assert_eq!(plausible(now), Some(now), "just now is fine");
assert_eq!(plausible(-38_107_284_710_668), None);
assert_eq!(plausible(0), None, "the epoch is not a process start time");
assert_eq!(plausible(now + 86_400), None, "nor is tomorrow");
}
struct Child(std::process::Child);
impl Child {
fn spawn() -> Self {
Self(
std::process::Command::new("sleep")
.arg("5")
.spawn()
.expect("spawn a short-lived child for the test"),
)
}
fn pid(&self) -> u32 {
self.0.id()
}
}
impl Drop for Child {
fn drop(&mut self) {
let _ = self.0.kill();
let _ = self.0.wait();
}
}
#[test]
fn process_identity_check_reports_alive_for_the_current_process() {
let identity = ProcessIdentity::current();
assert_eq!(ProcessIdentity::check(&identity), ProcessLiveness::Alive);
}
#[test]
fn process_identity_check_reports_dead_for_an_unused_pid() {
let fake = ProcessIdentity {
pid: 999_999_999,
started_at: 1,
};
assert_eq!(ProcessIdentity::check(&fake), ProcessLiveness::Dead);
}
#[test]
fn process_identity_check_reports_reused_when_start_time_mismatches() {
let mut identity = ProcessIdentity::current();
identity.started_at += 1_000_000; assert_eq!(ProcessIdentity::check(&identity), ProcessLiveness::Reused);
}
#[test]
fn process_identity_check_reports_alive_for_a_real_child_with_matching_start_time() {
let child = Child::spawn();
let Some(recorded_start) = process_start_time(child.pid()) else {
eprintln!("skipping: this host cannot read process start times");
return;
};
let recorded = ProcessIdentity {
pid: child.pid(),
started_at: recorded_start,
};
assert_eq!(ProcessIdentity::check(&recorded), ProcessLiveness::Alive);
}
#[test]
fn an_unreadable_start_time_is_unknown_rather_than_reused() {
let child = Child::spawn();
let recorded = ProcessIdentity {
pid: child.pid(),
started_at: 0,
};
assert_eq!(ProcessIdentity::check(&recorded), ProcessLiveness::Unknown);
}
#[test]
fn process_identity_check_reports_reused_for_a_real_pid_with_mismatched_start_time() {
let child = Child::spawn();
let recorded = ProcessIdentity {
pid: child.pid(),
started_at: 12345, };
assert_eq!(ProcessIdentity::check(&recorded), ProcessLiveness::Reused);
}
#[test]
fn process_identity_check_reports_unknown_when_recorded_start_time_was_never_captured() {
let mut identity = ProcessIdentity::current();
identity.started_at = 0;
assert_eq!(ProcessIdentity::check(&identity), ProcessLiveness::Unknown);
}
#[test]
fn decide_stale_lock_keeps_existing_for_a_confirmed_alive_process() {
let identity = ProcessIdentity::current();
assert_eq!(
decide_stale_lock(&identity, "test.lock", Path::new("/tmp/test.lock")),
StaleLockDecision::KeepExisting
);
}
#[test]
fn decide_stale_lock_keeps_existing_when_liveness_is_unverifiable() {
let mut identity = ProcessIdentity::current();
identity.started_at = 0;
assert_eq!(
decide_stale_lock(&identity, "test.lock", Path::new("/tmp/test.lock")),
StaleLockDecision::KeepExisting
);
}
#[test]
fn decide_stale_lock_reclaims_a_dead_pid() {
let fake = ProcessIdentity {
pid: 999_999_999,
started_at: 1,
};
assert_eq!(
decide_stale_lock(&fake, "test.lock", Path::new("/tmp/test.lock")),
StaleLockDecision::Reclaim
);
}
#[test]
fn decide_stale_lock_reclaims_a_reused_pid() {
let mut identity = ProcessIdentity::current();
identity.started_at += 1_000_000; assert_eq!(
decide_stale_lock(&identity, "test.lock", Path::new("/tmp/test.lock")),
StaleLockDecision::Reclaim
);
}
#[test]
#[cfg(unix)]
fn parse_elapsed_handles_every_ps_etime_shape() {
assert_eq!(parse_elapsed("00:05"), Some(5));
assert_eq!(parse_elapsed("02:30"), Some(150));
assert_eq!(parse_elapsed("01:02:03"), Some(3723));
assert_eq!(parse_elapsed("3-01:02:03"), Some(3 * 86400 + 3723));
assert_eq!(parse_elapsed("not-a-time"), None);
assert_eq!(parse_elapsed(""), None);
}
}