use std::{
ffi::OsString,
future::Future,
io,
net::TcpListener,
sync::{
atomic::{AtomicUsize, Ordering},
Arc,
},
time::Duration,
};
use tokio::sync::{watch, Notify};
use super::remotes::CALL_TIMEOUT;
use crate::daemon::Executable;
const LISTENER_FD_FLAG: &str = "--listener-fd";
const CHECK_INTERVAL: Duration = Duration::from_secs(1);
const DRAIN_TIMEOUT: Duration = CALL_TIMEOUT.saturating_add(Duration::from_secs(20));
pub(crate) struct Upgrade {
executable: Executable,
args: Vec<OsString>,
}
impl Upgrade {
pub(crate) fn new(
executable: Executable,
args: impl Iterator<Item = OsString>,
) -> Option<Self> {
cfg!(unix).then(|| Self {
executable,
args: without_listener_fd(args),
})
}
pub(super) async fn replaced(&self) -> String {
let executable = &self.executable;
let mut checks = tokio::time::interval(CHECK_INTERVAL);
checks.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
let mut probed = None;
loop {
checks.tick().await;
let Some(replacement) = executable.replacement() else {
probed = None;
continue;
};
if probed == Some(replacement.identity) {
continue;
}
match executable.probe().await {
Ok(version) => return version,
Err(error) if error.is_transient() => {
tracing::debug!(%error, "could not probe the server's replaced executable; trying again");
}
Err(error) => {
eprintln!(
"rho mcp serve: {} was replaced by a file that is not rho ({error}); not upgrading",
executable.path().display()
);
probed = Some(replacement.identity);
}
}
}
}
fn relaunch(self, listener: TcpListener, version: &str) -> anyhow::Error {
let running = env!("CARGO_PKG_VERSION");
let older = crate::update::version_is_newer(running, version);
if older {
eprintln!(
"rho mcp serve: {version} is older than {running} and may not take over the listening socket; it listens anew"
);
}
#[cfg(unix)]
{
let handed = (!older).then_some(&listener);
let error = unix::relaunch(handed, self.executable.path(), self.args);
anyhow::Error::new(error).context(format!(
"could not re-execute {} to upgrade",
self.executable.path().display()
))
}
#[cfg(not(unix))]
{
let _ = (listener, self.args);
anyhow::anyhow!("the server upgrades in place only on Unix")
}
}
}
pub(crate) fn inherit_listener(fd: i32) -> io::Result<TcpListener> {
#[cfg(unix)]
{
let listener = TcpListener::from(crate::daemon::adopt(fd)?);
listener.local_addr()?;
listener.set_nonblocking(true)?;
Ok(listener)
}
#[cfg(not(unix))]
Err(io::Error::other(format!(
"a server hands on its listening socket only on Unix, not {LISTENER_FD_FLAG} {fd}"
)))
}
pub(super) struct Drain {
calls: InFlight,
begin: watch::Sender<bool>,
}
impl Drain {
pub(super) fn new() -> Self {
Self {
calls: InFlight::default(),
begin: watch::Sender::new(false),
}
}
pub(super) fn calls(&self) -> InFlight {
self.calls.clone()
}
pub(super) fn began(&self) -> impl Future<Output = ()> + Send + 'static {
let mut begin = self.begin.subscribe();
async move { drop(begin.wait_for(|began| *began).await) }
}
pub(super) async fn finish(
self,
upgrade: Upgrade,
version: &str,
listener: tokio::net::TcpListener,
) -> anyhow::Error {
self.begin.send_replace(true);
eprintln!(
"rho mcp serve: upgrading to {version} in place once the calls under way end ({} now)",
self.calls.count()
);
if !self.calls.drained(DRAIN_TIMEOUT).await {
eprintln!(
"rho mcp serve: {} calls still under way after DRAIN_TIMEOUT ({DRAIN_TIMEOUT:?}); cutting them short to upgrade",
self.calls.count()
);
}
match listener.into_std() {
Ok(listener) => upgrade.relaunch(listener, version),
Err(error) => {
anyhow::Error::new(error).context("could not hand on the listening socket")
}
}
}
}
#[derive(Clone, Default)]
pub(super) struct InFlight {
count: Arc<AtomicUsize>,
ended: Arc<Notify>,
}
pub(super) struct Call(InFlight);
impl InFlight {
pub(super) fn enter(&self) -> Call {
self.count.fetch_add(1, Ordering::SeqCst);
Call(self.clone())
}
fn count(&self) -> usize {
self.count.load(Ordering::SeqCst)
}
async fn drained(&self, timeout: Duration) -> bool {
tokio::time::timeout(timeout, async {
loop {
let ended = self.ended.notified();
if self.count() == 0 {
return;
}
ended.await;
}
})
.await
.is_ok()
}
}
impl Drop for Call {
fn drop(&mut self) {
self.0.count.fetch_sub(1, Ordering::SeqCst);
self.0.ended.notify_waiters();
}
}
fn without_listener_fd(args: impl Iterator<Item = OsString>) -> Vec<OsString> {
let mut kept = Vec::new();
let mut args = args.peekable();
while let Some(arg) = args.next() {
if arg == LISTENER_FD_FLAG {
args.next();
} else {
kept.push(arg);
}
}
kept
}
#[cfg(unix)]
mod unix {
use std::{
ffi::OsString,
io,
net::TcpListener,
os::{
fd::{AsFd, AsRawFd},
unix::process::CommandExt,
},
path::Path,
process::Command,
};
use super::LISTENER_FD_FLAG;
use crate::daemon::{reap_exited_children, set_close_on_exec};
pub(super) fn relaunch(
handed: Option<&TcpListener>,
executable: &Path,
args: Vec<OsString>,
) -> io::Error {
let socket = handed.map(AsFd::as_fd);
if let Some(Err(error)) =
socket.map(|socket| set_close_on_exec(socket, false))
{
return error;
}
reap_exited_children();
let mut command = Command::new(executable);
command.args(args);
if let Some(socket) = socket {
command
.arg(LISTENER_FD_FLAG)
.arg(socket.as_raw_fd().to_string());
}
let error = command.exec();
if let Some(socket) = socket {
let _ = set_close_on_exec(socket, true);
}
error
}
}
#[cfg(test)]
#[path = "upgrade_tests.rs"]
mod tests;