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