mod process;
mod start;
mod stop;
#[cfg(test)]
mod tests;
use std::io;
use std::path::{Path, PathBuf};
use std::time::Duration;
pub use process::{PinnedProcess, Signal};
pub use start::{RestartOutcome, StartOutcome, restart, restart_with, start};
pub use stop::{KernelDelivery, SignalDelivery, StopOutcome, stop, stop_with};
pub(crate) const PROBE_TIMEOUT: Duration = Duration::from_millis(500);
pub(crate) const POLL_INTERVAL: Duration = Duration::from_millis(20);
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum StoppedSignal {
SocketRefuses,
LockFree(PathBuf),
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct DaemonDescriptor {
pub binary: String,
pub install_dir: PathBuf,
pub socket: PathBuf,
pub spawn_args: Vec<String>,
pub stopped_signal: StoppedSignal,
pub stop_grace: Duration,
pub kill_wait: Duration,
pub ready_timeout: Duration,
}
impl DaemonDescriptor {
pub const DEFAULT_STOP_GRACE: Duration = Duration::from_secs(10);
pub const DEFAULT_KILL_WAIT: Duration = Duration::from_secs(5);
pub const DEFAULT_READY_TIMEOUT: Duration = Duration::from_secs(30);
pub fn new(
binary: impl Into<String>,
socket: impl Into<PathBuf>,
stopped_signal: StoppedSignal,
) -> Result<Self, LifecycleError> {
let install_dir =
crate::bin_resolve::canonical_bin_dir().ok_or(LifecycleError::NoInstallDir)?;
Self::with_install_dir(binary, install_dir, socket, stopped_signal)
}
pub fn with_install_dir(
binary: impl Into<String>,
install_dir: impl Into<PathBuf>,
socket: impl Into<PathBuf>,
stopped_signal: StoppedSignal,
) -> Result<Self, LifecycleError> {
let desc = Self {
binary: binary.into(),
install_dir: install_dir.into(),
socket: socket.into(),
spawn_args: Vec::new(),
stopped_signal,
stop_grace: Self::DEFAULT_STOP_GRACE,
kill_wait: Self::DEFAULT_KILL_WAIT,
ready_timeout: Self::DEFAULT_READY_TIMEOUT,
};
desc.validate()?;
Ok(desc)
}
pub fn program(&self) -> PathBuf {
self.install_dir.join(&self.binary)
}
pub(crate) fn validate(&self) -> Result<(), LifecycleError> {
let bad = |reason: &str| {
Err(LifecycleError::InvalidDescriptor {
reason: reason.to_string(),
})
};
if self.binary.is_empty() || self.binary == "." || self.binary == ".." {
return bad("binary name is empty or a dot entry");
}
if self.binary.contains('/') {
return bad("binary must be a file name, not a path");
}
if !self.install_dir.is_absolute() {
return bad("install_dir must be absolute");
}
if self.socket.as_os_str().is_empty() {
return bad("socket path is empty");
}
Ok(())
}
}
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum LifecycleError {
#[error("invalid daemon descriptor: {reason}")]
InvalidDescriptor {
reason: String,
},
#[error("no install directory: neither CARGO_HOME nor a home directory is set")]
NoInstallDir,
#[error("cannot tell whether {} is served (connect timed out or failed)", socket.display())]
ProbeInconclusive {
socket: PathBuf,
},
#[error("{} is served, but SO_PEERCRED reported no peer pid", socket.display())]
NoPeerPid {
socket: PathBuf,
},
#[error(
"{} is not served but {} is locked; the holder cannot be identified",
socket.display(),
lock.display()
)]
Unidentified {
socket: PathBuf,
lock: PathBuf,
},
#[error("pid {pid} serves the socket but runs `{found}`, not `{expected}`; not signalled")]
IdentityMismatch {
pid: u32,
expected: String,
found: String,
},
#[error("cannot read the executable of pid {pid}: {source}")]
IdentityUnreadable {
pid: u32,
source: io::Error,
},
#[error("sending {signal:?} to pid {pid} failed: {source}")]
Signal {
pid: u32,
signal: Signal,
source: io::Error,
},
#[error("pid {pid} survived SIGKILL; the daemon is not stopped")]
Survivor {
pid: u32,
},
#[error("pid {pid} exited, but {signal} still does not hold")]
StoppedSignalNotReached {
pid: u32,
signal: String,
},
#[error("daemon binary {} is not installed", path.display())]
BinaryMissing {
path: PathBuf,
},
#[error("{} is already served{}", socket.display(), pid.map(|p| format!(" by pid {p}")).unwrap_or_default())]
AlreadyRunning {
socket: PathBuf,
pid: Option<u32>,
},
#[error("could not spawn {}: {message}", program.display())]
Spawn {
program: PathBuf,
message: String,
},
#[error("pid {pid} exited before serving the socket")]
ChildExited {
pid: u32,
},
#[error("pid {pid} did not serve the socket within {timeout:?}; {}", reap_note(*killed))]
NotReady {
pid: u32,
timeout: Duration,
killed: bool,
},
#[error("could not pin spawned pid {pid} with a pidfd ({source}); {}", reap_note(*killed))]
ChildUnpinned {
pid: u32,
killed: bool,
source: io::Error,
},
#[error("{context}: {source}")]
Io {
context: String,
source: io::Error,
},
}
fn reap_note(killed: bool) -> &'static str {
if killed {
"it was killed and reaped"
} else {
"it was sent SIGKILL but not reaped within the kill wait"
}
}
pub(crate) fn lock_is_free(lock: &Path) -> Result<bool, LifecycleError> {
let file = match std::fs::File::open(lock) {
Ok(f) => f,
Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(true),
Err(source) => {
return Err(LifecycleError::Io {
context: format!("open lock {}", lock.display()),
source,
});
}
};
match file.try_lock() {
Ok(()) => Ok(true),
Err(std::fs::TryLockError::WouldBlock) => Ok(false),
Err(std::fs::TryLockError::Error(source)) => Err(LifecycleError::Io {
context: format!("flock {}", lock.display()),
source,
}),
}
}