OXYGENHUB

Coverage / crates/flow/src/update.rs 59.5%

166 of 279 lines run, 30 of 97 functions · run #189 on main · run missed

1
//! Runner updates, the runner's side (docs/jetstream.md §8.2, #85): check
2
//! a new `flow` build, stage it beside the running one, swap it in keeping
3
//! the old one as `flow.prev`, and have the running runner leave with
4
//! notice so its unit starts the new build. The new build proves itself by
5
//! reaching the hub; three failed starts, or ten minutes without the hub,
6
//! put `flow.prev` back.
7
8
use anyhow::{bail, Context, Result};
9
use serde::{Deserialize, Serialize};
10
use std::path::{Path, PathBuf};
11
use std::time::Duration;
12
13
/// The staged build, beside the installed one.
14
pub const NEW: &str = "flow.new";
15
/// The build an update replaced, kept to go back to.
16
pub const PREV: &str = "flow.prev";
17
/// In the runner's home: the update not yet proven.
18
const PENDING: &str = "update.json";
19
/// In the runner's home: every update and rollback, a JSON line each.
20
const LOG: &str = "updates.log";
21
/// In the runner's home: the running runner's process id.
22
const PID: &str = "runner.pid";
23
/// Starts of an unproven build after which the previous one comes back.
24
pub const MAX_STARTS: u32 = 3;
25
/// How long a new build has to reach the hub.
26
pub const PROVE_WITHIN: Duration = Duration::from_secs(10 * 60);
27
28
/// An update swapped in and not yet proven.
29
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
30
pub struct Pending {
31
    pub from: String,
32
    pub to: String,
33
    /// The installed binary the update replaced.
34
    pub exe: PathBuf,
35
    pub at_ms: u64,
36
    /// How long the running runner had to finish what it held.
37
    pub notice_secs: u64,
38
    /// Starts of the new build so far.
39
    pub starts: u32,
40
}
41
42
/// What [`install`] did, or would do.
43
#[derive(Debug, PartialEq, Eq)]
44
pub struct Installed {
45
    pub from: String,
46
    pub to: String,
47
    pub exe: PathBuf,
48
    /// The running runner told to leave, by process id.
49
    pub told: Option<u32>,
50
}
51
52
/// The version a `flow --version` line names: `flow 0.3.1 (build)` → `0.3.1`.
534×
pub fn parse_version(line: &str) -> Option<String> {
544×
    let v = line.trim().strip_prefix("flow ")?.split_whitespace().next()?;
558×
    v.split('.').all(|p| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit())).then(|| v.to_string())
