use std::io::ErrorKind;
#[cfg(unix)]
use std::os::unix::fs::OpenOptionsExt;
use std::path::PathBuf;
use shep_core::paths::ShepPaths;
use super::BootError;
#[must_use]
pub fn pidfile(paths: &ShepPaths) -> PathBuf {
paths.pids.join("shepd.pid")
}
#[cfg(test)]
#[cfg_attr(windows, allow(dead_code))]
pub(super) fn write_pidfile(paths: &ShepPaths, pid: u32) -> Result<(), BootError> {
use std::io::Write;
use tempfile::NamedTempFile;
let path = pidfile(paths);
let mut tmp = NamedTempFile::new_in(&paths.pids).map_err(|source| BootError::Io {
path: paths.pids.clone(),
source,
})?;
tmp.write_all(pid.to_string().as_bytes())
.map_err(|source| BootError::Io {
path: path.clone(),
source,
})?;
shep_core::atomic_file::publish(tmp, &path).map_err(|source| BootError::Io { path, source })
}
pub(crate) fn read_pidfile(paths: &ShepPaths) -> Result<Option<u32>, BootError> {
let path = pidfile(paths);
match std::fs::read_to_string(&path) {
Ok(contents) => Ok(contents.trim().parse::<u32>().ok()),
Err(err) if err.kind() == ErrorKind::NotFound => Ok(None),
Err(source) => Err(BootError::Io { path, source }),
}
}
#[derive(Debug)]
pub(super) struct PidfileLock {
#[cfg(unix)]
flock: UnixLock,
#[cfg(windows)]
_handle: std::fs::File,
}
#[cfg(unix)]
#[derive(Debug)]
enum UnixLock {
Taken(nix::fcntl::Flock<std::fs::File>),
Adopted(std::fs::File),
}
#[cfg(unix)]
impl UnixLock {
fn file(&mut self) -> &mut std::fs::File {
match self {
Self::Taken(flock) => flock,
Self::Adopted(file) => file,
}
}
fn as_raw_fd(&self) -> std::os::fd::RawFd {
use std::os::fd::AsRawFd as _;
match self {
Self::Taken(flock) => flock.as_raw_fd(),
Self::Adopted(file) => file.as_raw_fd(),
}
}
}
#[cfg(windows)]
fn pidfile_lock_path(paths: &ShepPaths) -> PathBuf {
paths.pids.join("shepd.pid.lock")
}
impl PidfileLock {
#[cfg(unix)]
pub(super) fn acquire(paths: &ShepPaths) -> Result<Self, BootError> {
let path = pidfile(paths);
let file = std::fs::OpenOptions::new()
.create(true)
.write(true)
.truncate(false) .mode(0o600)
.open(&path)
.map_err(|source| BootError::Io {
path: path.clone(),
source,
})?;
match nix::fcntl::Flock::lock(file, nix::fcntl::FlockArg::LockExclusiveNonblock) {
Ok(flock) => Ok(Self {
flock: UnixLock::Taken(flock),
}),
Err((_file, nix::errno::Errno::EWOULDBLOCK)) => Err(BootError::AlreadyRunning {
pid: read_pidfile(paths)?,
}),
Err((_file, errno)) => Err(BootError::Io {
path,
source: errno.into(),
}),
}
}
#[cfg(windows)]
pub(super) fn acquire(paths: &ShepPaths) -> Result<Self, BootError> {
use std::os::windows::fs::OpenOptionsExt as _;
const ERROR_SHARING_VIOLATION: i32 = 32;
let path = pidfile_lock_path(paths);
match std::fs::OpenOptions::new()
.create(true)
.write(true)
.truncate(false)
.share_mode(0)
.open(&path)
{
Ok(handle) => Ok(Self { _handle: handle }),
Err(err) if err.raw_os_error() == Some(ERROR_SHARING_VIOLATION) => {
Err(BootError::AlreadyRunning {
pid: read_pidfile(paths)?,
})
}
Err(source) => Err(BootError::Io { path, source }),
}
}
#[cfg(windows)]
pub(super) fn record(&mut self, paths: &ShepPaths, pid: u32) -> Result<(), BootError> {
use std::io::Write as _;
let path = pidfile(paths);
let mut file = std::fs::OpenOptions::new()
.create(true)
.write(true)
.truncate(true)
.open(&path)
.map_err(|source| BootError::Io {
path: path.clone(),
source,
})?;
file.write_all(pid.to_string().as_bytes())
.map_err(|source| BootError::Io {
path: path.clone(),
source,
})?;
file.sync_all()
.map_err(|source| BootError::Io { path, source })
}
#[cfg(unix)]
pub(super) fn from_locked(file: std::fs::File) -> Self {
Self {
flock: UnixLock::Adopted(file),
}
}
#[cfg(unix)]
pub(super) fn as_raw_fd(&self) -> std::os::fd::RawFd {
self.flock.as_raw_fd()
}
#[cfg(unix)]
pub(super) fn record(&mut self, paths: &ShepPaths, pid: u32) -> Result<(), BootError> {
use std::io::{Seek, SeekFrom, Write};
let path = pidfile(paths);
let file = self.flock.file();
file.set_len(0).map_err(|source| BootError::Io {
path: path.clone(),
source,
})?;
file.seek(SeekFrom::Start(0))
.map_err(|source| BootError::Io {
path: path.clone(),
source,
})?;
file.write_all(pid.to_string().as_bytes())
.map_err(|source| BootError::Io {
path: path.clone(),
source,
})?;
file.sync_all()
.map_err(|source| BootError::Io { path, source })
}
}
pub fn daemon_liveness(paths: &ShepPaths) -> Result<Shepherd, BootError> {
match PidfileLock::acquire(paths) {
Ok(lock) => {
drop(lock);
Ok(Shepherd::Absent)
}
Err(BootError::AlreadyRunning { pid: Some(pid) }) => Ok(Shepherd::Running(pid)),
Err(BootError::AlreadyRunning { pid: None }) => Ok(Shepherd::Booting),
Err(BootError::Io {
ref path,
ref source,
}) if source.kind() == ErrorKind::NotFound && path.starts_with(&paths.pids) => {
Ok(Shepherd::Absent)
}
Err(other) => Err(other),
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Shepherd {
Absent,
Running(u32),
Booting,
}
#[cfg(all(test, windows))]
mod windows_tests {
use super::*;
use crate::boot::{init_dirs, paths_in};
#[test]
fn a_second_pidfile_lock_is_refused_and_can_still_read_the_winners_pid() {
let dir = tempfile::tempdir().unwrap();
let paths = paths_in(dir.path());
init_dirs(&paths).unwrap();
let mut first = PidfileLock::acquire(&paths).expect("the first daemon must win");
first.record(&paths, 4242).unwrap();
let refusal = PidfileLock::acquire(&paths).expect_err("a second daemon must be refused");
let BootError::AlreadyRunning { pid } = refusal else {
panic!("a contended lock must report AlreadyRunning, got {refusal:?}");
};
assert_eq!(
pid,
Some(4242),
"the loser must be able to read the winner's pid off the pidfile"
);
}
#[test]
fn dropping_the_lock_releases_it_for_the_next_daemon() {
let dir = tempfile::tempdir().unwrap();
let paths = paths_in(dir.path());
init_dirs(&paths).unwrap();
let first = PidfileLock::acquire(&paths).unwrap();
drop(first);
PidfileLock::acquire(&paths)
.expect("a released lock must be re-acquirable, or a crash would wedge $SHEP_HOME");
}
}
#[cfg(all(test, unix))]
mod tests {
use super::*;
use crate::boot::init_dirs;
use crate::testing::test_paths;
use std::time::Duration;
#[test]
fn the_adopted_pidfile_arm_does_not_release_the_lock() {
let dir = tempfile::tempdir().unwrap();
let paths = test_paths(&dir);
init_dirs(&paths).unwrap();
let mut held = PidfileLock::acquire(&paths).expect("the predecessor must win");
let fd = std::os::fd::AsRawFd::as_raw_fd(held.flock.file());
core::mem::forget(held);
let inherited = crate::sys::adopt_handover_fd(fd)
.expect("the successor adopts the number the blob named");
let adopted = PidfileLock::from_locked(inherited);
let refusal = PidfileLock::acquire(&paths)
.expect_err("the lock must never be free while a successor holds it");
assert!(
matches!(refusal, BootError::AlreadyRunning { .. }),
"a contended lock must report AlreadyRunning, got {refusal:?}"
);
drop(adopted);
let deadline = std::time::Instant::now() + Duration::from_secs(5);
let claimed = loop {
match PidfileLock::acquire(&paths) {
Ok(claimed) => break claimed,
Err(error) => assert!(
std::time::Instant::now() < deadline,
"a successor that exits must leave the home claimable: {error:?}"
),
}
std::thread::sleep(Duration::from_millis(10));
};
drop(claimed);
}
#[test]
fn pidfile_round_trips_and_reports_absence() {
let dir = tempfile::tempdir().unwrap();
let paths = test_paths(&dir);
init_dirs(&paths).unwrap();
assert_eq!(read_pidfile(&paths).unwrap(), None);
write_pidfile(&paths, 4242).unwrap();
assert_eq!(read_pidfile(&paths).unwrap(), Some(4242));
assert_eq!(pidfile(&paths), paths.pids.join("shepd.pid"));
}
#[test]
fn liveness_reports_none_when_no_daemon_holds_the_lock() {
let dir = tempfile::tempdir().unwrap();
let paths = test_paths(&dir);
init_dirs(&paths).unwrap();
assert_eq!(daemon_liveness(&paths).unwrap(), Shepherd::Absent);
}
#[test]
fn liveness_reports_none_for_a_stale_pidfile_nobody_holds() {
let dir = tempfile::tempdir().unwrap();
let paths = test_paths(&dir);
init_dirs(&paths).unwrap();
std::fs::write(pidfile(&paths), "999999").unwrap();
assert_eq!(daemon_liveness(&paths).unwrap(), Shepherd::Absent);
}
#[test]
fn liveness_reports_the_pid_a_lock_holder_recorded() {
let dir = tempfile::tempdir().unwrap();
let paths = test_paths(&dir);
init_dirs(&paths).unwrap();
let mut held = PidfileLock::acquire(&paths).unwrap();
held.record(&paths, 4242).unwrap();
assert_eq!(daemon_liveness(&paths).unwrap(), Shepherd::Running(4242));
drop(held);
assert_eq!(
daemon_liveness(&paths).unwrap(),
Shepherd::Absent,
"a released lock is not a live daemon, whatever the file still says"
);
}
#[test]
fn liveness_reports_booting_for_a_holder_that_has_not_recorded_a_pid_yet() {
let dir = tempfile::tempdir().unwrap();
let paths = test_paths(&dir);
init_dirs(&paths).unwrap();
let held = PidfileLock::acquire(&paths).unwrap();
assert_eq!(daemon_liveness(&paths).unwrap(), Shepherd::Booting);
drop(held);
assert_eq!(daemon_liveness(&paths).unwrap(), Shepherd::Absent);
}
}