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