use std::fmt::Write as _;
use std::fs;
use std::io::{self, Write as _};
use std::os::unix::fs::MetadataExt;
use std::path::{Path, PathBuf};
use std::sync::mpsc;
use std::thread::JoinHandle;
use std::time::{Duration, Instant, SystemTime};
use rand::Rng;
pub(super) const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(10);
const STALE_AFTER: Duration = Duration::from_mins(5);
pub(super) const OBSERVE_BEFORE_TAKEOVER: Duration = Duration::from_secs(30);
const VERSION: &str = "1";
#[derive(Clone, Debug, PartialEq, Eq)]
struct Fingerprint {
boot_id: Option<String>,
pid_ns: Option<u64>,
ipc_ns: Option<u64>,
}
impl Fingerprint {
fn current() -> Self {
Self {
boot_id: boot_id(),
pid_ns: namespace("pid"),
ipc_ns: namespace("ipc"),
}
}
}
#[cfg(target_os = "linux")]
fn boot_id() -> Option<String> {
fs::read_to_string("/proc/sys/kernel/random/boot_id")
.ok()
.map(|id| id.trim().to_owned())
.filter(|id| !id.is_empty())
}
#[cfg(target_os = "macos")]
fn boot_id() -> Option<String> {
use nix::libc;
let name = c"kern.bootsessionuuid";
let mut buf = [0u8; 64];
let mut len = buf.len();
let result = unsafe {
libc::sysctlbyname(
name.as_ptr(),
buf.as_mut_ptr().cast(),
&raw mut len,
std::ptr::null_mut(),
0,
)
};
if result == 0 {
let id = String::from_utf8_lossy(&buf[..len]);
let id = id.trim_end_matches('\0').trim();
(!id.is_empty()).then(|| id.to_owned())
} else {
None
}
}
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
fn boot_id() -> Option<String> {
None
}
fn namespace(kind: &str) -> Option<u64> {
if cfg!(target_os = "linux") {
fs::metadata(format!("/proc/self/ns/{kind}"))
.ok()
.map(|m| m.ino())
} else {
None
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Relation {
SameNamespace,
SameKernel,
OtherKernel,
Copy,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct Record {
fingerprint: Fingerprint,
namespace_known: bool,
pub(super) hostname: String,
pid: u32,
datadir: (u64, u64),
}
impl Record {
pub(super) fn current(datadir: &Path) -> io::Result<Self> {
let metadata = fs::metadata(datadir)?;
Ok(Self {
fingerprint: Fingerprint::current(),
namespace_known: true,
hostname: nix::unistd::gethostname()
.map_or_default(|name| name.to_string_lossy().into_owned()),
pid: std::process::id(),
datadir: (metadata.dev(), metadata.ino()),
})
}
pub(super) fn with_unknown_namespace(mut self) -> Self {
self.namespace_known = false;
self.fingerprint.pid_ns = None;
self.fingerprint.ipc_ns = None;
self
}
pub(super) fn relation(&self, current: &Record) -> Relation {
let (ours, theirs) = (¤t.fingerprint, &self.fingerprint);
match (&ours.boot_id, &theirs.boot_id) {
(Some(ours_id), Some(theirs_id)) if ours_id == theirs_id => {
if self.datadir != current.datadir {
Relation::Copy
} else if self.namespace_known
&& ours.pid_ns == theirs.pid_ns
&& ours.ipc_ns == theirs.ipc_ns
{
Relation::SameNamespace
} else {
Relation::SameKernel
}
}
_ => Relation::OtherKernel,
}
}
fn serialize(&self) -> String {
let mut out = String::new();
let mut line = |key: &str, value: &dyn std::fmt::Display| {
writeln!(out, "{key}={value}").expect("writing to a String cannot fail");
};
line("version", &VERSION);
line("hostname", &self.hostname.replace('\n', " "));
line("pid", &self.pid);
if let Some(boot_id) = &self.fingerprint.boot_id {
line("boot_id", boot_id);
}
if let Some(pid_ns) = self.fingerprint.pid_ns {
line("pid_ns", &pid_ns);
}
if let Some(ipc_ns) = self.fingerprint.ipc_ns {
line("ipc_ns", &ipc_ns);
}
if !self.namespace_known {
line("namespace", &"unknown");
}
line("datadir_dev", &self.datadir.0);
line("datadir_ino", &self.datadir.1);
out
}
fn parse(text: &str) -> Option<Self> {
let mut version = None;
let (mut hostname, mut pid, mut boot_id, mut pid_ns, mut ipc_ns) =
(None, None, None, None, None);
let (mut dev, mut ino) = (None, None);
let mut namespace_known = true;
for line in text.lines() {
let (key, value) = line.split_once('=')?;
match key {
"version" => version = Some(value),
"hostname" => hostname = Some(value.to_owned()),
"pid" => pid = Some(value.parse().ok()?),
"boot_id" => boot_id = Some(value.to_owned()),
"pid_ns" => pid_ns = Some(value.parse().ok()?),
"ipc_ns" => ipc_ns = Some(value.parse().ok()?),
"namespace" if value == "unknown" => namespace_known = false,
"namespace" => return None,
"datadir_dev" => dev = Some(value.parse().ok()?),
"datadir_ino" => ino = Some(value.parse().ok()?),
_ => (),
}
}
if version == Some(VERSION) {
Some(Self {
fingerprint: Fingerprint { boot_id, pid_ns, ipc_ns },
namespace_known,
hostname: hostname?,
pid: pid?,
datadir: (dev?, ino?),
})
} else {
None
}
}
}
#[derive(Debug)]
pub(super) struct Found {
pub(super) record: Record,
pub(super) age: Duration,
}
impl Found {
pub(super) fn is_fresh(&self) -> bool {
self.age <= STALE_AFTER
}
}
pub(super) fn read(path: &Path) -> io::Result<Option<Found>> {
const ATTEMPTS: u32 = 3;
for attempt in 1..=ATTEMPTS {
let mut file = match fs::File::open(path) {
Ok(file) => file,
Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(None),
Err(err) => return Err(err),
};
let modified = file.metadata()?.modified()?;
let mut text = String::new();
io::Read::read_to_string(&mut file, &mut text)?;
if let Some(record) = Record::parse(&text) {
let age = SystemTime::now()
.duration_since(modified)
.unwrap_or_default();
return Ok(Some(Found { record, age }));
} else if attempt < ATTEMPTS {
std::thread::sleep(Duration::from_millis(100));
continue;
} else {
continue;
}
}
Err(io::Error::new(
io::ErrorKind::InvalidData,
format!("could not understand owner file {}", path.display()),
))
}
pub(super) fn ago(duration: Duration) -> String {
let secs = duration.as_secs();
match secs {
0..=10 => "just now".to_owned(),
11..=59 => format!("{secs}s ago"),
60..=3599 => format!("{}m {}s ago", secs / 60, secs % 60),
3600..=86399 => format!("{}h {}m ago", secs / 3600, secs % 3600 / 60),
_ => format!("{}d {}h ago", secs / 86400, secs % 86400 / 3600),
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Observed {
Unchanged,
Changed,
Gone,
Interrupted,
}
pub(super) fn observe(
path: &Path,
window: Duration,
interrupted: &dyn Fn() -> bool,
) -> io::Result<Observed> {
let identity = || -> io::Result<Option<_>> {
match fs::File::open(path) {
Ok(file) => {
let metadata = file.metadata()?;
Ok(Some((metadata.dev(), metadata.ino(), metadata.modified()?)))
}
Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(None),
Err(err) => Err(err),
}
};
match identity()? {
None => Ok(Observed::Gone),
Some(initial) => {
let poll = (window / 10).min(Duration::from_secs(1));
let deadline = Instant::now() + window;
loop {
std::thread::sleep(poll.min(deadline.saturating_duration_since(Instant::now())));
if interrupted() {
return Ok(Observed::Interrupted);
} else {
match identity()? {
None => return Ok(Observed::Gone),
Some(current) if current != initial => return Ok(Observed::Changed),
Some(_) if Instant::now() >= deadline => return Ok(Observed::Unchanged),
Some(_) => continue,
}
}
}
}
}
}
pub(super) fn claim(path: &Path, record: &Record) -> io::Result<bool> {
claim_via(path, record, std::iter::repeat_with(|| temp_path(path)))
}
fn claim_via(
path: &Path,
record: &Record,
temps: impl IntoIterator<Item = PathBuf>,
) -> io::Result<bool> {
let (temp, mut file) = create_temp(temps)?;
let result = (|| {
file.write_all(record.serialize().as_bytes())?;
file.sync_all()?;
match fs::hard_link(&temp, path) {
Ok(()) => Ok(true),
Err(err) if err.kind() == io::ErrorKind::AlreadyExists => Ok(false),
Err(err) => Err(err),
}
})();
drop(file);
match fs::remove_file(&temp) {
Err(err) if err.kind() != io::ErrorKind::NotFound && result.is_ok() => Err(err),
_ => result,
}
}
fn create_temp(temps: impl IntoIterator<Item = PathBuf>) -> io::Result<(PathBuf, fs::File)> {
const ATTEMPTS: usize = 8;
for temp in temps.into_iter().take(ATTEMPTS) {
match fs::File::options().write(true).create_new(true).open(&temp) {
Ok(file) => return Ok((temp, file)),
Err(err) if err.kind() == io::ErrorKind::AlreadyExists => continue,
Err(err) => return Err(err),
}
}
Err(io::Error::new(
io::ErrorKind::AlreadyExists,
"could not create a temporary file for the owner record",
))
}
fn temp_path(path: &Path) -> PathBuf {
let mut name = path.file_name().unwrap_or_default().to_owned();
name.push(format!(".{:016x}", rand::rng().next_u64()));
path.with_file_name(name)
}
pub(super) fn release(path: &Path) -> io::Result<()> {
match fs::remove_file(path) {
Err(err) if err.kind() != io::ErrorKind::NotFound => Err(err),
_ => Ok(()),
}
}
fn touch(path: &Path) -> io::Result<()> {
use nix::sys::stat::{utimensat, UtimensatFlags};
use nix::sys::time::TimeSpec;
match utimensat(
nix::fcntl::AT_FDCWD,
path,
&TimeSpec::UTIME_NOW,
&TimeSpec::UTIME_NOW,
UtimensatFlags::FollowSymlink,
) {
Ok(()) | Err(nix::errno::Errno::ENOENT) => Ok(()),
Err(errno) => Err(errno.into()),
}
}
#[derive(Debug)]
pub(super) struct Heartbeat {
stop: Option<mpsc::Sender<()>>,
thread: Option<JoinHandle<()>>,
}
impl Heartbeat {
pub(super) fn start(path: PathBuf, interval: Duration) -> Self {
let (stop, stopped) = mpsc::channel::<()>();
let thread = std::thread::Builder::new()
.name("pgdo-heartbeat".into())
.spawn(move || loop {
if let Err(err) = touch(&path) {
log::warn!("Could not update {}: {err}", path.display());
}
if matches!(
stopped.recv_timeout(interval),
Err(mpsc::RecvTimeoutError::Timeout)
) {
continue;
} else {
break;
}
})
.ok();
if thread.is_none() {
log::warn!(
"Could not start heartbeat thread; other hosts may think the cluster is idle."
);
}
Self { stop: Some(stop), thread }
}
}
impl Drop for Heartbeat {
fn drop(&mut self) {
drop(self.stop.take());
if let Some(thread) = self.thread.take() {
let _ = thread.join();
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn record(boot_id: &str, pid_ns: u64, datadir: (u64, u64)) -> Record {
Record {
fingerprint: Fingerprint {
boot_id: Some(boot_id.into()),
pid_ns: Some(pid_ns),
ipc_ns: Some(1),
},
namespace_known: true,
hostname: "example".into(),
pid: 1234,
datadir,
}
}
#[test]
fn fingerprint_of_current_process_identifies_kernel() {
let fingerprint = Fingerprint::current();
if cfg!(any(target_os = "linux", target_os = "macos")) {
assert!(fingerprint.boot_id.is_some());
}
assert_eq!(fingerprint.pid_ns.is_some(), cfg!(target_os = "linux"));
}
#[test]
fn serialize_and_parse_round_trip() {
let record = record("boot", 42, (1, 2));
assert_eq!(Record::parse(&record.serialize()), Some(record));
let mut record = Record::current(Path::new("/")).unwrap();
record.fingerprint.pid_ns = None;
record.fingerprint.boot_id = None;
assert_eq!(Record::parse(&record.serialize()), Some(record));
}
#[test]
fn serialize_and_parse_round_trip_with_unknown_namespace() {
let joined = record("boot", 42, (1, 2)).with_unknown_namespace();
assert!(joined.serialize().contains("namespace=unknown\n"));
assert_eq!(Record::parse(&joined.serialize()), Some(joined));
let text = record("boot", 42, (1, 2)).serialize() + "namespace=bogus\n";
assert_eq!(Record::parse(&text), None);
}
#[test]
fn relation_with_unknown_namespace_is_never_same_namespace() {
let current = record("boot", 42, (1, 2));
let joined = current.clone().with_unknown_namespace();
assert_eq!(joined.relation(¤t), Relation::SameKernel);
assert_eq!(joined.relation(&joined), Relation::SameKernel);
let mut copied = joined.clone();
copied.datadir = (1, 3);
assert_eq!(copied.relation(¤t), Relation::Copy);
let mut other = joined.clone();
other.fingerprint.boot_id = Some("other".into());
assert_eq!(other.relation(¤t), Relation::OtherKernel);
}
#[test]
fn ago_describes_durations() {
let ago = |secs| super::ago(Duration::from_secs(secs));
assert_eq!(super::ago(Duration::from_millis(999)), "just now");
assert_eq!(ago(10), "just now");
assert_eq!(ago(11), "11s ago");
assert_eq!(ago(45), "45s ago");
assert_eq!(ago(73), "1m 13s ago");
assert_eq!(ago(302), "5m 2s ago");
assert_eq!(ago(3 * 3600 + 7 * 60 + 5), "3h 7m ago");
assert_eq!(ago(2 * 86400 + 4 * 3600), "2d 4h ago");
}
#[test]
fn parse_rejects_malformed_or_unknown_versions() {
assert_eq!(Record::parse(""), None);
assert_eq!(Record::parse("version=1\nhostname=x\n"), None);
assert_eq!(Record::parse("garbage"), None);
let text = record("boot", 42, (1, 2))
.serialize()
.replace("version=1", "version=2");
assert_eq!(Record::parse(&text), None);
}
#[test]
fn relation() {
let current = record("boot", 42, (1, 2));
assert_eq!(
record("boot", 42, (1, 2)).relation(¤t),
Relation::SameNamespace
);
assert_eq!(
record("boot", 43, (1, 2)).relation(¤t),
Relation::SameKernel
);
assert_eq!(
record("boot", 42, (1, 3)).relation(¤t),
Relation::Copy
);
assert_eq!(
record("other", 42, (1, 2)).relation(¤t),
Relation::OtherKernel
);
assert_eq!(
record("other", 42, (9, 9)).relation(¤t),
Relation::OtherKernel
);
let mut unknown = record("boot", 42, (1, 2));
unknown.fingerprint.boot_id = None;
assert_eq!(unknown.relation(¤t), Relation::OtherKernel);
}
#[test]
fn claim_is_exclusive_and_read_reports_age() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let path = dir.path().join("pgdo.owner");
let first = record("boot", 1, (1, 2));
assert!(claim(&path, &first)?);
assert!(!claim(&path, &record("boot", 2, (1, 2)))?);
assert_eq!(fs::read_dir(dir.path())?.count(), 1);
let found = read(&path)?.expect("owner file missing");
assert_eq!(found.record, first);
assert!(found.is_fresh());
let file = fs::File::options().write(true).open(&path)?;
file.set_modified(SystemTime::now() - STALE_AFTER * 2)?;
assert!(!read(&path)?.expect("owner file missing").is_fresh());
touch(&path)?;
assert!(read(&path)?.expect("owner file missing").is_fresh());
release(&path)?;
assert!(read(&path)?.is_none());
release(&path)?; Ok(())
}
#[test]
fn claim_skips_existing_temporary_files_and_leaves_them_alone() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let path = dir.path().join("pgdo.owner");
let theirs = dir.path().join("pgdo.owner.theirs");
fs::write(&theirs, "theirs")?;
let ours = dir.path().join("pgdo.owner.ours");
let record = record("boot", 1, (1, 2));
assert!(claim_via(&path, &record, [theirs.clone(), ours.clone()])?);
assert_eq!(read(&path)?.expect("owner file missing").record, record);
assert_eq!(fs::read_to_string(&theirs)?, "theirs");
assert!(!ours.exists());
Ok(())
}
#[test]
fn claim_gives_up_after_repeated_collisions() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let path = dir.path().join("pgdo.owner");
let taken = dir.path().join("pgdo.owner.taken");
fs::write(&taken, "taken")?;
let record = record("boot", 1, (1, 2));
let err = claim_via(&path, &record, std::iter::repeat(taken.clone())).unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::AlreadyExists);
assert!(!path.exists());
assert_eq!(fs::read_to_string(&taken)?, "taken");
Ok(())
}
#[test]
fn observe_sees_unchanged_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let path = dir.path().join("pgdo.owner");
fs::write(&path, "")?;
assert_eq!(
observe(&path, Duration::from_millis(100), &|| false)?,
Observed::Unchanged
);
Ok(())
}
#[test]
fn observe_sees_heartbeats_even_with_stale_times() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let path = dir.path().join("pgdo.owner");
fs::write(&path, "")?;
let base = SystemTime::now() - Duration::from_secs(3600);
fs::File::options()
.write(true)
.open(&path)?
.set_modified(base)?;
let beating = {
let path = path.clone();
std::thread::spawn(move || {
for i in 1..=10 {
std::thread::sleep(Duration::from_millis(20));
let file = fs::File::options().write(true).open(&path).unwrap();
file.set_modified(base + Duration::from_secs(i)).unwrap();
}
})
};
assert_eq!(
observe(&path, Duration::from_millis(500), &|| false)?,
Observed::Changed
);
beating.join().unwrap();
Ok(())
}
#[test]
fn observe_stops_promptly_when_interrupted() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let path = dir.path().join("pgdo.owner");
fs::write(&path, "")?;
let started = Instant::now();
let observed = observe(&path, Duration::from_secs(30), &|| {
started.elapsed() > Duration::from_millis(100)
})?;
assert_eq!(observed, Observed::Interrupted);
assert!(started.elapsed() < Duration::from_secs(3));
Ok(())
}
#[test]
fn observe_sees_replaced_and_removed_files() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let path = dir.path().join("pgdo.owner");
assert_eq!(
observe(&path, Duration::from_millis(100), &|| false)?,
Observed::Gone
);
fs::write(&path, "")?;
let replacing = {
let path = path.clone();
std::thread::spawn(move || {
std::thread::sleep(Duration::from_millis(50));
let temp = path.with_extension("new");
fs::write(&temp, "").unwrap();
fs::rename(&temp, &path).unwrap();
})
};
assert_eq!(
observe(&path, Duration::from_millis(500), &|| false)?,
Observed::Changed
);
replacing.join().unwrap();
let removing = {
let path = path.clone();
std::thread::spawn(move || {
std::thread::sleep(Duration::from_millis(50));
fs::remove_file(&path).unwrap();
})
};
assert_eq!(
observe(&path, Duration::from_millis(500), &|| false)?,
Observed::Gone
);
removing.join().unwrap();
Ok(())
}
#[test]
fn read_rejects_unintelligible_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let path = dir.path().join("pgdo.owner");
fs::write(&path, "garbage")?;
assert_eq!(read(&path).unwrap_err().kind(), io::ErrorKind::InvalidData);
Ok(())
}
#[test]
fn heartbeat_touches_file_until_dropped() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let path = dir.path().join("pgdo.owner");
fs::write(&path, "")?;
let old = SystemTime::now() - Duration::from_secs(3600);
fs::File::options()
.write(true)
.open(&path)?
.set_modified(old)?;
let heartbeat = Heartbeat::start(path.clone(), Duration::from_millis(20));
std::thread::sleep(Duration::from_millis(100));
assert!(fs::metadata(&path)?.modified()? > old);
drop(heartbeat);
fs::File::options()
.write(true)
.open(&path)?
.set_modified(old)?;
std::thread::sleep(Duration::from_millis(100));
assert_eq!(fs::metadata(&path)?.modified()?, old);
Ok(())
}
}