564×
}
57
58
/// Whether version `a` is older than `b`, part by part.
593×
pub fn older(a: &str, b: &str) -> bool {
6017×
    let parts = |v: &str| v.split('.').map(|p| p.parse::<u64>().unwrap_or(0)).collect::<Vec<_>>();
613×
    parts(a) < parts(b)
623×
}
63
64
/// The ELF machine number of this build's architecture.
652×
fn machine_here() -> Option<u16> {
662×
    Some(match std::env::consts::ARCH {
672×
        "x86_64" => 62,
680×
        "aarch64" => 183,
690×
        "riscv64" => 243,
700×
        _ => return None,
71
    })
722×
}
73
74
/// Refuse a file that is not a 64-bit little-endian ELF executable for this
75
/// machine: a build for another target would not start, and the rollback
76
/// would only notice after three tries.
773×
pub fn check_target(bytes: &[u8]) -> Result<()> {
783×
    if bytes.len() < 20 || &bytes[..4] != b"\x7fELF" {
791×
        bail!("not an ELF executable");
802×
    }
812×
    if bytes[4] != 2 || bytes[5] != 1 {
820×
        bail!("not a 64-bit little-endian build");
832×
    }
842×
    let machine = u16::from_le_bytes([bytes[18], bytes[19]]);
852×
    match machine_here() {
862×
        Some(m) if m == machine => Ok(()),
871×
        Some(_) => bail!("a build for another machine (ELF machine {machine}); this runner is {}", std::env::consts::ARCH),
880×
        None => bail!("updates are not supported on {}", std::env::consts::ARCH),
89
    }
903×
}
91
92
/// Run `file args…` with a time limit, returning its standard output.
930×
fn run(file: &Path, args: &[&str], limit: Duration) -> Result<String> {
940×
    let mut child = std::process::Command::new(file)
950×
        .args(args)
960×
        .stdin(std::process::Stdio::null())
970×
        .stdout(std::process::Stdio::piped())
980×
        .stderr(std::process::Stdio::piped())
990×
        .spawn()
1000×
        .with_context(|| format!("starting {}", file.display()))?;
1010×
    let start = std::time::Instant::now();
102
    loop {
1030×
        if child.try_wait()?.is_some() {
1040×
            break;
1050×
        }
1060×
        if start.elapsed() > limit {
1070×
            let _ = child.kill();
1080×
            let _ = child.wait();
1090×
            bail!("`{} {}` did not finish within {} s", file.display(), args.join(" "), limit.as_secs());
1100×
        }
1110×
        std::thread::sleep(Duration::from_millis(50));
112
    }
1130×
    let out = child.wait_with_output()?;
1140×
    if !out.status.success() {
1150×
        bail!("`{} {}` failed ({}): {}", file.display(), args.join(" "), out.status, String::from_utf8_lossy(&out.stderr).trim());
1160×
    }
1170×
    Ok(String::from_utf8_lossy(&out.stdout).into_owned())
1180×
}
119
120
/// Check a build as the runner would run it: this machine's target, it
121
/// starts and names its version, and it finds the tiers this home offers.
122
/// Returns its version.
1230×
pub fn check(file: &Path, home: &Path) -> Result<String> {
1240×
    let mut head = vec![0u8; 64];
1250×
    let n = std::io::Read::read(&mut std::fs::File::open(file).with_context(|| format!("opening {}", file.display()))?, &mut head)?;
1260×
    check_target(&head[..n])?;
1270×
    let limit = Duration::from_secs(30);
1280×
    let line = run(file, &["--version"], limit)?;
1290×
    let version = parse_version(&line).with_context(|| format!("{} does not say it is flow: {:?}", file.display(), line.trim()))?;
1300×
    let home_s = home.to_string_lossy();
1310×
    let tiers = run(file, &["--home", &home_s, "tiers"], limit)?;
1320×
    if !tiers.lines().any(|l| l.ends_with(": available")) {
1330×
        bail!("flow {version} finds no tier it can run here:\n{}", tiers.trim());
1340×
    }
1350×
    Ok(version)
1360×
}
137
1382×
fn now_ms() -> u64 {
1392×
    std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0)
