Skip to main content

rigtop_core/
update.rs

1//! Updating rigtop: this machine's copy to the latest release, and remote
2//! hosts to this machine's version.
3//!
4//! The latest release is looked up with the system's `curl` (Windows 10 and
5//! later ship one), from where `/releases/latest` redirects to, so no API
6//! rate limit applies. An update feeds a script to `sh -s`, locally or over
7//! the host's SSH connection settings. It finds the rigtop to replace and,
8//! when that sits in a directory the user can write to, installs the
9//! release through its `install.sh` (curl or wget, checksums). Copies
10//! installed by `cargo install` or a package manager are left alone, with
11//! the command to update them instead. No new dependency is needed.
12
13use std::io::Write;
14use std::path::Path;
15use std::process::{Command, Stdio};
16use std::sync::mpsc::{self, Receiver};
17use std::thread;
18use std::time::{Duration, Instant};
19
20use crate::remote::RemoteTarget;
21
22/// Where release files are downloaded from.
23const RELEASES_URL: &str = "https://github.com/akivajp/rigtop/releases/download";
24/// Redirects to the page of the latest release (`.../tag/v0.12.0`).
25const LATEST_URL: &str = "https://github.com/akivajp/rigtop/releases/latest";
26
27/// This rigtop's version, the one remote hosts are updated to.
28pub fn target_version() -> &'static str {
29    env!("CARGO_PKG_VERSION")
30}
31
32/// Whether an agent reporting `agent_version` is older than this rigtop,
33/// so that updating it helps (`false` when unknown or not older).
34pub fn agent_is_older(agent_version: &str) -> bool {
35    match (
36        parse_version(agent_version),
37        parse_version(target_version()),
38    ) {
39        (Some(agent), Some(ours)) => agent < ours,
40        _ => false,
41    }
42}
43
44/// Whether `version` (e.g. of the latest release) is newer than this rigtop.
45pub fn is_newer(version: &str) -> bool {
46    match (parse_version(version), parse_version(target_version())) {
47        (Some(other), Some(ours)) => other > ours,
48        _ => false,
49    }
50}
51
52/// "0.10.1" -> [0, 10, 1]; pre-release suffixes are ignored.
53fn parse_version(version: &str) -> Option<Vec<u64>> {
54    let core = version.split(['-', '+']).next()?;
55    core.split('.').map(|part| part.parse().ok()).collect()
56}
57
58/// The program an agent command starts: its first word when that is a
59/// path (`/opt/rigtop/rigtop --agent`), else `None` (found on `PATH`).
60fn agent_binary(agent_command: &str) -> Option<&str> {
61    agent_command
62        .split_whitespace()
63        .next()
64        .filter(|program| program.contains('/'))
65}
66
67/// Puts `text` in single quotes for `sh`.
68fn shell_quote(text: &str) -> String {
69    format!("'{}'", text.replace('\'', r"'\''"))
70}
71
72/// The script run on the remote host with `sh -s` to update the rigtop
73/// that `agent_command` starts to `version` (e.g. "0.11.0").
74pub fn update_script(version: &str, agent_command: &str) -> String {
75    script(version, agent_binary(agent_command))
76}
77
78/// The script that updates this machine's copy at `exe` (the running
79/// program, `rigtop` or `rigtop-gui`) to `version`.
80pub fn self_update_script(version: &str, exe: &Path) -> String {
81    script(version, Some(&exe.to_string_lossy()))
82}
83
84/// The update script for the program at `binary`, or the `rigtop` on PATH.
85fn script(version: &str, binary: Option<&str>) -> String {
86    let tag = shell_quote(&format!("v{version}"));
87    let url = shell_quote(&format!("{RELEASES_URL}/v{version}/install.sh"));
88    // A leading "~/" is expanded by the remote shell; quoting would stop it.
89    let find = match binary {
90        Some(path) => match path.strip_prefix("~/") {
91            Some(rest) => format!("bin=\"$HOME\"/{}", shell_quote(rest)),
92            None => format!("bin={}", shell_quote(path)),
93        },
94        // Like the agent connection: PATH first, then the install script's
95        // directory, then cargo's.
96        None => "bin=$(command -v rigtop 2>/dev/null || true)\n\
97                 [ -n \"$bin\" ] || [ ! -x \"$HOME/.local/bin/rigtop\" ] || bin=\"$HOME/.local/bin/rigtop\"\n\
98                 [ -n \"$bin\" ] || [ ! -x \"$HOME/.cargo/bin/rigtop\" ] || bin=\"$HOME/.cargo/bin/rigtop\""
99            .to_owned(),
100    };
101    format!(
102        r#"set -eu
103{find}
104if [ -z "$bin" ] || [ ! -e "$bin" ]; then
105    echo "rigtop update: rigtop not found on this host" >&2
106    exit 1
107fi
108case "$bin" in
109    */.cargo/bin/*)
110        echo "rigtop update: $bin was installed with cargo; update it with: cargo install $(basename "$bin") --version {version} --locked" >&2
111        exit 1
112        ;;
113esac
114dir=$(dirname "$bin")
115if [ ! -w "$dir" ]; then
116    echo "rigtop update: $dir is not writable (a package manager's copy?); update it with the package manager or the .deb of v{version}" >&2
117    exit 1
118fi
119# Keep rigtop-gui only where it was installed.
120gui=--tui-only
121[ ! -x "$dir/rigtop-gui" ] || gui=
122script=$(mktemp)
123trap 'rm -f "$script"' EXIT
124if command -v curl >/dev/null 2>&1; then
125    curl -fsSL --retry 3 {url} -o "$script"
126elif command -v wget >/dev/null 2>&1; then
127    wget -q -O "$script" {url}
128else
129    echo "rigtop update: needs curl or wget" >&2
130    exit 1
131fi
132sh "$script" --version {tag} --bin-dir "$dir" $gui
133"#
134    )
135}
136
137/// Why a host whose OS is `os` (from its snapshot) cannot be updated from
138/// here, if it cannot: the update script needs a POSIX shell.
139pub fn unsupported_reason(os: &str) -> Option<String> {
140    os.starts_with("Windows").then(|| {
141        "on Windows, update rigtop there with `scoop update rigtop`, or with the zip \
142         from the releases page"
143            .to_owned()
144    })
145}
146
147/// Why this machine's copy cannot update itself, if it cannot: on Windows
148/// a running program cannot be replaced in place (see the README).
149pub fn self_update_unsupported() -> Option<String> {
150    cfg!(windows).then(|| {
151        "on Windows, quit rigtop and run `scoop update rigtop`, or replace it with the \
152         zip from the releases page"
153            .to_owned()
154    })
155}
156
157/// What updating this machine's copy to `version` does, shown before asking.
158pub fn describe_self(version: &str) -> String {
159    format!(
160        "Update rigtop from {ours} to {version}? This downloads the v{version} release \
161         from GitHub, checks it and replaces the rigtop you are running (when it is in a \
162         directory you can write to; copies from cargo or a package manager are left \
163         alone). The new version runs after a restart.",
164        ours = target_version()
165    )
166}
167
168/// One sentence on what an update does, shown before asking.
169pub fn describe(host: &str, agent_version: &str) -> String {
170    format!(
171        "Update rigtop on {host} from {agent_version} to {version}? Over SSH, this \
172         downloads the v{version} release from GitHub, checks it and replaces the \
173         rigtop the agent runs (when it is in a directory you can write to; copies \
174         from cargo or a package manager are left alone). The connection then restarts.",
175        version = target_version()
176    )
177}
178
179/// An update running in the background.
180pub struct UpdateJob {
181    result: Receiver<Result<String, String>>,
182}
183
184impl UpdateJob {
185    /// Starts updating the host `target` connects to, to this version.
186    pub fn start(target: &RemoteTarget) -> Self {
187        let agent_command = target.args.last().cloned().unwrap_or_default();
188        let script = update_script(target_version(), &agent_command);
189        // Same SSH options and destination, but a shell reading the script.
190        let mut args = target.args.clone();
191        if let Some(last) = args.last_mut() {
192            *last = "sh -s".to_owned();
193        }
194        Self::spawn(target.program.clone(), args, script)
195    }
196
197    /// Starts updating this machine's copy at `exe` to `version`. `exe`
198    /// must be taken at startup: once replaced, the running program's
199    /// path reads "... (deleted)" on Linux.
200    pub fn start_self(version: &str, exe: &Path) -> Self {
201        let script = self_update_script(version, exe);
202        Self::spawn("sh".to_owned(), vec!["-s".to_owned()], script)
203    }
204
205    fn spawn(program: String, args: Vec<String>, script: String) -> Self {
206        let (tx, result) = mpsc::channel();
207        thread::Builder::new()
208            .name("rigtop-update".to_owned())
209            .spawn(move || {
210                let result = run_script(&program, &args, &script).map(|line| {
211                    // install.sh ends with "rigtop install: done: rigtop 0.11.0".
212                    line.strip_prefix("rigtop install: done: ")
213                        .map_or(line.clone(), str::to_owned)
214                });
215                let _ = tx.send(result);
216            })
217            .expect("spawn update thread");
218        Self { result }
219    }
220
221    /// The outcome once finished: the last line of the output, or why it
222    /// failed.
223    pub fn poll(&self) -> Option<Result<String, String>> {
224        self.result.try_recv().ok()
225    }
226}
227
228/// How often [`ReleaseChecker`] looks for a new release by default.
229pub const DEFAULT_CHECK_INTERVAL: Duration = Duration::from_secs(3600);
230
231/// Looks for new releases now and then, in the background.
232pub struct ReleaseChecker {
233    interval: Duration,
234    next_check: Instant,
235    running: Option<Receiver<Result<String, String>>>,
236    /// Newest version seen that is newer than this rigtop.
237    newer: Option<String>,
238    fetch: fn() -> Result<String, String>,
239}
240
241impl ReleaseChecker {
242    /// Checks right away, then every `interval`.
243    pub fn new(interval: Duration) -> Self {
244        Self::with_fetch(interval, latest_release)
245    }
246
247    fn with_fetch(interval: Duration, fetch: fn() -> Result<String, String>) -> Self {
248        Self {
249            interval,
250            next_check: Instant::now(),
251            running: None,
252            newer: None,
253            fetch,
254        }
255    }
256
257    /// A newer release than this rigtop, once one has been seen (e.g.
258    /// "0.12.1"). Call regularly: it also starts the next check when due.
259    pub fn poll(&mut self) -> Option<&str> {
260        if let Some(running) = &self.running
261            && let Ok(result) = running.try_recv()
262        {
263            self.running = None;
264            // A failed check (offline, no curl) just waits for the next one.
265            if let Ok(version) = result
266                && is_newer(&version)
267            {
268                self.newer = Some(version);
269            }
270        }
271        if self.running.is_none() && Instant::now() >= self.next_check {
272            self.next_check = Instant::now() + self.interval;
273            let (tx, rx) = mpsc::channel();
274            let fetch = self.fetch;
275            let started = thread::Builder::new()
276                .name("rigtop-release-check".to_owned())
277                .spawn(move || {
278                    let _ = tx.send(fetch());
279                });
280            if started.is_ok() {
281                self.running = Some(rx);
282            }
283        }
284        self.newer.as_deref()
285    }
286}
287
288/// The version of the latest release (e.g. "0.12.0"), from where GitHub's
289/// `/releases/latest` redirects to.
290pub fn latest_release() -> Result<String, String> {
291    let null = if cfg!(windows) { "NUL" } else { "/dev/null" };
292    let mut command = Command::new("curl");
293    command
294        .args([
295            "-fsSL",
296            "--max-time",
297            "30",
298            "-o",
299            null,
300            "-w",
301            "%{url_effective}",
302        ])
303        .arg(LATEST_URL)
304        .stdin(Stdio::null())
305        .stderr(Stdio::null());
306    #[cfg(windows)]
307    {
308        use std::os::windows::process::CommandExt;
309        // CREATE_NO_WINDOW: a GUI must not flash a console for curl.exe.
310        command.creation_flags(0x0800_0000);
311    }
312    let output = command
313        .output()
314        .map_err(|err| format!("cannot run curl: {err}"))?;
315    if !output.status.success() {
316        return Err(format!("curl exited with {}", output.status));
317    }
318    version_from_release_url(&String::from_utf8_lossy(&output.stdout))
319        .ok_or_else(|| "no release found".to_owned())
320}
321
322/// ".../releases/tag/v0.12.0" -> "0.12.0".
323fn version_from_release_url(url: &str) -> Option<String> {
324    let tag = url.trim().rsplit_once("/tag/")?.1;
325    let version = tag.strip_prefix('v')?;
326    parse_version(version).map(|_| version.to_owned())
327}
328
329/// Runs `program args` with `script` on its stdin and returns the last
330/// line it printed, or, when it fails, the last line of its errors.
331fn run_script(program: &str, args: &[String], script: &str) -> Result<String, String> {
332    let mut command = Command::new(program);
333    command
334        .args(args)
335        .stdin(Stdio::piped())
336        .stdout(Stdio::piped())
337        .stderr(Stdio::piped());
338    #[cfg(windows)]
339    {
340        use std::os::windows::process::CommandExt;
341        // CREATE_NO_WINDOW: a GUI must not flash a console for ssh.exe.
342        command.creation_flags(0x0800_0000);
343    }
344    let mut child = command
345        .spawn()
346        .map_err(|err| format!("cannot start {program}: {err}"))?;
347    if let Some(mut stdin) = child.stdin.take() {
348        // A shell that exits early closes the pipe; its status says why.
349        let _ = stdin.write_all(script.as_bytes());
350    }
351    let output = child
352        .wait_with_output()
353        .map_err(|err| format!("{program} failed: {err}"))?;
354    let last_line = |bytes: &[u8]| {
355        String::from_utf8_lossy(bytes)
356            .lines()
357            .rev()
358            .map(str::trim)
359            .find(|line| !line.is_empty())
360            .map(str::to_owned)
361    };
362    if output.status.success() {
363        Ok(last_line(&output.stdout).unwrap_or_else(|| "done".to_owned()))
364    } else {
365        Err(last_line(&output.stderr)
366            .or_else(|| last_line(&output.stdout))
367            .unwrap_or_else(|| format!("{program} exited with {}", output.status)))
368    }
369}
370
371#[cfg(test)]
372mod tests {
373    use super::*;
374
375    #[test]
376    fn versions_compare_by_number() {
377        assert_eq!(parse_version("0.10.1"), Some(vec![0, 10, 1]));
378        assert_eq!(parse_version("1.2.0-rc.1"), Some(vec![1, 2, 0]));
379        assert_eq!(parse_version(""), None);
380        assert!(agent_is_older("0.0.9"));
381        assert!(!agent_is_older(target_version()));
382        assert!(!agent_is_older("999.0.0"));
383        assert!(!agent_is_older(""), "unknown versions are not offered");
384    }
385
386    #[test]
387    fn newer_releases_are_found() {
388        assert_eq!(
389            version_from_release_url("https://github.com/akivajp/rigtop/releases/tag/v0.12.1\n"),
390            Some("0.12.1".to_owned())
391        );
392        assert_eq!(
393            version_from_release_url("https://github.com/akivajp/rigtop/releases"),
394            None
395        );
396        assert!(is_newer("999.0.0"));
397        assert!(!is_newer(target_version()));
398
399        let mut checker =
400            ReleaseChecker::with_fetch(Duration::from_secs(3600), || Ok("999.0.0".to_owned()));
401        // The first call starts the check; the answer comes a moment later.
402        let mut found = None;
403        for _ in 0..100 {
404            if let Some(version) = checker.poll() {
405                found = Some(version.to_owned());
406                break;
407            }
408            thread::sleep(Duration::from_millis(10));
409        }
410        assert_eq!(found.as_deref(), Some("999.0.0"));
411
412        let mut checker = ReleaseChecker::with_fetch(Duration::from_secs(3600), || {
413            Ok(target_version().to_owned())
414        });
415        checker.poll();
416        thread::sleep(Duration::from_millis(50));
417        assert!(checker.poll().is_none(), "the same version is not news");
418    }
419
420    /// Asks GitHub (network): `cargo test -p rigtop-core -- --ignored latest_release`.
421    #[test]
422    #[ignore]
423    fn latest_release_from_github() {
424        let version = latest_release().unwrap();
425        assert!(parse_version(&version).is_some(), "{version}");
426    }
427
428    #[test]
429    fn self_update_script_targets_the_running_program() {
430        let script = self_update_script("1.2.3", Path::new("/home/me/.local/bin/rigtop-gui"));
431        assert!(script.contains("bin='/home/me/.local/bin/rigtop-gui'"));
432    }
433
434    #[test]
435    fn windows_hosts_get_directions_instead() {
436        assert!(unsupported_reason("Windows 11 Pro").is_some());
437        assert!(unsupported_reason("Linux (Ubuntu 24.04)").is_none());
438    }
439
440    #[test]
441    fn script_uses_the_agent_command_path() {
442        assert!(update_script("1.2.3", "rigtop --agent").contains("command -v rigtop"));
443        let script = update_script("1.2.3", "/opt/my rig/rigtop --agent");
444        // The first word only; spaces in paths need `command -v`.
445        assert!(script.contains("bin='/opt/my'"));
446        let script = update_script("1.2.3", "~/bin/rigtop --agent");
447        assert!(script.contains(r#"bin="$HOME"/'bin/rigtop'"#));
448        assert!(
449            script.contains(
450                "'https://github.com/akivajp/rigtop/releases/download/v1.2.3/install.sh'"
451            )
452        );
453        assert!(script.contains("--version 'v1.2.3'"));
454    }
455
456    /// Runs the script with `sh` in a sandbox: a fake rigtop on PATH and a
457    /// fake curl whose "install.sh" prints the arguments it got.
458    #[cfg(unix)]
459    #[test]
460    fn script_installs_next_to_the_running_rigtop() {
461        use std::fs;
462        use std::os::unix::fs::PermissionsExt;
463
464        let tmp = tempfile::tempdir().unwrap();
465        let bin = tmp.path().join("bin");
466        let tools = tmp.path().join("tools");
467        fs::create_dir_all(&bin).unwrap();
468        fs::create_dir_all(&tools).unwrap();
469        let executable = |path: &std::path::Path, text: &str| {
470            fs::write(path, text).unwrap();
471            fs::set_permissions(path, fs::Permissions::from_mode(0o755)).unwrap();
472        };
473        executable(&bin.join("rigtop"), "#!/bin/sh\n");
474        // `curl ... URL -o FILE` writes a stand-in install.sh to FILE.
475        executable(
476            &tools.join("curl"),
477            "#!/bin/sh\nwhile [ $# -gt 1 ]; do [ \"$1\" = -o ] && out=$2; shift; done\n\
478             printf 'echo installed \"$@\"\\n' > \"$out\"\n",
479        );
480        let path = format!("{}:{}:/usr/bin:/bin", bin.display(), tools.display());
481        let run = |script: &str| {
482            run_script(
483                "env",
484                &[format!("PATH={path}"), "sh".to_owned(), "-s".to_owned()],
485                script,
486            )
487        };
488
489        let output = run(&update_script("1.2.3", "rigtop --agent")).unwrap();
490        assert_eq!(
491            output,
492            format!(
493                "installed --version v1.2.3 --bin-dir {} --tui-only",
494                bin.display()
495            )
496        );
497
498        // Not on PATH: ~/.local/bin (the install script's place) is found.
499        let home = tmp.path().join("home");
500        let local = home.join(".local/bin");
501        fs::create_dir_all(&local).unwrap();
502        executable(&local.join("rigtop"), "#!/bin/sh\n");
503        let output = run_script(
504            "env",
505            &[
506                format!("HOME={}", home.display()),
507                format!("PATH={}:/usr/bin:/bin", tools.display()),
508                "sh".to_owned(),
509                "-s".to_owned(),
510            ],
511            &update_script("1.2.3", "rigtop --agent"),
512        )
513        .unwrap();
514        assert!(
515            output.contains(&format!("--bin-dir {}", local.display())),
516            "{output}"
517        );
518
519        // A copy the user cannot replace is left alone, with a reason.
520        fs::set_permissions(&bin, fs::Permissions::from_mode(0o555)).unwrap();
521        let result = run(&update_script("1.2.3", "rigtop --agent"));
522        fs::set_permissions(&bin, fs::Permissions::from_mode(0o755)).unwrap();
523        // Root can write anywhere (e.g. in containers); then it installs.
524        if let Err(error) = result {
525            assert!(error.contains("is not writable"), "{error}");
526        }
527
528        // cargo's copy is cargo's to update.
529        let cargo = tmp.path().join(".cargo/bin");
530        fs::create_dir_all(&cargo).unwrap();
531        executable(&cargo.join("rigtop"), "#!/bin/sh\n");
532        let command = format!("{}/rigtop --agent", cargo.display());
533        let error = run(&update_script("1.2.3", &command)).unwrap_err();
534        assert!(
535            error.contains("cargo install rigtop --version 1.2.3"),
536            "{error}"
537        );
538
539        // Updating this machine's copy works the same, for rigtop-gui too.
540        executable(&bin.join("rigtop-gui"), "#!/bin/sh\n");
541        let output = run(&self_update_script("1.2.3", &bin.join("rigtop-gui"))).unwrap();
542        assert_eq!(
543            output,
544            format!("installed --version v1.2.3 --bin-dir {}", bin.display())
545        );
546
547        let error = run(&update_script("1.2.3", "/nowhere/rigtop --agent")).unwrap_err();
548        assert!(error.contains("not found"), "{error}");
549    }
550}