use std::{
future::Future,
sync::{Arc, Mutex, MutexGuard, PoisonError},
time::Duration,
};
use rho_protocol::{
Caller, ClientEnvironment, ClientInfo, ConnectionId, DaemonUpdateParams, DaemonUpdateResponse,
DaemonUpdateResult, DaemonUpdateResultParams, ErrorCode, HostPath, HostStreamId,
HostStreamWriter, RpcError, TryWriteError, UpdateMethod, UpdateOutcome, UpdateRestart,
UpdateRestarting, HOST_STREAM_FAILURE_MAX_BYTES,
};
use tokio::sync::watch;
use crate::{
cli_runtime::StderrTail,
daemon::Shutdown,
update::{update_unattended, InstallMethod, Lands, Report, Unattended},
};
const UNASKED_RESULT_GRACE: Duration = Duration::from_secs(60);
const OUTPUT_TAIL_BYTES: usize = HOST_STREAM_FAILURE_MAX_BYTES;
const WHY_MAX_BYTES: usize = HOST_STREAM_FAILURE_MAX_BYTES;
const STOPPED: &str = "the update stopped unexpectedly";
pub(super) struct Daemon {
pub(super) in_progress: Arc<dyn Fn() -> u64 + Send + Sync>,
pub(super) replaced: Arc<dyn Fn() -> Option<String> + Send + Sync>,
pub(super) shutdown: Shutdown,
}
#[cfg(test)]
impl Daemon {
pub(super) fn idle() -> Self {
Self {
in_progress: Arc::new(|| 0_u64),
replaced: Arc::new(|| None),
shutdown: Shutdown::default(),
}
}
}
pub(super) trait Install: Send + Sync + 'static {
fn install<'a>(
&'a self,
environment: ClientEnvironment,
replaced: Option<String>,
progress: &'a mut Progress,
) -> impl Future<Output = anyhow::Result<Unattended>> + Send + 'a;
}
pub(super) struct RhoInstall;
impl Install for RhoInstall {
async fn install(
&self,
environment: ClientEnvironment,
replaced: Option<String>,
progress: &mut Progress,
) -> anyhow::Result<Unattended> {
update_unattended(env!("CARGO_PKG_VERSION"), replaced, &environment, progress).await
}
}
pub(super) struct Updates<I = RhoInstall> {
install: Arc<I>,
shared: Arc<Shared>,
}
struct Shared {
from: String,
daemon: Daemon,
state: Mutex<State>,
}
#[derive(Default)]
struct State {
running: Option<Running>,
moving: Follow,
committed: bool,
}
impl State {
fn follow(&self) -> Follow {
match self.running {
Some(_) => Follow::Held,
None => self.moving,
}
}
}
struct Running {
connection: ConnectionId,
progress: HostStreamId,
client: ClientInfo,
restart: UpdateRestart,
over: watch::Receiver<Option<Over>>,
}
#[derive(Clone, Debug)]
enum Over {
Done(Unattended),
Failed {
why: String,
message: String,
},
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(super) enum Follow {
Held,
#[default]
Watch,
RestartNow,
Replace { once_idle: bool },
}
impl<I: Install> Updates<I> {
pub(super) fn new(install: I, daemon: Daemon) -> Self {
Self {
install: Arc::new(install),
shared: Arc::new(Shared {
from: env!("CARGO_PKG_VERSION").to_owned(),
daemon,
state: Mutex::default(),
}),
}
}
pub(super) fn start(
&self,
caller: Caller,
params: DaemonUpdateParams,
environment: ClientEnvironment,
) -> Result<DaemonUpdateResponse, RpcError> {
if self.shared.daemon.shutdown.is_requested() {
return Err(stopping("updates nothing"));
}
let mut state = lock(&self.shared.state);
if state.committed {
return Err(RpcError::new(
ErrorCode::HostCallFailed,
"the daemon is moving onto a new rho, so it starts no update; ask again once it runs",
));
}
if let Some(running) = &state.running {
let under_way = match *running.over.borrow() {
Some(_) => "an update is over and waits for its result",
None => "an update is already running",
};
return Err(RpcError::new(
ErrorCode::HostCallFailed,
format!(
"{under_way}, asked for by {} {}",
running.client.name, running.client.version
),
));
}
let writer = caller.open_stream()?;
let progress = writer.id().clone();
let (finished, over) = watch::channel(None);
state.running = Some(Running {
connection: caller.connection,
progress: progress.clone(),
client: caller.client.clone(),
restart: params.restart,
over,
});
drop(state);
tracing::info!(
connection = ?caller.connection,
client = ?caller.client.name,
client_version = ?caller.client.version,
from = %self.shared.from,
restart = ?params.restart,
"update started"
);
let (connection, left) = (caller.connection, caller.left());
let replaced = (self.shared.daemon.replaced)();
let install = Arc::clone(&self.install);
let task = Task {
shared: Arc::clone(&self.shared),
connection,
progress: progress.clone(),
finished,
};
tokio::spawn(async move {
let mut said = Progress::new(writer);
let done = install.install(environment, replaced, &mut said).await;
let over = said.end(done);
match &over {
Over::Done(done) => tracing::info!(?connection, outcome = ?done, "update over"),
Over::Failed { why, .. } => tracing::warn!(?connection, %why, "update failed"),
}
task.finished.send_replace(Some(over));
let unasked = tokio::select! {
() = left => "the connection that asked left without asking for its result",
() = tokio::time::sleep(UNASKED_RESULT_GRACE) => "its result was not asked for within UNASKED_RESULT_GRACE",
};
if task.shared.settle(connection, &task.progress).is_some() {
tracing::info!(
?connection,
grace_secs = UNASKED_RESULT_GRACE.as_secs(),
"update settled: {unasked}"
);
}
});
Ok(DaemonUpdateResponse::new(
progress,
self.shared.from.clone(),
))
}
pub(super) async fn result(
&self,
caller: &Caller,
params: DaemonUpdateResultParams,
) -> Result<DaemonUpdateResult, RpcError> {
let unknown = || {
RpcError::new(
ErrorCode::InvalidParams,
format!(
"no update this connection started is waiting for its answer with progress stream {}",
params.progress
),
)
};
let mut over = {
let state = lock(&self.shared.state);
match &state.running {
Some(running)
if running.connection == caller.connection
&& running.progress == params.progress =>
{
running.over.clone()
}
_ => return Err(unknown()),
}
};
tokio::select! {
biased;
() = self.shared.daemon.shutdown.requested() => {
return Err(stopping("will not answer the update"));
}
_ = over.wait_for(Option::is_some) => {}
}
match self.shared.settle(caller.connection, ¶ms.progress) {
Some(Ok(outcome)) => Ok(DaemonUpdateResult::new(outcome)),
Some(Err(message)) => Err(RpcError::new(ErrorCode::HostCallFailed, message)),
None => match &*over.borrow() {
Some(Over::Failed { message, .. }) => {
Err(RpcError::new(ErrorCode::HostCallFailed, message.clone()))
}
_ => Err(unknown()),
},
}
}
pub(super) fn follow(&self) -> Follow {
lock(&self.shared.state).follow()
}
pub(super) fn commit(&self, follow: Follow, claim: impl FnOnce() -> bool) -> bool {
let mut state = lock(&self.shared.state);
if follow == Follow::Held || state.follow() != follow {
return false;
}
let committed = claim();
state.committed |= committed;
committed
}
}
struct Task {
shared: Arc<Shared>,
connection: ConnectionId,
progress: HostStreamId,
finished: watch::Sender<Option<Over>>,
}
impl Drop for Task {
fn drop(&mut self) {
let stopped = self.finished.send_if_modified(|over| {
if over.is_some() {
return false;
}
*over = Some(Over::Failed {
why: STOPPED.to_owned(),
message: format!("could not update rho: {STOPPED}"),
});
true
});
let settled = self
.shared
.settle(self.connection, &self.progress)
.is_some();
if stopped {
tracing::warn!(connection = ?self.connection, settled, "{STOPPED}");
}
}
}
impl Shared {
fn settle(
&self,
connection: ConnectionId,
progress: &HostStreamId,
) -> Option<Result<UpdateOutcome, String>> {
let mut state = lock(&self.state);
let running = state
.running
.take_if(|running| running.connection == connection && running.progress == *progress)?;
let over = (*running.over.borrow())
.clone()
.unwrap_or_else(|| Over::Failed {
why: STOPPED.to_owned(),
message: format!("could not update rho: {STOPPED}"),
});
Some(match over {
Over::Failed { message, .. } => Err(message),
Over::Done(Unattended::UpToDate) => Ok(UpdateOutcome::UpToDate),
Over::Done(Unattended::NeedsTerminal { latest, command }) => {
Ok(UpdateOutcome::needs_terminal(latest, command))
}
Over::Done(Unattended::Installed { to, method, lands }) => {
let (restarting, moving) =
next_move(lands, running.restart, (self.daemon.in_progress)());
tracing::info!(
connection = ?running.connection,
client = ?running.client.name,
client_version = ?running.client.version,
from = %self.from,
%to,
method = method.label(),
restart = ?restarting,
"rho updated"
);
state.moving = moving;
Ok(UpdateOutcome::installed(to, method.into(), restarting))
}
})
}
}
fn next_move(lands: Lands, restart: UpdateRestart, in_progress: u64) -> (UpdateRestarting, Follow) {
let now = restart == UpdateRestart::Now;
match lands {
Lands::AtItsPath if now => (UpdateRestarting::Now, Follow::RestartNow),
Lands::AtItsPath => (UpdateRestarting::when_idle(in_progress), Follow::Watch),
Lands::AtAnotherPath(at) => {
let at = HostPath::new(at.to_string_lossy());
let waiting_for = (!now && in_progress > 0).then_some(in_progress);
(
UpdateRestarting::replaced(at, waiting_for),
Follow::Replace { once_idle: !now },
)
}
}
}
impl From<InstallMethod> for UpdateMethod {
fn from(method: InstallMethod) -> Self {
match method {
InstallMethod::Cargo => Self::Cargo,
InstallMethod::Mise => Self::Mise,
InstallMethod::Pacman => Self::Pacman,
InstallMethod::Dnf => Self::Dnf,
InstallMethod::Scoop => Self::Scoop,
InstallMethod::ScoopGlobal => Self::ScoopGlobal,
InstallMethod::Script => Self::Script,
}
}
}
fn stopping(does: &str) -> RpcError {
RpcError::new(
ErrorCode::HostCallFailed,
format!("the daemon is stopping, so it {does}; ask again once it runs"),
)
}
pub(super) struct Progress {
stream: Option<HostStreamWriter>,
tail: StderrTail,
}
impl Progress {
fn new(writer: HostStreamWriter) -> Self {
Self {
stream: Some(writer),
tail: StderrTail::with_limit(OUTPUT_TAIL_BYTES),
}
}
fn line(&mut self, line: &str) {
let mut bytes = Vec::with_capacity(line.len() + 1);
bytes.extend_from_slice(line.as_bytes());
bytes.push(b'\n');
self.tail.push(&bytes);
let Some(writer) = &mut self.stream else {
return;
};
match writer.try_write(bytes) {
Ok(()) => {}
Err(TryWriteError::Closed) => self.stream = None,
Err(_) => {
if let Some(writer) = self.stream.take() {
writer.truncate();
}
}
}
}
fn end(self, done: anyhow::Result<Unattended>) -> Over {
match done {
Ok(done) => {
if let Some(writer) = self.stream {
writer.finish();
}
Over::Done(done)
}
Err(error) => {
let why = cut(format!("{error:#}"), WHY_MAX_BYTES);
if let Some(writer) = self.stream {
writer.fail(why.clone());
}
Over::Failed {
message: failure(&why, self.tail),
why,
}
}
}
}
}
impl Report for Progress {
fn say(&mut self, line: &str) {
self.line(line);
}
fn warn(&mut self, line: &str) {
self.line(line);
}
}
fn cut(text: String, max: usize) -> String {
if text.len() <= max {
return text;
}
let end = rho_sdk::floor_char_boundary(&text, max - rho_sdk::ELLIPSIS.len());
format!("{}{}", &text[..end], rho_sdk::ELLIPSIS)
}
fn failure(why: &str, tail: StderrTail) -> String {
let tail = tail.finish();
if tail.is_empty() {
return format!("could not update rho: {why}");
}
format!(
"could not update rho: {why}\nthe end of its output, at most {OUTPUT_TAIL_BYTES} bytes:\n{tail}"
)
}
fn lock(state: &Mutex<State>) -> MutexGuard<'_, State> {
state.lock().unwrap_or_else(PoisonError::into_inner)
}
#[cfg(test)]
#[path = "machine_update_tests.rs"]
mod tests;