garage44.eu/jeroen/midas

logclone: git clone https://garage44.eu/jeroen/midas.git

.. /src/check.rs

raw

//! `midas check`: is the workspace healthy, in one command. By default it
//! prints what is wrong — ✗ for a problem, · for something to know — and one
//! count per section of what is fine; `-v` prints every check with ✓.
//!
//! A problem is either **yours**, the caller's to fix where it runs (its ssh
//! config, its route to Forgejo, a hub it cannot reach), or **the owner's**: a
//! node's machine, the warmer, the midas the hub runs. Both are ✗ (the
//! session-start hook shows every ✗ line), the owner's labelled so; the exit
//! status counts only yours, so a script that gates on it is not stopped by a
//! Mac's full build directory it can do nothing about.
//!
//! Each check is here because its failure once went unnoticed: a guard loop
//! that had died (no heartbeat), a hub left on an older build (versions), an
//! ssh config left behind by a node change, a warmer failing every round.

use std::collections::BTreeMap;

use anyhow::Result;
use serde_json::Value;

use crate::client;
use crate::events;
use crate::registry;
use crate::sshcfg;

/// Below this the hub's disk is a problem: the line a node's /work is held to.
const HUB_LOW_DISK: u64 = 10_000_000_000;

/// Whose a node's problem is: its machine's owner, or the warmer they run.
const NODE_OWNER: &str = "for the node's owner";

#[derive(Default)]
struct Report {
    /// Every check printed, ✓ too.
    verbose: bool,
    /// Collect the problems instead of printing (the tests).
    quiet: bool,
    /// Problems the caller can act on: the exit status.
    yours: i32,
    /// Problems for an owner: printed and labelled, not counted.
    owners: i32,
    /// Every problem's text, whoever's.
    problems: Vec<String>,
    /// The section being checked: its name, what passed, what did not.
    section: String,
    ok: usize,
    lines: Vec<String>,
    /// Instead of "N ok": what the section counts (nodes, not checks).
    summary: Option<String>,
}

impl Report {
    fn begin(&mut self, name: &str) {
        self.end();
        self.section = name.to_string();
        if self.verbose && !self.quiet {
            println!("{name}");
        }
    }

    /// The section's line and what was wrong in it (all of it with -v, said as it came).
    fn end(&mut self) {
        if self.section.is_empty() {
            return;
        }
        if !self.verbose && !self.quiet {
            let count = self.summary.take().unwrap_or_else(|| match self.ok {
                0 if self.lines.is_empty() => "nothing to check".into(),
                0 => String::new(),
                n => format!("{n} ok"),
            });
            println!("{}{}{count}", self.section, if count.is_empty() { "" } else { ": " });
            for l in &self.lines {
                println!("{l}");
            }
        }
        self.section.clear();
        self.ok = 0;
        self.lines.clear();
        self.summary = None;
    }

    fn line(&mut self, l: String) {
        if self.quiet {
            return;
        }
        if self.verbose {
            println!("{l}");
        } else {
            self.lines.push(l);
        }
    }

    /// A check whose failure is the caller's to fix.
    fn check(&mut self, good: bool, what: &str) -> bool {
        if good {
            self.pass(what);
        } else {
            self.yours += 1;
            self.problems.push(what.to_string());
            self.line(format!("  ✗ {what}"));
        }
        good
    }

    /// A check whose failure is somebody else's: `whose` says whose.
    fn owner_check(&mut self, good: bool, what: &str, whose: &str) -> bool {
        if good {
            self.pass(what);
        } else {
            self.owners += 1;
            self.problems.push(what.to_string());
            self.line(format!("  ✗ {what} — {whose}"));
        }
        good
    }

    fn pass(&mut self, what: &str) {
        self.ok += 1;
        if self.verbose {
            self.line(format!("  ✓ {what}"));
        }
    }

    fn note(&mut self, what: &str) {
        self.line(format!("  · {what}"));
    }
}

