use std::{
future::Future,
sync::{Mutex, MutexGuard, PoisonError},
time::Duration,
};
use rho_protocol::ClientInfo;
use tokio::sync::Notify;
use super::{machine_update::Follow, DaemonHost};
use crate::daemon::{Executable, FileIdentity, ProbeError};
const UPGRADE_CHECK_INTERVAL: Duration = Duration::from_secs(1);
#[derive(Default)]
pub(super) struct Upgrades {
pending: Mutex<Option<String>>,
newer_client: Mutex<Option<String>>,
heard_newer: Notify,
}
#[derive(Default)]
pub(super) struct Watch {
probed: Option<FileIdentity>,
warned: Option<String>,
}
#[derive(Debug, PartialEq, Eq)]
pub(super) enum Check {
Wait,
Upgrade,
}
impl Upgrades {
pub(super) fn heard(&self, client: &ClientInfo) {
if !crate::update::version_is_newer(&client.version, env!("CARGO_PKG_VERSION")) {
return;
}
let mut newest = lock(&self.newer_client);
if newest
.as_deref()
.is_none_or(|newest| crate::update::version_is_newer(&client.version, newest))
{
*newest = Some(client.version.clone());
}
drop(newest);
self.heard_newer.notify_one();
}
pub(super) fn pending(&self) -> Option<String> {
lock(&self.pending).clone()
}
pub(super) async fn next_check(&self, interval: &mut tokio::time::Interval) {
tokio::select! {
_ = interval.tick() => {}
() = self.heard_newer.notified() => {}
}
}
pub(super) async fn check(&self, executable: &Executable, watch: &mut Watch) -> Check {
let Some(replacement) = executable.replacement() else {
*lock(&self.pending) = None;
watch.probed = None;
let newer_client = lock(&self.newer_client).clone();
if newer_client.is_some() && watch.warned != newer_client {
tracing::warn!(
client = newer_client.as_deref(),
executable = %executable.path().display(),
"a newer rho client connected, but the daemon's executable was not \
replaced; restart the daemon from the newer rho to upgrade it"
);
watch.warned = newer_client;
}
return Check::Wait;
};
if watch.probed != Some(replacement.identity) {
let probed = executable.probe().await;
match &probed {
Ok(version) => tracing::info!(
%version,
executable = %executable.path().display(),
"the daemon's executable was replaced; upgrading once nothing would be cut short"
),
Err(error) if error.is_transient() => tracing::debug!(
%error,
executable = %executable.path().display(),
"could not probe the daemon's replaced executable; trying again"
),
Err(error) => tracing::warn!(
%error,
executable = %executable.path().display(),
"the daemon's executable was replaced by one that is not rho; not upgrading"
),
}
if !probed.as_ref().is_err_and(ProbeError::is_transient) {
watch.probed = Some(replacement.identity);
}
*lock(&self.pending) = probed.ok();
}
match *lock(&self.pending) {
Some(_) => Check::Upgrade,
None => Check::Wait,
}
}
}
impl DaemonHost {
pub(in crate::app) async fn upgrade_when_replaced(&self, executable: &Executable) {
let mut checks = tokio::time::interval(UPGRADE_CHECK_INTERVAL);
checks.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
let mut watch = Watch::default();
loop {
tokio::select! {
() = self.upgrades.next_check(&mut checks) => {}
() = self.shutdown.requested() => return,
}
let mut watching = Watching {
host: self,
executable,
watch: &mut watch,
};
match at_check(&mut watching).await {
None => {}
Some((Begin::Restart, follow)) => {
tracing::info!(?follow, "upgrading in place");
self.begin_restart();
return;
}
Some((Begin::Replace, follow)) => {
tracing::info!(
?follow,
"stopping for the rho an update installed at another path"
);
self.begin_replace();
return;
}
}
}
}
fn claim_idle(&self) -> bool {
let Some(idle) = self.jobs.idle() else {
return false;
};
super::work_outside_jobs(&self.logins, &self.sessions) == 0
&& self.jobs.close_if_still(idle)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Begin {
Restart,
Replace,
}
trait Watched {
fn follow(&self) -> Follow;
fn replaced(&mut self) -> impl Future<Output = bool> + Send;
fn commit(&mut self, follow: Follow, once_idle: bool) -> bool;
}
async fn at_check(watched: &mut impl Watched) -> Option<(Begin, Follow)> {
let follow = watched.follow();
let (begin, once_idle) = match follow {
Follow::Held => return None,
Follow::Watch => (Begin::Restart, true),
Follow::RestartNow => (Begin::Restart, false),
Follow::Replace { once_idle } => (Begin::Replace, once_idle),
};
if begin == Begin::Restart && !watched.replaced().await {
return None;
}
watched.commit(follow, once_idle).then_some((begin, follow))
}
struct Watching<'a> {
host: &'a DaemonHost,
executable: &'a Executable,
watch: &'a mut Watch,
}
impl Watched for Watching<'_> {
fn follow(&self) -> Follow {
self.host.machine.updates().follow()
}
async fn replaced(&mut self) -> bool {
self.host.upgrades.check(self.executable, self.watch).await == Check::Upgrade
}
fn commit(&mut self, follow: Follow, once_idle: bool) -> bool {
let host = self.host;
host.machine
.updates()
.commit(follow, || !once_idle || host.claim_idle())
}
}
fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
mutex.lock().unwrap_or_else(PoisonError::into_inner)
}
#[cfg(test)]
#[path = "upgrade_tests.rs"]
mod tests;