use std::env;
use std::ffi::OsString;
use std::iter;
use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::time::{Duration, Instant};
use tokio::process::Command;
use tokio::time;
use crate::cli::service as cli_service;
use crate::store::cluster;
use crate::store::cluster::version::{Version, Versions};
use crate::store::cluster::{Member, Node, NodeId};
use crate::sys::tmux::TmuxManager;
const CHECK_EVERY: Duration = Duration::from_secs(60);
const FIRST_RETRY: Duration = Duration::from_secs(5 * 60);
const MAX_RETRY: Duration = Duration::from_secs(2 * 60 * 60);
const UPGRADE_TIMEOUT: Duration = Duration::from_secs(15 * 60);
const CRATE: &str = "orch-cli";
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Install {
Brew {
brew: PathBuf,
orch: PathBuf,
},
Cargo {
dir: PathBuf,
binstall: Option<PathBuf>,
},
Other(PathBuf),
}
pub(crate) fn detect(exe: &Path, cargo_home: Option<&Path>, home: Option<&Path>) -> Install {
let real = exe.canonicalize().unwrap_or_else(|_| exe.to_path_buf());
let text = real.to_string_lossy();
if let Some((prefix, _)) = text.split_once("/Cellar/orch/") {
let prefix = Path::new(prefix);
return Install::Brew {
brew: prefix.join("bin/brew"),
orch: prefix.join("opt/orch/bin/orch"),
};
}
let Some(dir) = real.parent() else {
return Install::Other(real);
};
let cargo_bins: Vec<PathBuf> = cargo_home
.map(|c| c.join("bin"))
.into_iter()
.chain(home.map(|h| h.join(".cargo/bin")))
.collect();
if !cargo_bins.iter().any(|b| b == dir) && !dir.ends_with(".cargo/bin") {
return Install::Other(real);
}
let binstall = iter::once(dir.to_path_buf())
.chain(cargo_bins)
.map(|d| d.join("cargo-binstall"))
.find(|p| p.is_file());
Install::Cargo {
dir: dir.to_path_buf(),
binstall,
}
}
pub(crate) fn binstall_args(dir: &Path, target: Version) -> Vec<OsString> {
vec![
"binstall".into(),
"--no-confirm".into(),
"--disable-strategies".into(),
"compile".into(),
"--install-path".into(),
dir.into(),
format!("{CRATE}@{target}").into(),
]
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum UpgradeError {
Unsupported(String),
Failed(String),
}
pub(crate) trait Host {
async fn live_sessions(&self) -> usize;
async fn upgrade(&self, target: Version) -> Result<Version, UpgradeError>;
async fn restart(&self) -> anyhow::Result<()>;
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Peer {
pub id: NodeId,
pub voter: bool,
pub reachable: bool,
pub version: Option<Version>,
pub auto_upgrade: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct View {
pub id: NodeId,
pub voter: bool,
pub mine: Version,
pub target: Option<Version>,
pub auto_upgrade: bool,
pub peers: Vec<Peer>,
}
impl View {
pub(crate) fn of(id: NodeId, versions: &Versions, members: &[Member]) -> Option<Self> {
Some(Self {
id,
voter: members.iter().any(|m| m.me && m.voter),
mine: versions.mine()?,
target: versions.target(),
auto_upgrade: versions.auto_upgrade(),
peers: members
.iter()
.filter(|m| !m.me)
.map(|m| Peer {
id: m.id,
voter: m.voter,
reachable: m.answered.is_some(),
version: m.version,
auto_upgrade: m.answered.as_ref().is_some_and(|a| a.auto_upgrade),
})
.collect(),
})
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Wait {
Off,
Current,
VoterUnreachable(NodeId),
Behind(NodeId),
Backoff,
Sessions(usize),
Unsupported,
}
pub(crate) fn turn(v: &View) -> Result<Version, Wait> {
if !v.auto_upgrade {
return Err(Wait::Off);
}
let Some(target) = v.target.filter(|t| *t > v.mine) else {
return Err(Wait::Current);
};
if v.voter
&& let Some(p) = v.peers.iter().find(|p| p.voter && !p.reachable)
{
return Err(Wait::VoterUnreachable(p.id));
}
let first = v
.peers
.iter()
.filter(|p| p.reachable && p.auto_upgrade && p.version.is_some_and(|x| x < target))
.map(|p| p.id)
.min();
match first {
Some(id) if id < v.id => Err(Wait::Behind(id)),
_ => Ok(target),
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Step {
Waited(Wait),
Failed,
Restarted,
}
pub(crate) struct Upgrader<H> {
host: H,
failures: u32,
retry_at: Option<Instant>,
warned: bool,
}
impl<H: Host> Upgrader<H> {
pub(crate) fn new(host: H) -> Self {
Self {
host,
failures: 0,
retry_at: None,
warned: false,
}
}
#[cfg(test)]
pub(crate) fn host(&self) -> &H {
&self.host
}
pub(crate) async fn step(&mut self, view: &View, versions: &Versions, now: Instant) -> Step {
let target = match turn(view) {
Ok(t) => t,
Err(w) => return Step::Waited(w),
};
if self.retry_at.is_some_and(|at| now < at) {
return Step::Waited(Wait::Backoff);
}
let sessions = self.host.live_sessions().await;
if sessions > 0 {
return Step::Waited(Wait::Sessions(sessions));
}
tracing::info!(from = %view.mine, to = %target, "upgrading orch to the cluster's version");
let done = match self.host.upgrade(target).await {
Ok(installed) if installed > view.mine => {
self.host.restart().await.map_err(|e| e.to_string())
}
Ok(installed) => Err(format!(
"the upgrade left orch {installed}, which is not newer than {}",
view.mine
)),
Err(UpgradeError::Unsupported(why)) => {
if !self.warned {
tracing::warn!(target_version = %target, "cannot upgrade orch: {why}");
self.warned = true;
}
versions.set_upgrade_error(Some(why));
return Step::Waited(Wait::Unsupported);
}
Err(UpgradeError::Failed(e)) => Err(e),
};
match done {
Ok(()) => {
versions.set_upgrade_error(None);
Step::Restarted
}
Err(e) => {
self.failures += 1;
let delay = retry_delay(self.failures);
self.retry_at = Some(now + delay);
tracing::warn!(target_version = %target, retry_in = ?delay, err = %e, "orch upgrade failed");
versions.set_upgrade_error(Some(e));
Step::Failed
}
}
}
}
fn retry_delay(failures: u32) -> Duration {
let doubled = FIRST_RETRY.saturating_mul(2u32.saturating_pow(failures.saturating_sub(1)));
doubled.min(MAX_RETRY)
}
pub(crate) async fn run(node: Node) {
let exe = env::current_exe().unwrap_or_default();
let install = detect(
&exe,
env::var_os("CARGO_HOME").map(PathBuf::from).as_deref(),
env::var_os("HOME").map(PathBuf::from).as_deref(),
);
tracing::info!(?install, "cluster.auto_upgrade is on");
let mut upgrader = Upgrader::new(SystemHost { install });
let mut ticker = time::interval(CHECK_EVERY);
loop {
ticker.tick().await;
let members = cluster::describe(&node).await;
let Some(view) = View::of(node.id(), node.versions(), &members) else {
return;
};
match upgrader.step(&view, node.versions(), Instant::now()).await {
Step::Restarted => return,
Step::Waited(why) => tracing::debug!(?why, "auto upgrade waits"),
Step::Failed => {}
}
}
}
struct SystemHost {
install: Install,
}
impl SystemHost {
async fn run(program: &Path, args: &[OsString]) -> Result<(), UpgradeError> {
let mut cmd = Command::new(program);
cmd.args(args)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true);
let out = time::timeout(UPGRADE_TIMEOUT, cmd.output())
.await
.map_err(|_| UpgradeError::Failed(format!("{} timed out", program.display())))?
.map_err(|e| UpgradeError::Failed(format!("{}: {e}", program.display())))?;
if out.status.success() {
return Ok(());
}
let stderr = String::from_utf8_lossy(&out.stderr);
let last = stderr.lines().rev().find(|l| !l.trim().is_empty());
let last: String = last.unwrap_or_default().trim().chars().take(200).collect();
Err(UpgradeError::Failed(format!(
"{} exited with {}: {last}",
program.display(),
out.status
)))
}
async fn installed(orch: &Path) -> Result<Version, UpgradeError> {
let out = Command::new(orch)
.arg("--version")
.output()
.await
.map_err(|e| UpgradeError::Failed(format!("{}: {e}", orch.display())))?;
let text = String::from_utf8_lossy(&out.stdout);
text.split_whitespace()
.last()
.and_then(|v| v.parse().ok())
.ok_or_else(|| UpgradeError::Failed(format!("{} printed no version", orch.display())))
}
}
impl Host for SystemHost {
async fn live_sessions(&self) -> usize {
TmuxManager::new()
.list_sessions()
.await
.map_or(0, |s| s.len())
}
async fn upgrade(&self, target: Version) -> Result<Version, UpgradeError> {
match &self.install {
Install::Brew { brew, orch } => {
Self::run(brew, &["upgrade".into(), "orch".into()]).await?;
Self::installed(orch).await
}
Install::Cargo {
dir,
binstall: Some(binstall),
} => {
Self::run(binstall, &binstall_args(dir, target)).await?;
Self::installed(&dir.join("orch")).await
}
Install::Cargo { binstall: None, .. } => Err(UpgradeError::Unsupported(
"cargo-binstall is not next to orch or in the cargo bin directory".into(),
)),
Install::Other(path) => Err(UpgradeError::Unsupported(format!(
"{} was not installed by Homebrew or cargo",
path.display()
))),
}
}
async fn restart(&self) -> anyhow::Result<()> {
let (program, args) = cli_service::restart_command();
let program = match &self.install {
Install::Brew { brew, .. } if program == "brew" => brew.clone(),
_ => PathBuf::from(program),
};
Command::new(program)
.args(args)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.process_group(0)
.spawn()?;
Ok(())
}
}
#[cfg(test)]
mod tests;