use std::{
ffi::OsString,
io,
path::{Path, PathBuf},
process::{Output, Stdio},
sync::{Mutex, PoisonError},
time::Duration,
};
use anyhow::Context;
use rho_protocol::ClientEnvironment;
use super::{
announce, cargo_update_root_in, detect_install_method_in, latest_release, mise_tool_in,
prepare, update_in_place, version_is_newer, InstallMethod, Lookups, Plan, Report, UpdateCheck,
};
use crate::{
app::daemon_install::Installed,
daemon::{probe_version, started_path, DaemonPaths},
installation::{installed_scoop_scope, Probe, ScoopInstallScope},
};
#[cfg(not(windows))]
const INSTALLER_DEADLINE: Duration = Duration::from_secs(60 * 60);
#[cfg(not(windows))]
const PIPE_DRAIN_AFTER_EXIT: Duration = Duration::from_secs(1);
#[cfg(not(windows))]
const LINE_MAX_BYTES: usize = 4 * 1024;
const LOOKUP_TIMEOUT: Duration = Duration::from_secs(10);
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum Unattended {
UpToDate,
NeedsTerminal { latest: String, command: String },
Installed {
to: String,
method: InstallMethod,
lands: Lands,
},
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum Lands {
AtItsPath,
AtAnotherPath(PathBuf),
}
pub(crate) async fn update_unattended(
current_version: &str,
replaced: Option<String>,
environment: &ClientEnvironment,
report: &mut impl Report,
) -> anyhow::Result<Unattended> {
let own_path = started_path();
let (method, lookups) = install_method(environment).await?;
if let Some(to) = replaced.filter(|to| version_is_newer(to, current_version)) {
report.say(&format!(
"rho v{to} already replaced this rho; the daemon moves onto it"
));
return Ok(Unattended::Installed {
to,
method,
lands: Lands::AtItsPath,
});
}
if method.needs_terminal() {
let update = latest_release(current_version)
.await
.context("could not check the latest rho release")?;
let check = UpdateCheck::new(update, method, &lookups)?;
return Ok(match check.command {
None => Unattended::UpToDate,
Some(command) => Unattended::NeedsTerminal {
latest: check.latest,
command,
},
});
}
let Some(plan) = prepare(method, current_version, report).await? else {
return Ok(Unattended::UpToDate);
};
announce(method, &plan, &lookups, report)?;
match plan {
Plan::Run { git_ref } => {
run_command(method, &git_ref, &lookups, environment, report).await?;
}
Plan::InPlace(update) => update_in_place(method, &update, report).await?,
Plan::Print { .. } => {
anyhow::bail!("rho only prints the {} update command here", method.label())
}
}
let (to, lands) = installed_version(method, own_path, environment, current_version).await?;
Ok(Unattended::Installed { to, method, lands })
}
pub(crate) async fn check_unattended(
current_version: &str,
environment: &ClientEnvironment,
) -> anyhow::Result<UpdateCheck> {
let update = latest_release(current_version)
.await
.context("could not check the latest rho release")?;
let (method, lookups) = install_method(environment).await?;
UpdateCheck::new(update, method, &lookups)
}
async fn install_method(
environment: &ClientEnvironment,
) -> anyhow::Result<(InstallMethod, Lookups)> {
let copies = DaemonPaths::of_this_process().map(|paths| paths.copies_dir());
let copied = match (super::current_exe(), copies) {
(Ok(executable), Ok(copies)) => is_copy(&executable, &copies),
_ => false,
};
let login = Login::new(
environment.clone(),
tokio::runtime::Handle::current(),
LOOKUP_TIMEOUT,
);
tokio::task::spawn_blocking(move || {
let method = if copied {
match installed_scoop_scope() {
ScoopInstallScope::User => InstallMethod::Scoop,
ScoopInstallScope::Global => InstallMethod::ScoopGlobal,
}
} else {
detect_install_method_in(&login)
};
let cargo_root = match method {
InstallMethod::Cargo => cargo_update_root_in(&login),
_ => None,
};
if let Some(why) = login.timed_out() {
anyhow::bail!("{why}");
}
let mise_tool = match method {
InstallMethod::Mise => mise_tool_in(&login).map_err(|err| format!("{err:#}")),
_ => Err("rho was not installed with mise".to_owned()),
};
Ok((
method,
Lookups::Found {
cargo_root,
mise_tool,
},
))
})
.await
.context("could not tell how rho was installed")?
.context("could not tell how rho was installed")
}
struct Login {
environment: ClientEnvironment,
runtime: tokio::runtime::Handle,
timeout: Duration,
timed_out: Mutex<Option<String>>,
}
impl Login {
fn new(
environment: ClientEnvironment,
runtime: tokio::runtime::Handle,
timeout: Duration,
) -> Self {
Self {
environment,
runtime,
timeout,
timed_out: Mutex::default(),
}
}
fn timed_out(&self) -> Option<String> {
self.timed_out
.lock()
.unwrap_or_else(PoisonError::into_inner)
.clone()
}
}
impl Probe for Login {
fn var(&self, name: &str) -> Option<OsString> {
self.environment
.iter()
.find(|(variable, _)| *variable == name)
.map(|(_, value)| value.into())
}
fn output(&self, command: std::process::Command) -> io::Result<Output> {
let shown = std::iter::once(command.get_program())
.chain(command.get_args())
.map(|part| part.to_string_lossy())
.collect::<Vec<_>>()
.join(" ");
let mut command = tokio::process::Command::from(command);
command
.env_clear()
.envs(self.environment.iter())
.stdin(Stdio::null())
.kill_on_drop(true);
if let Some(home) = self.var("HOME") {
command.current_dir(home);
}
let ran = self
.runtime
.block_on(async { tokio::time::timeout(self.timeout, command.output()).await });
ran.unwrap_or_else(|_| {
let why = format!(
"`{shown}` did not answer within LOOKUP_TIMEOUT ({:?})",
self.timeout
);
let mut kept = self
.timed_out
.lock()
.unwrap_or_else(PoisonError::into_inner);
if kept.is_none() {
*kept = Some(why.clone());
}
Err(io::Error::new(io::ErrorKind::TimedOut, why))
})
}
}
fn is_copy(executable: &Path, copies: &Path) -> bool {
let dir = |path: &Path| std::fs::canonicalize(path).ok();
let copies = dir(copies);
copies.is_some() && executable.parent().and_then(dir) == copies
}
async fn installed_version(
method: InstallMethod,
own_path: io::Result<PathBuf>,
environment: &ClientEnvironment,
current_version: &str,
) -> anyhow::Result<(String, Lands)> {
let (path, lands) = match method.installs() {
Installed::OverTheExecutable | Installed::MovingTheRunningAside => (
own_path.context("could not find the rho the daemon runs")?,
Lands::AtItsPath,
),
Installed::AtAnotherPath => {
let path = match method {
InstallMethod::Mise => mise_which(environment).await?,
_ => on_path(environment)
.context("the installer finished, but the login PATH finds no `rho`")?,
};
(path.clone(), Lands::AtAnotherPath(path))
}
};
let version = newer_version(&path, current_version).await?;
Ok((version, lands))
}
async fn newer_version(path: &Path, current_version: &str) -> anyhow::Result<String> {
let version = probe_version(path).await.with_context(|| {
format!(
"the installer finished, but {} does not run as rho",
path.display()
)
})?;
newer(path, version, current_version)
}
fn newer(path: &Path, version: String, current_version: &str) -> anyhow::Result<String> {
if !version_is_newer(&version, current_version) {
anyhow::bail!(
"the installer finished, but {} still reports rho {version}",
path.display()
);
}
Ok(version)
}
async fn mise_which(environment: &ClientEnvironment) -> anyhow::Result<PathBuf> {
let mut command = tokio::process::Command::new("mise");
command
.args(["which", "rho"])
.env_clear()
.envs(environment.iter())
.stdin(Stdio::null())
.kill_on_drop(true);
if let Some((_, home)) = environment.iter().find(|(name, _)| *name == "HOME") {
command.current_dir(home);
}
let output = tokio::time::timeout(LOOKUP_TIMEOUT, command.output())
.await
.map_err(|_| {
anyhow::anyhow!(
"`mise which rho` did not answer within LOOKUP_TIMEOUT ({} s)",
LOOKUP_TIMEOUT.as_secs()
)
})?
.context("could not run `mise which rho`")?;
let printed = String::from_utf8_lossy(&output.stdout);
let path = PathBuf::from(printed.trim());
if !output.status.success() || !path.is_absolute() {
anyhow::bail!(
"`mise which rho` named no rho ({}); the installer finished all the same",
output.status
);
}
Ok(path)
}
fn on_path(environment: &ClientEnvironment) -> Option<PathBuf> {
let (_, path) = environment
.iter()
.find(|(name, _)| name.eq_ignore_ascii_case("PATH"))?;
let name = format!("rho{}", std::env::consts::EXE_SUFFIX);
std::env::split_paths(path)
.filter(|dir| dir.is_absolute())
.map(|dir| dir.join(&name))
.find(|file| file.is_file())
}
#[cfg(windows)]
async fn run_command(
method: InstallMethod,
_git_ref: &str,
_lookups: &Lookups,
_environment: &ClientEnvironment,
_report: &mut impl Report,
) -> anyhow::Result<()> {
anyhow::bail!("rho runs no {} update command on Windows", method.label())
}
#[cfg(not(windows))]
async fn run_command(
method: InstallMethod,
git_ref: &str,
lookups: &Lookups,
environment: &ClientEnvironment,
report: &mut impl Report,
) -> anyhow::Result<()> {
let command = super::update_command(method, git_ref, lookups, Some(environment))?;
run_reporting(command, method.label(), INSTALLER_DEADLINE, report).await
}
#[cfg(not(windows))]
async fn run_reporting(
mut command: tokio::process::Command,
label: &str,
deadline: Duration,
report: &mut impl Report,
) -> anyhow::Result<()> {
let mut child = command
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.process_group(0)
.spawn()
.with_context(|| format!("failed to run {label} update command"))?;
let group = child.id();
let (sender, mut lines) = tokio::sync::mpsc::unbounded_channel();
if let Some(stdout) = child.stdout.take() {
tokio::spawn(forward_lines(stdout, sender.clone()));
}
if let Some(stderr) = child.stderr.take() {
tokio::spawn(forward_lines(stderr, sender));
}
let status = {
let mut exited = std::pin::pin!(child.wait());
let mut deadline_passed = std::pin::pin!(tokio::time::sleep(deadline));
let mut open = true;
loop {
tokio::select! {
status = &mut exited => break status,
line = lines.recv(), if open => match line {
Some(line) => report.say(&line),
None => open = false,
},
() = &mut deadline_passed => {
if let Some(group) = group.and_then(|group| libc::pid_t::try_from(group).ok()) {
unsafe { libc::killpg(group, libc::SIGKILL) };
}
anyhow::bail!(
"{label} update command ran past INSTALLER_DEADLINE ({} min), so rho stopped it",
deadline.as_secs() / 60
);
}
}
}
}
.with_context(|| format!("failed to run {label} update command"))?;
let drained = async {
while let Some(line) = lines.recv().await {
report.say(&line);
}
};
let _ = tokio::time::timeout(PIPE_DRAIN_AFTER_EXIT, drained).await;
if !status.success() {
anyhow::bail!("{label} update command exited with {status}");
}
Ok(())
}
#[cfg(not(windows))]
async fn forward_lines(
output: impl tokio::io::AsyncRead + Unpin,
lines: tokio::sync::mpsc::UnboundedSender<String>,
) {
use tokio::io::AsyncBufReadExt as _;
let mut output = tokio::io::BufReader::new(output);
let mut line = Vec::new();
let send = |line: &mut Vec<u8>| {
let text = String::from_utf8_lossy(line);
let _ = lines.send(text.trim_end_matches(['\n', '\r']).to_owned());
line.clear();
};
loop {
let chunk = match output.fill_buf().await {
Ok([]) | Err(_) => break,
Ok(chunk) => chunk,
};
let room = &chunk[..chunk.len().min(LINE_MAX_BYTES - line.len())];
let (taken, ended) = match room.iter().position(|byte| *byte == b'\n') {
Some(end) => (end + 1, true),
None => (room.len(), line.len() + room.len() == LINE_MAX_BYTES),
};
line.extend_from_slice(&room[..taken]);
output.consume(taken);
if ended {
send(&mut line);
}
}
if !line.is_empty() {
send(&mut line);
}
}
#[cfg(test)]
#[path = "update_unattended_tests.rs"]
mod tests;