pub fn check(verbose: bool) -> Result<i32> {
    let mut r = Report { verbose, ..Default::default() };

    r.begin("hub");
    let (hub_version, hub_recipe) = match client::get("/v1/health") {
        Ok(v) => {
            let version = v["version"].as_str().map(str::to_string);
            r.check(true, &format!("answers at {} (midas {})", client::hub_url(), version.as_deref().unwrap_or("?")));
            // Its state, git mirrors, LFS cache and sessions share one disk:
            // full, every take and every write of the state fails.
            if let Some(free) = v["disk_free"].as_u64() {
                r.owner_check(free >= HUB_LOW_DISK, &format!("{} GB free on the hub's state disk", free / 1_000_000_000),
                    "for the hub's owner");
            }
            (version, v["recipe"].as_str().map(str::to_string))
        }
        Err(e) => {
            r.check(false, &format!("{e:#}"));
            r.end();
            println!("\n1 problem — nothing else can be checked without the hub");
            return Ok(1);
        }
    };
    // Six copies of one binary run in four places; a stale one shows up only as
    // odd behaviour unless something compares them. This machine's is installed
    // by whoever deploys midas, not by the session asking.
    r.owner_check(hub_version.as_deref() == Some(crate::VERSION),
        &format!("this machine runs midas {}, the hub {}", crate::VERSION, hub_version.as_deref().unwrap_or("?")),
        "for whoever deploys midas (deploy.sh)");

    r.begin("nodes");
    let nodes = client::nodes()?;
    let mut fine = 0;
    let mut versions: BTreeMap<String, Vec<String>> = BTreeMap::new();
    let mut old_recipe: Vec<String> = Vec::new();
    for n in &nodes {
        let reading = n.get("reading").filter(|v| !v.is_null());
        let before = r.owners;
        node(&mut r, n, reading);
        let id = n["id"].as_str().unwrap_or("?").to_string();
        if let Some(rd) = reading {
            if hub_recipe.is_some() && rd["recipe"].as_str() != hub_recipe.as_deref() {
                old_recipe.push(id.clone());
            }
        }
        fine += usize::from(r.owners == before);
        if let Some(v) = reading.and_then(|rd| rd["version"].as_str()) {
            versions.entry(v.to_string()).or_default().push(id);
        }
    }
    // Said once, not per node. A node takes the hub's midas by itself once
    // free (`midas node update`); only a changed recipe — the container or VM,
    // the machine's firewall — needs its owner's sudo.
    let hub = hub_version.as_deref().unwrap_or("?");
    for (v, ids) in &versions {
        if v == hub {
            r.pass(&format!("{} run midas {v}, as the hub does", ids.join(", ")));
        } else {
            r.note(&format!("{} run midas {v}; they take the hub's {hub} when free", ids.join(", ")));
        }
    }
    if !old_recipe.is_empty() {
        r.owner_check(false, &format!("{} set up from an older recipe: sudo midas setup <node> on its machine, once \
            (midas update does every machine)", old_recipe.join(", ")), "for the machine's owner");
    }
    r.summary = Some(if fine == nodes.len() { format!("{fine} ok") } else { format!("{fine} of {} ok", nodes.len()) });

    r.begin("this machine");
    if let Some(home) = std::env::var("HOME").ok().filter(|_| client::key().is_some()) {
        let cfg = format!("{home}/.ssh/config");
        let want = sshcfg::block(&sshcfg::Opts::agent(None, None, true, None));
        match sshcfg::installed(&cfg) {
            Some(have) => r.check(have == want, if have == want { "ssh config's node block matches the nodes" }
                else { "ssh config's node block is out of date — midas ssh-config --flush --write ~/.ssh/config" }),
            None => r.check(false, "no midas node block in ~/.ssh/config — midas ssh-config --flush --write ~/.ssh/config"),
        };
        match crate::mcp::forgejo_version() {
            Ok(v) => r.check(true, &format!("Forgejo through the hub: {v}")),
            // Every repository at the hub, and hub.conf names no Forgejo: nothing to reach.
            Err(e) if format!("{e:#}").contains("has no Forgejo") => r.check(true, "no Forgejo: the hub hosts every repository"),
            Err(e) => r.check(false, &format!("Forgejo through the hub: {e:#}")),
        };
    } else {
        r.note("no hub key here: this is not an agent's machine");
    }

    r.begin("the last 24 hours");
    let evs = client::events(&events::Filter { since: chrono::Duration::hours(24), kinds: vec![], node: None, actor: None })?;
    let count = |k: &str| evs.iter().filter(|e| e["kind"] == k).count();
    let failed = count("warm_failed");
    let last = evs.iter().rev().find(|e| e["kind"] == "warm_done").and_then(|e| e["ts"].as_str());
    r.owner_check(failed == 0, &format!("warmer: {} warm(s) finished, {failed} failed{}", count("warm_done"),
        last.map(|t| format!(", last at {t}")).unwrap_or_default()), "for the workspace's owner");
    for (kind, label) in [("error", "errors"), ("sync_failed", "failed syncs"), ("oom_kill", "OOM kills"),
                          ("lease_lapsed", "lapsed leases"), ("lease_idle", "leases given back after 30 idle minutes"), ("ssh_blocked", "ssh refused to a non-holder")] {
        // Reported, not failed: each happens in normal use; a run of them is the
        // thing to look at.
        match count(kind) {
            0 => r.pass(&format!("{label}: 0")),
            n => r.note(&format!("{label}: {n} — midas log --since 24h --kind {kind}")),
        }
    }
    match evs.iter().filter(|e| e["kind"] == "guard" && e["stage"] == "stop").count() {
        0 => r.pass("GPU guard stops: 0"),
        n => r.note(&format!("GPU guard stops: {n} — midas log --since 24h --kind guard")),
    }
    r.end();

    println!();
    println!("{}", match (r.yours, r.owners) {
        (0, 0) => "all good".to_string(),
        (y, 0) => format!("{y} problem(s) for you"),
        (0, o) => format!("nothing for you to fix; {o} problem(s) for an owner"),
        (y, o) => format!("{y} problem(s) for you; {o} for an owner (not in the exit status)"),
    });
    Ok(r.yours.min(100))
}


