use std::{
fs::{self, File},
io::{self, Write},
path::{Path, PathBuf},
time::{Duration, Instant},
};
use fs2::FileExt;
use rho_protocol::ProtocolVersion;
use serde::{Deserialize, Serialize};
use super::{
paths::DaemonPaths,
platform::{self, DaemonPathError},
};
#[derive(Debug)]
pub(crate) struct DaemonLock {
file: File,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct DaemonRecord {
pub(crate) pid: u32,
pub(crate) version: String,
pub(crate) protocol: ProtocolVersion,
pub(crate) started_at: u64,
pub(crate) socket: PathBuf,
}
#[derive(Debug, thiserror::Error)]
pub(crate) enum LockError {
#[error("{}", already_running_message(.record.as_ref()))]
AlreadyRunning { record: Option<DaemonRecord> },
#[error("could not open rho daemon lock {path}: {source}")]
Io { path: PathBuf, source: io::Error },
#[error(transparent)]
StateDir(#[from] DaemonPathError),
}
fn already_running_message(record: Option<&DaemonRecord>) -> String {
match record {
Some(DaemonRecord {
pid,
version,
socket,
..
}) => format!(
"rho daemon is already running (pid {pid}, version {version}, socket {})",
socket.display()
),
None => "rho daemon is already running (it is still starting)".to_owned(),
}
}
pub(crate) fn acquire(paths: &DaemonPaths) -> Result<DaemonLock, LockError> {
paths.prepare_state_dir()?;
let file = open_lock_file(&paths.lock)?;
match FileExt::try_lock_exclusive(&file) {
Ok(()) => Ok(DaemonLock { file }),
Err(error) if is_contended(&error) => Err(LockError::AlreadyRunning {
record: read_record(paths),
}),
Err(source) => Err(LockError::Io {
path: paths.lock.clone(),
source,
}),
}
}
impl DaemonLock {
pub(super) fn adopt(file: File) -> io::Result<Self> {
FileExt::try_lock_exclusive(&file)?;
Ok(Self { file })
}
}
impl AsRef<File> for DaemonLock {
fn as_ref(&self) -> &File {
&self.file
}
}
fn is_contended(error: &io::Error) -> bool {
error.kind() == io::ErrorKind::WouldBlock
|| error.raw_os_error() == fs2::lock_contended_error().raw_os_error()
}
pub(crate) fn is_held(paths: &DaemonPaths) -> Result<bool, LockError> {
let file = match open_lock_file(&paths.lock) {
Ok(file) => file,
Err(LockError::Io { source, .. }) if source.kind() == io::ErrorKind::NotFound => {
return Ok(false)
}
Err(error) => return Err(error),
};
match FileExt::try_lock_shared(&file) {
Ok(()) => Ok(false),
Err(error) if is_contended(&error) => Ok(true),
Err(source) => Err(LockError::Io {
path: paths.lock.clone(),
source,
}),
}
}
pub(crate) async fn wait_until_released(
paths: &DaemonPaths,
timeout: Duration,
) -> Result<Option<Duration>, LockError> {
let started = Instant::now();
loop {
if !is_held(paths)? {
return Ok(Some(started.elapsed()));
}
if started.elapsed() >= timeout {
return Ok(None);
}
tokio::time::sleep(LOCK_POLL_INTERVAL).await;
}
}
const LOCK_POLL_INTERVAL: Duration = Duration::from_millis(10);
pub(crate) fn write_record(paths: &DaemonPaths, record: &DaemonRecord) -> io::Result<()> {
let mut file = tempfile::NamedTempFile::new_in(&paths.state_dir)?;
serde_json::to_writer(&mut file, record)?;
file.write_all(b"\n")?;
file.persist(&paths.info_file)
.map_err(|error| error.error)?;
Ok(())
}
pub(crate) fn read_record(paths: &DaemonPaths) -> Option<DaemonRecord> {
let contents = fs::read(&paths.info_file).ok()?;
serde_json::from_slice(&contents).ok()
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum LockHolder {
Nobody,
Unrecorded,
Daemon(DaemonRecord),
}
impl LockHolder {
pub(crate) fn record(self) -> Option<DaemonRecord> {
match self {
Self::Daemon(record) => Some(record),
Self::Nobody | Self::Unrecorded => None,
}
}
}
pub(crate) fn holder(paths: &DaemonPaths) -> LockHolder {
if !is_held(paths).unwrap_or(false) {
return LockHolder::Nobody;
}
read_record(paths).map_or(LockHolder::Unrecorded, LockHolder::Daemon)
}
pub(crate) fn terminate_recorded_daemon(paths: &DaemonPaths) -> anyhow::Result<Option<u32>> {
if !is_held(paths)? {
return Ok(None);
}
let record = read_record(paths)
.ok_or_else(|| anyhow::anyhow!("rho daemon is still starting; retry in a moment"))?;
platform::request_stop(paths, record.pid)?;
Ok(Some(record.pid))
}
fn open_lock_file(path: &Path) -> Result<File, LockError> {
platform::open_lock_file(path).map_err(|source| LockError::Io {
path: path.to_path_buf(),
source,
})
}
#[cfg(test)]
#[path = "lock_tests.rs"]
mod tests;