//! `midas update [...]`: bring the build machines' nodes to the midas //! in the owner's checkout, from the owner's own machine, one machine after //! another. //! //! The hub says only which machines there are and which nodes each runs. How //! to reach one is this machine's config, never the hub's: `MIDAS_MACHINES` in //! hub.env, an ssh target with the machine owner's login per machine //! (`deck=deck@192.168.1.50 vps=…`). A machine whose nodes are set up here is //! updated in place and needs no entry. The code is the checkout's HEAD //! (`--src`, `MIDAS_SRC`, or the checkout you are in), each machine builds it //! itself, and root is the owner's sudo: a hub that could push the code a node //! runs would decide it (0f35ae0 took that away, and this does not bring it //! back). //! //! Without a terminal — an agent running it — sudo asks in a dialog on this //! machine's screen: midas is its own askpass (`ASKPASS`), and a remote //! machine's password, asked for here, goes to its one `sudo -S` over ssh's //! stdin. Never into an argument list, never into the output the agent reads. //! //! Setup restarts a node, which cuts off whoever holds it, so a machine with a //! held node is left alone unless `--force`, or waited for with `--wait`: its //! nodes are drained so nobody new takes them, their holders are told why and //! finish as usual, and the update goes ahead once they let go. The nodes //! being updated are drained for the length of it, and undrained however it //! ends (Ctrl-C, or a kill, too). use std::collections::BTreeMap; use std::io::Write; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; use std::sync::atomic::{AtomicBool, Ordering}; use std::time::{Duration, Instant}; use anyhow::{anyhow, bail, Context, Result}; use serde_json::Value; use crate::bot::sh_quote; use crate::util::git; use crate::{cli, client, setup}; /// Set on the sudo we run, so that the midas sudo starts as its askpass /// shows the dialog instead of parsing a command line. pub const ASKPASS: &str = "MIDAS_ASKPASS"; /// What needs root, as one sudo: the binary at $1, the nodes after it. One /// sudo, so one password and no reliance on sudo's timestamp, which is keyed /// by the parent pid when there is no terminal. const PRIV: &str = r#"unset MIDAS_ASKPASS install -d -m 755 /var/lib/midas/bin && install -m 755 "$1" /var/lib/midas/bin/midas && shift && for n in "$@"; do /var/lib/midas/bin/midas setup "$n" || exit; done"#; /// On the machine: $1 says where sudo's password comes from (`tty`, or /// `stdin`'s first line), $2 is PRIV, the nodes follow. The build keeps off /// stdin, which is the password's. SteamOS builds in its `arch` distrobox, /// /usr being read-only. const REMOTE: &str = r#"set -euo pipefail how=$1 priv=$2; shift 2 cd ~/midas echo "building $(git log -1 --format='%h %s')" if grep -qi steamos /etc/os-release 2>/dev/null; then distrobox enter arch -- sh -c "cd ~/midas && cargo build --release --quiet --target x86_64-unknown-linux-musl" , pub reach: Reach, } /// `MIDAS_MACHINES`: `machine=ssh-target`, separated by spaces or commas. pub fn parse_targets(s: &str) -> Result> { s.split(|c: char| c.is_whitespace() || c == ',') .filter(|w| !w.is_empty()) .map(|w| match w.split_once('=') { Some((m, t)) if !m.is_empty() && !t.is_empty() => Ok((m.to_string(), t.to_string())), _ => bail!("MIDAS_MACHINES: {w:?} is not machine=ssh-target"), }) .collect() } /// The machines to update, sorted: the hub's nodes grouped by machine, each /// with how it is reached. `here` says whether a node is set up on this /// machine; `only`, if not empty, the machines named. pub fn plan(nodes: &[Value], targets: &BTreeMap, here: &dyn Fn(&str) -> bool, only: &[String]) -> Result> { let mut by: BTreeMap> = BTreeMap::new(); for n in nodes { let (Some(id), Some(m)) = (n["id"].as_str(), n["machine"].as_str().or(n["host"].as_str())) else { continue }; by.entry(m.to_string()).or_default().push(id.to_string()); } if let Some(m) = only.iter().find(|m| !by.contains_key(*m)) { bail!("no machine {m} at the hub (it knows {})", by.keys().cloned().collect::>().join(", ")); } Ok(by.into_iter() .filter(|(m, _)| only.is_empty() || only.contains(m)) .map(|(name, mut nodes)| { nodes.sort(); let reach = if nodes.iter().all(|n| here(n)) { Reach::Here } else { targets.get(&name).map_or(Reach::Unknown, |t| Reach::Ssh(t.clone())) }; Machine { name, nodes, reach } }) .collect()) } /// The nodes somebody holds, as `node by owner`. pub fn held(nodes: &[String], leases: &Value) -> Vec { nodes.iter() .filter_map(|n| leases[n]["owner"].as_str().filter(|o| !o.is_empty()).map(|o| format!("{n} by {o}"))) .collect() } enum Outcome { Updated, Skipped(String), Held(Vec), Failed(String), } /// Set by Ctrl-C or a kill: the wait for holders stops, and the drains are lifted. static STOP: AtomicBool = AtomicBool::new(false); extern "C" fn stop(_: libc::c_int) { STOP.store(true, Ordering::SeqCst); } pub fn update(only: &[String], force: bool, wait: bool, src: Option) -> Result { let src = source(src)?; let targets = parse_targets(&client::setting("MIDAS_MACHINES").unwrap_or_default())?; let state = client::state()?; let nodes = state["nodes"].as_array().cloned().unwrap_or_default(); let machines = plan(&nodes, &targets, &|n| setup::stored(n).is_some(), only)?; let head = git(&src, &["log", "-1", "--format=%h %s"])?; println!("midas at {head}, from {}", src.display()); // Ctrl-C ends the build or ssh in front, not us: the drains are lifted below. // A handler, not SIG_IGN, so the children start with the default again. // SAFETY: installing a handler that only stores to an atomic. unsafe { libc::signal(libc::SIGINT, stop as *const () as libc::sighandler_t); libc::signal(libc::SIGTERM, stop as *const () as libc::sighandler_t); } let mut outcomes = Vec::new(); for m in &machines { let outcome = match &m.reach { Reach::Unknown => Outcome::Skipped(format!("not set up here and not in MIDAS_MACHINES (hub.env), e.g. {}=user@host", m.name)), _ if STOP.load(Ordering::SeqCst) => Outcome::Skipped("stopped".into()), _ if !force && !wait && !held(&m.nodes, &state["leases"]).is_empty() => Outcome::Held(held(&m.nodes, &state["leases"])), reach => { println!("\n== {}: {} ({})", m.name, m.nodes.join(" "), match reach { Reach::Ssh(t) => format!("ssh {t}"), _ => "this machine".into() }); match one(&src, m, wait && !force, &targets) { Ok(()) => Outcome::Updated, Err(e) => { eprintln!("{}: {e:#}", m.name); Outcome::Failed(format!("{e:#}")) } } } }; outcomes.push((m.name.clone(), outcome)); } println!(); let (mut failed, mut waiting) = (false, false); for (name, o) in &outcomes { match o { Outcome::Updated => println!("updated {name}"), Outcome::Skipped(why) => println!("skipped {name}: {why}"), Outcome::Held(h) => { waiting = true; println!("held {name}: {} — --wait waits for them, --force cuts them off", h.join(", ")) } Outcome::Failed(e) => { failed = true; println!("failed {name}: {}", e.lines().next().unwrap_or("")) } } } if outcomes.iter().any(|(_, o)| matches!(o, Outcome::Updated)) { println!("each node runs the new build once its next heartbeat says so (midas status)"); } // This machine's own sessions: the skills and hooks the new build carries, // into the ~/.claude of whoever ran the update (not root's). let here_updated = machines.iter().zip(&outcomes) .any(|(m, (_, o))| m.reach == Reach::Here && matches!(o, Outcome::Updated)); if here_updated { if let Err(e) = run(Command::new("/var/lib/midas/bin/midas").args(["claude", "install"])) { eprintln!("the skills in ~/.claude were not brought up to date: {e:#}"); } } // 75 as `midas wait` uses it: nothing wrong, worth trying again later. Ok(if failed { 1 } else if waiting { 75 } else { 0 }) } /// Drained while alive; back in the pool when dropped, however that happens. struct Drained(Vec); impl Drop for Drained { fn drop(&mut self) { for n in &self.0 { if let Err(e) = cli::drain(n, None, &cli::owner()) { eprintln!("{n} is still drained ({e:#}): midas undrain {n}"); } } } } fn one(src: &Path, m: &Machine, wait: bool, targets: &BTreeMap) -> Result<()> { let why = format!("updating midas from {}", hostname()); let mut drained = Drained(Vec::new()); // A node drained already (retired, someone's next turn) stays as it was: // not drained again over its reason, and not put back in the pool after. let st = client::state()?; let before: Vec = st["nodes"].as_array().into_iter().flatten() .filter(|n| n["drained"].is_object()).filter_map(|n| n["id"].as_str().map(str::to_string)).collect(); for n in m.nodes.iter().filter(|n| !before.contains(n)) { cli::drain(n, Some(&why), &cli::owner())?; drained.0.push(n.clone()); } if wait { wait_for_holders(m)?; } match &m.reach { Reach::Here => here(src, &m.nodes), Reach::Ssh(t) => remote(src, t, &m.nodes, targets), Reach::Unknown => unreachable!("skipped before"), } } /// Until nobody holds the machine's nodes. They are drained already, so nobody /// new takes one; each holder hears why once, and finishes as usual. fn wait_for_holders(m: &Machine) -> Result<()> { let mut told = std::collections::BTreeSet::new(); let mut said = Instant::now() - Duration::from_secs(3600); loop { let st = client::state()?; let held = held(&m.nodes, &st["leases"]); if held.is_empty() { return Ok(()); } for n in m.nodes.iter().filter(|n| st["leases"][n.as_str()]["owner"].is_string()) { if told.insert(n.clone()) { let _ = client::post("/v1/say", &serde_json::json!({"owner": cli::owner(), "to": format!("@{n}"), "text": format!( "{n} is drained for a midas update of {}, which starts once you release it. Nothing changes for \ you meanwhile: keep it as long as you need. The update restarts the node, so copy anything \ you want from its /tmp before you release.", m.name)})); } } if said.elapsed() >= Duration::from_secs(300) { println!("waiting for {} (they have been told; Ctrl-C gives up and undrains)", held.join(", ")); said = Instant::now(); } for _ in 0..30 { if STOP.load(Ordering::SeqCst) { bail!("stopped while waiting for {}", held.join(", ")); } std::thread::sleep(Duration::from_secs(1)); } } } /// This machine: build the checkout where it is, for this platform. fn here(src: &Path, nodes: &[String]) -> Result<()> { println!("building"); let mut args = vec!["build", "--release", "--quiet"]; let mut rel = PathBuf::from("release/midas"); if !cfg!(target_os = "macos") { args.extend(["--target", "x86_64-unknown-linux-musl"]); rel = PathBuf::from("x86_64-unknown-linux-musl/release/midas"); } run(Command::new("cargo").args(&args).current_dir(src).stdin(Stdio::null()))?; let target = std::env::var_os("CARGO_TARGET_DIR").map(PathBuf::from).unwrap_or_else(|| PathBuf::from("target")); let bin = src.join(target).join(rel); let mut sudo = Command::new("sudo"); if !terminal() { let exe = std::env::current_exe().context("finding this midas, for sudo's dialog")?; let prompt = format!("midas update: your password for sudo on this machine. It installs midas and sets up {}.", nodes.join(", ")); sudo.args(["-A", "-p", &prompt.replace('%', "%%")]).env("SUDO_ASKPASS", exe).env(ASKPASS, "1"); } run(sudo.args(["sh", "-c", PRIV, "sh"]).arg(&bin).args(nodes))?; run(Command::new("/var/lib/midas/bin/midas").arg("--version")) } /// What a machine has: a checkout of midas, sudo without a password, and its /// architecture (`uname -m`). fn probe(target: &str) -> Result<(bool, bool, String)> { let out = output(Command::new("ssh").args(["-o", "BatchMode=yes", target, "test -d ~/midas/.git && echo checkout; sudo -n true 2>/dev/null && echo nopass; uname -m"]).stdin(Stdio::null())) .with_context(|| format!("reaching {target}"))?; let lines: Vec<&str> = out.lines().collect(); Ok((lines.contains(&"checkout"), lines.contains(&"nopass"), lines.last().unwrap_or(&"").to_string())) } /// Another machine: send it this checkout's commits, then build, install and /// set up there. One with no checkout — the hub's own, with no toolchain — /// gets the binary another machine built instead (`prebuilt`). fn remote(src: &Path, target: &str, nodes: &[String], targets: &BTreeMap) -> Result<()> { let (checkout, nopass, arch) = probe(target)?; if !checkout { return prebuilt(src, target, nodes, &arch, nopass, targets); } let theirs = output(Command::new("ssh").args([target, "git -C ~/midas rev-parse HEAD"]).stdin(Stdio::null())) .with_context(|| format!("{target} needs a checkout of midas in ~/midas"))?; let ours = git(src, &["rev-parse", "HEAD"])?; if theirs != ours { // Sent from here, as a bundle: the machine's own git key often works // only from a login with its ssh agent. let ancestor = Command::new("git").args(["merge-base", "--is-ancestor", &theirs, &ours]).current_dir(src) .status()?.success(); if !ancestor { bail!("its ~/midas is at {:.8}, which is not behind this checkout's {:.8}: update it by hand", theirs, ours); } let bundle = std::env::temp_dir().join(format!("midas-update-{}.bundle", std::process::id())); let sent = (|| { run(Command::new("git").args(["bundle", "create", "-q"]).arg(&bundle).args(["HEAD", &format!("^{theirs}")]).current_dir(src))?; run(Command::new("scp").arg("-q").arg(&bundle).arg(format!("{target}:/tmp/midas-update.bundle")).stdin(Stdio::null()))?; run(Command::new("ssh").args([target, "cd ~/midas && git fetch -q /tmp/midas-update.bundle HEAD && git merge -q --ff-only FETCH_HEAD; \ s=$?; rm -f /tmp/midas-update.bundle; exit $s"]).stdin(Stdio::null())) })(); let _ = std::fs::remove_file(&bundle); sent?; } if nopass { return run(Command::new("ssh").args([target, &remote_command("none", nodes)]).stdin(Stdio::null())); } if terminal() { return run(Command::new("ssh").args(["-t", target, &remote_command("tty", nodes)])); } let password = ask(&format!("midas update: the password of {target} for sudo there. It installs midas and sets up {}.", nodes.join(", ")))?; let mut child = Command::new("ssh").args([target, &remote_command("stdin", nodes)]).stdin(Stdio::piped()).spawn()?; { let mut stdin = child.stdin.take().expect("piped"); stdin.write_all(password.as_bytes())?; stdin.write_all(b"\n")?; } // closed: sudo reads one line, and the commands after it read nothing drop(password); let status = child.wait()?; if !status.success() { bail!("ssh {target}: {status}"); } Ok(()) } /// Run the setup on a machine with no checkout of its own, as deploy.sh does on /// the hub's: a binary for its architecture, built at this commit by another /// machine in MIDAS_MACHINES (the run goes in name order, so one updated in /// the same run counts), copied over and run from /tmp — not installed, so /// what the machine runs for itself (the hub's /usr/local/bin/midas) stays. fn prebuilt(src: &Path, target: &str, nodes: &[String], arch: &str, nopass: bool, targets: &BTreeMap) -> Result<()> { let ours = git(src, &["rev-parse", "HEAD"])?; let rel = format!("midas/target/{arch}-unknown-linux-musl/release/midas"); let from = targets.values().filter(|t| t.as_str() != target).find(|t| { output(Command::new("ssh").args(["-o", "BatchMode=yes", "-o", "ConnectTimeout=5", t, &format!("uname -m; git -C ~/midas rev-parse HEAD; test -x ~/{rel} && echo built")]).stdin(Stdio::null())) .is_ok_and(|o| o.lines().collect::>() == [arch, ours.as_str(), "built"]) }).cloned(); let Some(from) = from else { bail!("{target} has no checkout of midas, and no machine in MIDAS_MACHINES has {:.8} built for {arch}: \ update one of them first, or in the same run", ours); }; println!("{target} has no checkout: the {arch} binary {from} built"); let local = std::env::temp_dir().join(format!("midas-update-{}.bin", std::process::id())); let copied = (|| { run(Command::new("scp").arg("-q").arg(format!("{from}:{rel}")).arg(&local).stdin(Stdio::null()))?; run(Command::new("scp").arg("-q").arg(&local).arg(format!("{target}:/tmp/midas-update.bin")).stdin(Stdio::null())) })(); let _ = std::fs::remove_file(&local); copied?; // As root: set the nodes up with it, then leave nothing behind. let script = r#"install -m 755 "$1" /tmp/midas-update; rm -f "$1"; shift; s=0 for n in "$@"; do /tmp/midas-update setup "$n" || { s=$?; break; }; done /tmp/midas-update --version; rm -f /tmp/midas-update; exit $s"#; let mut words = vec![sh_quote(script), "sh".into(), "/tmp/midas-update.bin".into()]; words.extend(nodes.iter().map(|n| sh_quote(n))); let tail = words.join(" "); if nopass { return run(Command::new("ssh").args([target, &format!("sudo -n sh -c {tail}")]).stdin(Stdio::null())); } if terminal() { return run(Command::new("ssh").args(["-t", target, &format!("sudo sh -c {tail}")])); } let password = ask(&format!("midas update: the password of {target} for sudo there. It sets up {}.", nodes.join(", ")))?; let mut child = Command::new("ssh").args([target, &format!("sudo -S -p '' sh -c {tail}")]).stdin(Stdio::piped()).spawn()?; { let mut stdin = child.stdin.take().expect("piped"); stdin.write_all(password.as_bytes())?; stdin.write_all(b"\n")?; } drop(password); let status = child.wait()?; if !status.success() { bail!("ssh {target}: {status}"); } Ok(()) } /// REMOTE as one string for ssh, which joins its words and hands them to the /// login shell to split again. fn remote_command(how: &str, nodes: &[String]) -> String { let mut w = vec!["bash".to_string(), "-c".into(), sh_quote(REMOTE), "midas-update".into(), how.into(), sh_quote(PRIV)]; w.extend(nodes.iter().map(|n| sh_quote(n))); w.join(" ") } /// Ask the person at this machine for a password, in a dialog: macOS's own, /// else the SUDO_ASKPASS they set. The answer goes only to the caller. fn ask(prompt: &str) -> Result { let out = if cfg!(target_os = "macos") { Command::new("osascript") .args(["-e", "on run argv", "-e", r#"text returned of (display dialog (item 1 of argv) default answer "" with hidden answer with title "midas" with icon caution)"#, "-e", "end run", prompt]) .stderr(Stdio::null()) .output()? } else { let askpass = std::env::var("SUDO_ASKPASS").ok().filter(|a| !a.is_empty()) .ok_or_else(|| anyhow!("no terminal for sudo's password: run it in one, or set SUDO_ASKPASS to a dialog program"))?; Command::new(askpass).arg(prompt).output()? }; if !out.status.success() { bail!("no password given"); } let mut s = String::from_utf8(out.stdout).context("the password is not UTF-8")?; if s.ends_with('\n') { s.pop(); } Ok(s) } /// sudo's askpass: sudo runs this midas with `ASKPASS` set and its prompt as /// the one argument, and reads the password from stdout. pub fn askpass(prompt: &str) -> Result { println!("{}", ask(prompt)?); Ok(0) } /// The midas checkout to install: --src, MIDAS_SRC, or the one you are in. fn source(src: Option) -> Result { let home = std::env::var("HOME").unwrap_or_default(); let dir = src .or_else(|| client::setting("MIDAS_SRC").map(|s| match s.strip_prefix("~/") { Some(rest) => Path::new(&home).join(rest), None => PathBuf::from(s), })) .or_else(|| git(Path::new("."), &["rev-parse", "--show-toplevel"]).ok().map(PathBuf::from)) .ok_or_else(|| anyhow!("which midas checkout? --src, MIDAS_SRC in hub.env, or run it inside one"))?; let cargo = std::fs::read_to_string(dir.join("Cargo.toml")).unwrap_or_default(); if !cargo.lines().any(|l| l.replace(' ', "") == r#"name="midas""#) { bail!("{} is not a midas checkout (--src, or MIDAS_SRC in hub.env)", dir.display()); } Ok(dir) } fn terminal() -> bool { // SAFETY: isatty on a descriptor every process has. unsafe { libc::isatty(0) == 1 } } fn hostname() -> String { output(Command::new("hostname").arg("-s")).unwrap_or_else(|_| "?".into()) } fn output(c: &mut Command) -> Result { let out = c.stderr(Stdio::inherit()).output().with_context(|| format!("running {:?}", c.get_program()))?; if !out.status.success() { bail!("{:?} failed ({})", c.get_program(), out.status); } Ok(String::from_utf8_lossy(&out.stdout).trim().to_string()) } fn run(c: &mut Command) -> Result<()> { let status = c.status().with_context(|| format!("running {:?}", c.get_program()))?; if !status.success() { bail!("{:?} failed ({status})", c.get_program()); } Ok(()) } #[cfg(test)] mod tests { use super::*; use serde_json::json; fn hub() -> Vec { vec![ json!({"id": "mac-2", "machine": "mini"}), json!({"id": "deck-1", "machine": "deck"}), json!({"id": "mac-1", "machine": "mini"}), json!({"id": "vps-1", "host": "vps"}), ] } #[test] fn machines_are_grouped_and_reached_by_config() { let targets = parse_targets("deck=deck@192.168.1.50").unwrap(); let here = |n: &str| n.starts_with("mac-"); let p = plan(&hub(), &targets, &here, &[]).unwrap(); assert_eq!(p, vec![ Machine { name: "deck".into(), nodes: vec!["deck-1".into()], reach: Reach::Ssh("deck@192.168.1.50".into()) }, Machine { name: "mini".into(), nodes: vec!["mac-1".into(), "mac-2".into()], reach: Reach::Here }, Machine { name: "vps".into(), nodes: vec!["vps-1".into()], reach: Reach::Unknown }, ]); } #[test] fn a_machine_only_partly_here_is_not_updated_in_place() { let here = |n: &str| n == "mac-1"; let p = plan(&hub(), &BTreeMap::new(), &here, &["mini".into()]).unwrap(); assert_eq!(p.len(), 1); assert_eq!(p[0].reach, Reach::Unknown); } #[test] fn a_machine_the_hub_does_not_know_is_an_error() { assert!(plan(&hub(), &BTreeMap::new(), &|_| false, &["laptop".into()]).is_err()); } #[test] fn targets_parse_with_spaces_or_commas_and_refuse_junk() { let t = parse_targets(" deck=deck@10.0.0.2,vps=root@vps ").unwrap(); assert_eq!(t.get("vps").map(String::as_str), Some("root@vps")); assert_eq!(t.len(), 2); assert!(parse_targets("deck").is_err()); assert!(parse_targets("=x").is_err()); assert!(parse_targets("").unwrap().is_empty()); } #[test] fn the_remote_command_splits_back_into_its_words() { let nodes = vec!["deck-1".to_string(), "deck-2".to_string()]; let out = Command::new("sh").arg("-c").arg(format!("printf '%s\\0' {}", remote_command("stdin", &nodes))) .output().unwrap(); let words: Vec = String::from_utf8(out.stdout).unwrap() .split_terminator('\0').map(str::to_string).collect(); assert_eq!(words, ["bash", "-c", REMOTE, "midas-update", "stdin", PRIV, "deck-1", "deck-2"]); } #[test] fn held_names_each_holder() { let leases = json!({"mac-1": {"owner": "warmer"}, "mac-2": {}}); assert_eq!(held(&["mac-1".into(), "mac-2".into()], &leases), vec!["mac-1 by warmer"]); } }