use std::{
ffi::OsString,
fs, io,
sync::Arc,
time::{SystemTime, UNIX_EPOCH},
};
use rho_protocol::{BuildId, DaemonInfo, FrameError, Service, PROTOCOL_VERSION};
use rho_sdk::CancellationToken;
use tokio::task::JoinSet;
use super::{
executable::Executable,
lock::{self, DaemonLock, DaemonRecord},
paths::DaemonPaths,
platform::{self, Listener},
shutdown::{Ending, Shutdown},
};
pub(crate) struct BoundDaemon {
listener: Listener,
paths: DaemonPaths,
started_at: u64,
lock: DaemonLock,
}
#[must_use = "dropping Served releases the daemon lock"]
pub(crate) enum Served {
Stopped {
result: io::Result<()>,
lock: DaemonLock,
},
Restarting(Box<Restarting>),
}
pub(crate) struct Restarting {
pub(super) lock: DaemonLock,
pub(super) listener: Listener,
pub(super) paths: DaemonPaths,
}
impl Served {
pub(crate) fn release(self) -> io::Result<()> {
match self {
Self::Stopped { result, lock } => {
drop(lock);
result
}
Self::Restarting(restarting) => {
restarting.release();
Ok(())
}
}
}
}
impl Restarting {
pub(super) fn release(self) {
let Self {
lock,
listener,
paths,
} = self;
drop(listener);
remove_daemon_files(&paths);
drop(lock);
}
pub(crate) fn relaunch(
self,
executable: &Executable,
args: impl FnOnce(Option<String>) -> Vec<OsString>,
) -> io::Result<()> {
platform::relaunch(self, executable.path(), args)
}
}
pub(crate) fn take_handoff(
paths: &DaemonPaths,
token: &str,
) -> io::Result<(DaemonLock, Option<Inherited>)> {
let (lock, listener) = platform::take_handoff(paths, token)?;
Ok((DaemonLock::adopt(lock)?, listener.map(Inherited)))
}
pub(crate) struct Inherited(Listener);
pub(crate) fn bind(paths: &DaemonPaths, lock: DaemonLock) -> io::Result<BoundDaemon> {
match fs::remove_file(&paths.info_file) {
Ok(()) => {
tracing::info!(path = %paths.info_file.display(), "removed stale daemon file");
}
Err(error) if error.kind() == io::ErrorKind::NotFound => {}
Err(error) => return Err(error),
}
let listener = Listener::bind(paths)?;
publish(paths, listener, lock, "rho daemon listening")
}
pub(crate) fn rebind(
paths: &DaemonPaths,
lock: DaemonLock,
Inherited(listener): Inherited,
) -> io::Result<BoundDaemon> {
publish(paths, listener, lock, "rho daemon re-executed in place")
}
fn publish(
paths: &DaemonPaths,
listener: Listener,
lock: DaemonLock,
message: &'static str,
) -> io::Result<BoundDaemon> {
let started_at = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |since_epoch| since_epoch.as_secs());
lock::write_record(
paths,
&DaemonRecord {
pid: std::process::id(),
version: env!("CARGO_PKG_VERSION").to_owned(),
protocol: PROTOCOL_VERSION,
started_at,
socket: paths.socket.clone(),
},
)?;
tracing::info!(
pid = std::process::id(),
version = env!("CARGO_PKG_VERSION"),
socket = %paths.socket.display(),
"{message}"
);
Ok(BoundDaemon {
listener,
paths: paths.clone(),
started_at,
lock,
})
}
impl BoundDaemon {
pub(crate) fn started_at(&self) -> u64 {
self.started_at
}
pub(crate) async fn serve<Svc: Service + 'static>(
self,
service: Arc<Svc>,
shutdown: Shutdown,
) -> Served {
let Self {
mut listener,
paths,
started_at: _,
lock,
} = self;
let info = Arc::new(DaemonInfo {
version: env!("CARGO_PKG_VERSION").to_owned(),
pid: std::process::id(),
build: reported_build(),
});
let mut connections = JoinSet::new();
let closing = CancellationToken::new();
let result = loop {
tokio::select! {
biased;
() = shutdown.requested() => break Ok(()),
Some(_) = connections.join_next(), if !connections.is_empty() => {}
accepted = listener.accept() => match accepted {
Ok(stream) => {
let service = Arc::clone(&service);
let info = Arc::clone(&info);
let closing = closing.clone();
connections.spawn(async move {
let served = rho_protocol::serve_connection(
stream,
&info,
service,
closing.cancelled(),
)
.await;
match served {
Ok(()) => {}
Err(error @ FrameError::Stalled { .. }) => {
tracing::warn!(%error, "dropped a client that stopped reading");
}
Err(error) => {
tracing::debug!(%error, "connection closed with an error");
}
}
});
}
Err(error) if is_transient_accept_error(&error) => {
tracing::debug!(%error, "accept failed");
}
Err(error) => {
tracing::error!(%error, "accept failed; shutting down");
shutdown.request(Ending::Stop, |_| {});
break Err(error);
}
},
}
};
let listener = match (&result, shutdown.ending()) {
(Ok(()), Ending::Restart) => {
tracing::info!("rho daemon restarting");
listener.hold_for_restart();
Some(listener)
}
(_, Ending::Stop | Ending::Restart) => {
tracing::info!("rho daemon shutting down");
drop(listener);
None
}
};
closing.cancel();
while connections.join_next().await.is_some() {}
tracing::info!("rho daemon stopped serving");
match listener {
Some(listener) => Served::Restarting(Box::new(Restarting {
lock,
listener,
paths,
})),
None => {
remove_daemon_files(&paths);
Served::Stopped { result, lock }
}
}
}
}
fn reported_build() -> BuildId {
#[cfg(debug_assertions)]
if let Ok(build) = std::env::var("RHO_TUI_TEST_BUILD_ID") {
return BuildId::new(build);
}
BuildId::of_this_crate()
}
fn remove_daemon_files(paths: &DaemonPaths) {
let removed = [
(&paths.socket, platform::remove_endpoint(paths)),
(&paths.info_file, fs::remove_file(&paths.info_file)),
];
for (path, removed) in removed {
if let Err(error) = removed {
if error.kind() != io::ErrorKind::NotFound {
tracing::warn!(path = %path.display(), %error, "could not remove daemon file");
}
}
}
}
fn is_transient_accept_error(error: &io::Error) -> bool {
matches!(
error.kind(),
io::ErrorKind::ConnectionAborted
| io::ErrorKind::ConnectionReset
| io::ErrorKind::Interrupted
| io::ErrorKind::WouldBlock
)
}
#[cfg(test)]
#[path = "server_tests.rs"]
mod tests;