fn node(r: &mut Report, n: &Value, reading: Option<&Value>) {
    let id = n["id"].as_str().unwrap_or("?");
    // Shut down on purpose while nobody uses it (sleep.rs): silence is no fault.
    if n["asleep"].is_object() {
        return;
    }
    let drained = n["drained"]["why"].as_str().map(|w| format!(" (drained: {w})")).unwrap_or_default();
    let Some(rd) = reading else {
        r.owner_check(false, &format!("{id}: no heartbeat ever{drained}"), NODE_OWNER);
        return;
    };
    let age = registry::now() - rd["at"].as_i64().unwrap_or(0);
    r.owner_check(age <= 180, &format!("{id}: heartbeat {age}s ago{drained}{}",
        if age > 180 { " — guard not running, or the node is down" } else { "" }), NODE_OWNER);
    if let Some(free) = rd["disk_free"].as_u64() {
        r.owner_check(free >= 10_000_000_000, &format!("{id}: {} GB free on /work", free / 1_000_000_000), NODE_OWNER);
    }
    if let Some(t) = rd["target_bytes"].as_u64() {
        // The warmer's own ceiling, which follows the disk: the node's guard trims
        // target/ back under it once no session is on it (node::trim_target).
        let c = crate::warm::ceiling(t, rd["disk_free"].as_u64());
        r.owner_check(t <= c, &format!("{id}: target/ {:.1} GB (ceiling {})", t as f64 / 1e9, c / 1_000_000_000),
            "trimmed by the node once no session is on it");
    }
    match rd["warm"].as_str().and_then(|w| w.get(..8)) {
        Some(w) => r.owner_check(true, &format!("{id}: warm at {w}"), NODE_OWNER),
        None => r.owner_check(false, &format!("{id}: not warm — the warmer has not finished it"), NODE_OWNER),
    };
    if let Some(g) = rd["gtt_pct"].as_f64() {
        r.owner_check(g < 80.0, &format!("{id}: GPU shared memory {g:.0} %"), NODE_OWNER);
        // Information, not a failure: the cap needs root on the machine.
        match rd["dmem_max"].as_str().filter(|m| m.contains("vram") && !m.ends_with(" max")) {
            Some(m) => r.pass(&format!("{id}: dedicated GPU memory capped ({m})")),
            None => r.note(&format!("{id}: dedicated GPU memory not capped — needs the dmem drop-in (docs/node.md), then sudo midas setup {id}")),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn a_nodes_problems_are_its_owners_and_not_in_the_exit_status() {
        let mut r = Report { quiet: true, ..Default::default() };
        // 12 GB free beside it: the ceiling is the floor, and 29.4 GB is over it.
        let rd = json!({"at": registry::now(), "disk_free": 12_000_000_000u64, "target_bytes": 29_400_000_000u64, "warm": "0123456789"});
        node(&mut r, &json!({"id": "mac-1"}), Some(&rd));
        assert_eq!((r.yours, r.owners), (0, 1));
        assert_eq!(r.problems, vec!["mac-1: target/ 29.4 GB (ceiling 24)".to_string()], "the text, without the label");
        // With 50 GB free the same target/ is within what the disk allows.
        let mut roomy = Report { quiet: true, ..Default::default() };
        node(&mut roomy, &json!({"id": "mac-1"}), Some(&json!({"at": registry::now(), "disk_free": 50_000_000_000u64, "target_bytes": 29_400_000_000u64, "warm": "0123456789"})));
        assert_eq!(roomy.owners, 0);
        r.check(false, "ssh config's node block is out of date");
        assert_eq!(r.yours, 1, "the caller's own problem is counted");
    }
}