1402×
}
141
1422×
fn log(home: &Path, event: &str, from: &str, to: &str, why: &str) {
143
    use std::io::Write;
1442×
    let line = serde_json::json!({"at_ms": now_ms(), "event": event, "from": from, "to": to, "why": why});
1452×
    if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(home.join(LOG)) {
1462×
        let _ = writeln!(f, "{line}");
1472×
    }
1482×
}
149
150
/// The update not yet proven, if any.
1519×
pub fn pending(home: &Path) -> Option<Pending> {
1529×
    serde_json::from_slice(&std::fs::read(home.join(PENDING)).ok()?).ok()
1539×
}
154
1555×
fn save(home: &Path, p: &Pending) -> Result<()> {
1565×
    let tmp = home.join(format!("{PENDING}.tmp"));
1575×
    std::fs::write(&tmp, serde_json::to_vec_pretty(p)?)?;
1585×
    std::fs::rename(&tmp, home.join(PENDING))?;
1595×
    Ok(())
1605×
}
161
162
/// Put `staged` in place of `exe`, keeping `exe` as [`PREV`] beside it.
163
/// `exe` is never missing: it is copied aside, then replaced in one rename.
1641×
pub fn swap(exe: &Path, staged: &Path) -> Result<()> {
1651×
    let prev = exe.with_file_name(PREV);
1661×
    let _ = std::fs::remove_file(&prev);
1671×
    if std::fs::hard_link(exe, &prev).is_err() {
1680×
        std::fs::copy(exe, &prev).with_context(|| format!("keeping {} as {}", exe.display(), prev.display()))?;
1691×
    }
1701×
    std::fs::rename(staged, exe).with_context(|| format!("putting {} in place of {}", staged.display(), exe.display()))?;
1711×
    Ok(())
1721×
}
173
174
/// Put [`PREV`] back in place of `exe`.
1751×
pub fn restore(exe: &Path) -> Result<()> {
1761×
    let prev = exe.with_file_name(PREV);
1771×
    if !prev.is_file() {
1780×
        bail!("{} is not there to go back to", prev.display());
1791×
    }
1801×
    std::fs::rename(&prev, exe).with_context(|| format!("putting {} back", prev.display()))?;
1811×
    Ok(())
1821×
}
183
184
/// Check `file`, stage it beside `exe`, and unless `dry_run` swap it in and
185
/// tell the running runner (if any) to leave within `notice`, finishing
186
/// what fits and handing back the rest, so its unit starts the new build.
1870×
pub fn install(home: &crate::home::Home, exe: &Path, file: &Path, notice: Duration, dry_run: bool, allow_older: bool) -> Result<Installed> {
1880×
    if !cfg!(unix) {
1890×
        bail!("runners update themselves on Linux only, so far");
1900×
    }
1910×
    if home.config.runner.as_ref().and_then(|r| r.update.as_ref()).is_some_and(|u| !u.allow) {
1920×
        bail!("flow.toml says [runner.update] allow = false: this runner takes no updates");
1930×
    }
1940×
    if let Some(p) = pending(&home.root) {
1950×
        bail!("the update from {} to {} is not proven yet; wait for it (or for its rollback)", p.from, p.to);
1960×
    }
1970×
    let from = env!("CARGO_PKG_VERSION").to_string();
1980×
    let staged = exe.with_file_name(NEW);
1990×
    let _ = std::fs::remove_file(&staged);
2000×
    std::fs::copy(file, &staged).with_context(|| format!("staging {} as {}", file.display(), staged.display()))?;
2010×
    crate::portable::set_mode(&staged, 0o755)?;
2020×
    let checked = check(&staged, &home.root).and_then(|to| {
2030×
        if older(&to, &from) && !allow_older {
2040×
            bail!("flow {to} is older than this runner's {from} (--allow-older to go back)");
2050×
        }
2060×
        Ok(to)
2070×
    });
2080×
    let to = match checked {
2090×
        Ok(v) => v,
2100×
        Err(e) => {
2110×
            let _ = std::fs::remove_file(&staged);
2120×
            return Err(e);
213
        }
214
    };
2150×
    if dry_run {
2160×
        let _ = std::fs::remove_file(&staged);
2170×
        return Ok(Installed { from, to, exe: exe.to_path_buf(), told: None });
2180×
    }
2190×
    swap(exe, &staged)?;
2200×
    let p =
2210×
        Pending { from: from.clone(), to: to.clone(), exe: exe.to_path_buf(), at_ms: now_ms(), notice_secs: notice.as_secs(), starts: 0 };
2220×
    save(&home.root, &p)?;
2230×
    log(&home.root, "installed", &from, &to, "flow runner update --from");
2240×
    let told = running(&home.root).filter(|pid| tell(*pid));
2250×
    Ok(Installed { from, to, exe: exe.to_path_buf(), told })
2260×
}
227
228
/// Ask runner `pid` to leave for the new build (SIGUSR1).
229
#[cfg(unix)]
2300×
fn tell(pid: u32) -> bool {
2310×
    unsafe { libc::kill(pid as libc::pid_t, libc::SIGUSR1) == 0 }
2320×
}
233
234
#[cfg(not(unix))]
235
fn tell(_pid: u32) -> bool {
236
    false
237
}
238
239
/// The running runner's process id, from its pid file, if that process is
240
/// still a `flow runner`: a stale file's pid may be another program's now,
241
/// and SIGUSR1 would end it. Builds before #85 write no pid file (and do
242
/// not listen for SIGUSR1), so they are never told.
2431×
fn running(home: &Path) -> Option<u32> {
2441×
    let pid: u32 = std::fs::read_to_string(home.join(PID)).ok()?.trim().parse().ok()?;
2451×
    let cmdline = std::fs::read(format!("/proc/{pid}/cmdline")).ok()?;
2461×
    is_runner(&cmdline).then_some(pid)
2471×
}
248
249
/// Whether a NUL-separated command line is `flow … runner` with no subcommand.
2506×
fn is_runner(cmdline: &[u8]) -> bool {
251230×
    let args: Vec<&[u8]> = cmdline.split(|b| *b == 0).filter(|a| !a.is_empty()).collect();
2526×
    let Some((argv0, rest)) = args.split_first() else { return false };
25339×
    let name = argv0.rsplit(|b| *b == b'/').next().unwrap_or(argv0);
2545×
    name.starts_with(b"flow") && rest.last() == Some(&&b"runner"[..])
2556×
}
256
257
/// Note this process as the home's runner, for `flow runner update` to tell.
2580×
pub fn note_runner(home: &Path) {
2590×
    let _ = std::fs::write(home.join(PID), std::process::id().to_string());
2600×
}
261
262
/// The runner stopped: forget its pid.
2630×
pub fn forget_runner(home: &Path) {
2640×
    if std::fs::read_to_string(home.join(PID)).is_ok_and(|p| p.trim() == std::process::id().to_string()) {
2650×
        let _ = std::fs::remove_file(home.join(PID));
2660×
    }
2670×
}
268
269
/// What a runner starting up should do about an update.
270
#[derive(Debug, PartialEq, Eq)]
271
pub enum Start {
272
    /// No update waits to be proven.
273
    Settled,
274
    /// The new build is on trial: prove it within [`PROVE_WITHIN`].
275
    Trial(Pending),
276
    /// It failed too often; the previous build is back and should be run.
277
    RolledBack(Pending),
278
}
279
280
/// Count this start of an unproven build; after [`MAX_STARTS`], put the
281
/// previous build back.
2826×
pub fn on_start(home: &Path) -> Result<Start> {
2836×
    let Some(mut p) = pending(home) else { return Ok(Start::Settled) };
2844×
    p.starts += 1;
2854×
    if p.starts > MAX_STARTS {
2861×
        roll_back(home, &p, &format!("{MAX_STARTS} starts without reaching the hub"))?;
2871×
        return Ok(Start::RolledBack(p));
2883×
    }
2893×
    save(home, &p)?;
2903×
    Ok(Start::Trial(p))
2916×
}
292
293
/// In the runner's home: what to tell the hub once it answers.
294
const NOTE: &str = "update.note";
295
296
/// Keep `note` to tell the hub (a proof, a rollback) once it answers.
2972×
fn note(home: &Path, note: &str) {
2982×
    let _ = std::fs::write(home.join(NOTE), note);
2992×
}
300
301
/// What there is to tell the hub, once.
3020×
pub fn take_note(home: &Path) -> Option<String> {
3030×
    let n = std::fs::read_to_string(home.join(NOTE)).ok()?;
3040×
    let _ = std::fs::remove_file(home.join(NOTE));
3050×
    Some(n).filter(|n| !n.trim().is_empty())
3060×
}
307
308
/// The new build reached the hub: it stays.
3091×
pub fn proven(home: &Path) {
3101×
    if let Some(p) = pending(home) {
3111×
        let _ = std::fs::remove_file(home.join(PENDING));
3121×
        log(home, "proven", &p.from, &p.to, "reached the hub");
3131×
        note(home, &format!("runs flow {} (was {}); proven", p.to, p.from));
3141×
        eprintln!("flow runner: flow {} proven (it reached the hub); flow {} stays as {PREV}", p.to, p.from);
3151×
    }
3161×
}
317
318
/// Put the previous build back and forget the update.
3191×
pub fn roll_back(home: &Path, p: &Pending, why: &str) -> Result<()> {
3201×
    restore(&p.exe)?;
3211×
    let _ = std::fs::remove_file(home.join(PENDING));
3221×
    log(home, "rolled back", &p.to, &p.from, why);
3231×
    note(home, &format!("rolled back from flow {} to {}: {why}", p.to, p.from));
3241×
    eprintln!("flow runner: rolled back from flow {} to {} ({why})", p.to, p.from);
3251×
    Ok(())
3261×
}
327
328
#[cfg(test)]
329
mod tests {
330
    use super::*;
331
332
    #[test]
3331×
    fn versions_are_read_and_compared() {
3341×
        assert_eq!(parse_version("flow 0.3.1 (local build)\n").as_deref(), Some("0.3.1"));
3351×
        assert_eq!(parse_version("flow 0.10.0"), Some("0.10.0".into()));
3361×
        assert_eq!(parse_version("oxy 0.6.0"), None);
3371×
        assert_eq!(parse_version("flow banana"), None);
3381×
        assert!(older("0.3.1", "0.10.0"), "by number, not by text");
3391×
        assert!(!older("0.3.1", "0.3.1"));
3401×
        assert!(older("0.3", "0.3.1"));
3411×
    }
342
343
    #[test]
3441×
    fn only_a_build_for_this_machine_passes() {
3451×
        let me = std::fs::read(std::env::current_exe().unwrap()).unwrap();
3461×
        check_target(&me[..64]).unwrap();
3471×
        assert!(check_target(b"#!/bin/sh\necho flow 9.9.9\n").unwrap_err().to_string().contains("not an ELF"));
3481×
        let mut other = me[..64].to_vec();
3491×
        other[18..20].copy_from_slice(&(if std::env::consts::ARCH == "riscv64" { 62u16 } else { 243u16 }).to_le_bytes());
3501×
        assert!(check_target(&other).unwrap_err().to_string().contains("another machine"));
3511×
    }
352
353
    #[test]
3541×
    fn a_swap_keeps_the_old_build_and_three_failed_starts_bring_it_back() {
3551×
        let dir = tempfile::tempdir().unwrap();
3561×
        let (bin, home) = (dir.path().join("bin"), dir.path().join("home"));
3571×
        std::fs::create_dir_all(&bin).unwrap();
3581×
        std::fs::create_dir_all(&home).unwrap();
3591×
        let exe = bin.join("flow");
3601×
        std::fs::write(&exe, "old").unwrap();
3611×
        std::fs::write(bin.join(NEW), "new").unwrap();
3621×
        swap(&exe, &bin.join(NEW)).unwrap();
3631×
        assert_eq!(std::fs::read_to_string(&exe).unwrap(), "new");
3641×
        assert_eq!(std::fs::read_to_string(bin.join(PREV)).unwrap(), "old");
3651×
        assert!(!bin.join(NEW).exists());
366
3671×
        assert_eq!(on_start(&home).unwrap(), Start::Settled, "no update, nothing to do");
3681×
        let p = Pending { from: "0.3.1".into(), to: "0.3.2".into(), exe: exe.clone(), at_ms: 1, notice_secs: 600, starts: 0 };
3691×
        save(&home, &p).unwrap();
3703×
        for n in 1..=MAX_STARTS {
3713×
            assert_eq!(on_start(&home).unwrap(), Start::Trial(Pending { starts: n, ..p.clone() }));
372
        }
3731×
        assert!(matches!(on_start(&home).unwrap(), Start::RolledBack(_)));
3741×
        assert_eq!(std::fs::read_to_string(&exe).unwrap(), "old", "the previous build is back");
3751×
        assert!(pending(&home).is_none());
3761×
        let log = std::fs::read_to_string(home.join(LOG)).unwrap();
3771×
        assert!(log.contains("rolled back") && log.contains("0.3.2"), "{log}");
3781×
    }
379
380
    #[test]
3811×
    fn only_a_running_runner_is_told() {
3821×
        assert!(is_runner(b"/usr/local/bin/flow\0runner\0"));
3831×
        assert!(is_runner(b"flow\0--home\0/srv/flow\0runner\0"));
3841×
        assert!(!is_runner(b"flow\0runner\0update\0--from\0x\0"), "not the update command itself");
3851×
        assert!(!is_runner(b"/usr/bin/vim\0runner\0"));
3861×
        assert!(!is_runner(b""));
3871×
        let dir = tempfile::tempdir().unwrap();
3881×
        std::fs::write(dir.path().join(PID), std::process::id().to_string()).unwrap();
3891×
        assert_eq!(running(dir.path()), None, "this test is not a flow runner");
3901×
    }
391
392
    #[test]
3931×
    fn a_proven_build_stays() {
3941×
        let dir = tempfile::tempdir().unwrap();
3951×
        let exe = dir.path().join("flow");
3961×
        std::fs::write(&exe, "new").unwrap();
3971×
        let p = Pending { from: "0.3.1".into(), to: "0.3.2".into(), exe: exe.clone(), at_ms: 1, notice_secs: 0, starts: 1 };
3981×
        save(dir.path(), &p).unwrap();
3991×
        proven(dir.path());
4001×
        assert!(pending(dir.path()).is_none());
4011×
        assert_eq!(on_start(dir.path()).unwrap(), Start::Settled);
4021×
        assert!(std::fs::read_to_string(dir.path().join(LOG)).unwrap().contains("proven"));
4031×
    }
404
}