garage44.eu/jeroen/midas

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

.. /src/warm.rs

raw

//! `midas hub warm`: keep every node's build directory warm at the default
//! branch, so taking a node costs the delta from it and not a cold build.
//!
//! What "warm" means is the workspace's own: the build commands in `hub.conf`'s
//! `warm` section, run in the checkout of its first repository. It is the
//! hub's job: it reads
//! what each node is warm for from the node's heartbeat, takes its lease like
//! any agent (so it never touches a node somebody holds, and yields to anybody
//! queued), runs the steps over ssh with the hub's operator key, and logs each
//! step with its duration.
//!
//! **Never cold, not always current.** A full warm is tens of minutes and
//! the branch moves several times a day; re-warming on every commit never converges.
//! A node warm at last week's commit is nearly as good — the ~560 dependencies
//! are the same and only the workspace crates recompile, which is the work an
//! agent's first build pays anyway (measured on a Rust workspace). So a node is warmed when it is cold (no
//! marker), over its 24 GB ceiling, or its marker is over three days old.

use std::fs::OpenOptions;
use std::os::unix::io::AsRawFd;
use std::process::{Command, Stdio};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};

use anyhow::{bail, Context, Result};
use serde_json::json;

use crate::events;
use crate::registry::{self, Locked};

const OWNER: &str = "warmer";
const TTL: i64 = 5400;
/// The least target/ is allowed to grow to, whatever the disk, and the most.
const CEILING_FLOOR: u64 = 24_000_000_000;
const CEILING_CAP: u64 = 80_000_000_000;
/// What the warmer keeps free on /work for everything else a node does.
pub(crate) const DISK_RESERVE: u64 = 20_000_000_000;
const STALE_S: u64 = 3 * 86400;

/// How big target/ may grow on a node, from its size now and what is free on
/// /work beside it: as far as leaves [`DISK_RESERVE`] free, within the floor
/// and the cap. One fixed 24 GB had the Macs, with 80 GB and more free, throw
/// away their whole target/ ten times in a week and spend 30 minutes each
/// rebuilding it (2026-10-28) — more node time than every landing gate.
pub fn ceiling(target: u64, free: Option<u64>) -> u64 {
    free.map_or(CEILING_FLOOR, |f| (target + f).saturating_sub(DISK_RESERVE).clamp(CEILING_FLOOR, CEILING_CAP))
}

/// A node's ceiling from its last heartbeat.
fn ceiling_of(r: &serde_json::Value) -> u64 {
    ceiling(r["target_bytes"].as_u64().unwrap_or(0), r["disk_free"].as_u64())
}
pub(crate) const SSH_CONFIG: &str = "/srv/midas/.ssh/config";
/// Where a node's checkout records what it was warmed at: beside the checkout,
/// not in it, so nothing of midas shows up in the repository's working tree.
const MARK: &str = "/work/.warm";
const MARK_OPTIONAL: &str = "/work/.warm-optional";

pub fn warm(only: Option<&str>, dry_run: bool) -> Result<i32> {
    // One warm at a time, however it was started.
    let lock = OpenOptions::new().create(true).append(true).open("/srv/midas/warm.lock")
        .or_else(|_| OpenOptions::new().create(true).append(true).open("/tmp/midas-warm.lock"))?;
    // SAFETY: flock on a descriptor we own.
    if unsafe { libc::flock(lock.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } != 0 {
        eprintln!("midas warm: another warm is running");
        return Ok(0);
    }

    let conf = crate::conf::hub();
    let Some(repo) = conf.repos.first().map(|r| crate::mirror::repo_name(r)).transpose()? else {
        bail!("no repository in hub.conf");
    };
    crate::mirror::refresh(&repo).context("refreshing the mirror")?;
    let main = git_mirror(&repo, &["rev-parse", &format!("refs/heads/{}", conf.warm.branch)])?;

    let reg = Locked::open()?;
    let candidates: Vec<(String, String)> = reg.nodes().iter()
        .filter(|s| s["enabled"].as_bool().unwrap_or(true) && !s["drained"].is_object())
        .filter_map(|s| s["id"].as_str().map(str::to_string))
        .filter(|id| only.is_none_or(|o| o == id))
        .filter(|id| !reg.leases().contains_key(id))
        .filter_map(|id| why_warm(&id).map(|w| (id, w)))
        .collect();
    drop(reg);

    if candidates.is_empty() {
        eprintln!("midas warm: every free node is warm, within what its disk allows, and fresh");
        return Ok(0);
    }
    for (node, why) in candidates {
        eprintln!("midas warm: {node} — {why}");
        if dry_run {
            continue;
        }
        if let Err(e) = warm_one(&node, &main, &why, &conf.warm) {
            events::emit("warm_failed", json!({"node": node, "actor": OWNER, "what": format!("{e:#}")}));
            eprintln!("midas warm: {node}: {e:#}");
        }
    }
    Ok(0)
}

/// Why this node needs warming, from its last heartbeat — or None.
fn why_warm(node: &str) -> Option<String> {
    let r = registry::reading(node)?;
    if r["warm"].as_str().is_none_or(|w| w.is_empty()) {
        return Some("cold: no warm marker".into());
    }
    // `warm_extra` from a node on a midas older than 2026-10-13.
    let optional = r["warm_optional"].as_str().or(r["warm_extra"].as_str());
    if optional.is_none_or(|w| w.is_empty()) {
        return Some("the optional steps have not been run".into());
    }
    if let Some(t) = r["target_bytes"].as_u64().filter(|t| *t > ceiling_of(&r)) {
        return Some(format!("target/ is {} GB, over the {} GB its disk allows", t / 1_000_000_000, ceiling_of(&r) / 1_000_000_000));
    }
    if let Some(a) = r["warm_age_s"].as_u64().filter(|a| *a > STALE_S) {
        return Some(format!("warm marker is {} days old", a / 86400));
    }
    None
}

fn warm_one(node: &str, main: &str, why: &str, warm: &crate::conf::Warm) -> Result<()> {
    let machine = registry::nodes().into_iter().find(|n| n["id"] == node)
        .and_then(|n| n["machine"].as_str().map(str::to_string)).unwrap_or_default();
    let w = &warm.for_machine(&machine);
    // Taken like any agent takes one, so the queue's fairness applies: somebody
    // waiting for this host goes first, and the warmer simply does not get it.
    {
        let mut reg = Locked::open()?;
        reg.reap();
        if reg.leases().contains_key(node) {
            bail!("taken before the warm started");
        }
        let this = reg.node(node).cloned().unwrap_or_default();
        if reg.waiters().values().any(|w| registry::wants(w, &this)) {
            eprintln!("midas warm: {node} — somebody is queued for it; leaving it to them");
            return Ok(());
        }
        let t = registry::now();
        reg.leases_mut().insert(node.into(), json!({
            "owner": OWNER, "claimed_at": t, "renewed_at": t, "ttl": TTL, "branch": warm.branch,
            "purpose": format!("warming to {}", &main[..8]), "last_active": t, "mode": "build",
        }));
        // Its checkout goes to main: no session's run is sent back to it for
        // its tree (`registry::prefer_last`).
        if let Some(m) = reg.state["last_node"].as_object_mut() {
            m.insert(OWNER.into(), json!({"node": node, "at": t}));
        }
        reg.mark();
        reg.commit()?;
    }
    events::emit("warm_start", json!({"node": node, "actor": OWNER, "to": main, "why": why}));
    let started = Instant::now();

    // A warm runs longer than a lease; renew it every five minutes so the node
    // never looks free under a running build.
    let stop = Arc::new(AtomicBool::new(false));
    let beat = {
        let (stop, node) = (stop.clone(), node.to_string());
        std::thread::spawn(move || {
            while !stop.load(Ordering::Relaxed) {
                for _ in 0..300 {
                    if stop.load(Ordering::Relaxed) {
                        return;
                    }
                    std::thread::sleep(Duration::from_secs(1));
                }
                if let Ok(mut reg) = Locked::open() {
                    if let Some(l) = reg.leases_mut().get_mut(&node) {
                        l["renewed_at"] = json!(registry::now());
                    }
                    reg.mark();
                    let _ = reg.commit();
                }
            }
        })
    };

    let result = (|| -> Result<usize> {
        // Over what its disk allows: the cheapest to lose first — incremental state, then
        // whichever profile or target triple was built longest ago (a deploy's, a
        // one-off's), and the whole of target/ only when that is not enough.
        // Once: what target/ drops is freed on /work, so their sum, and the ceiling, stay put.
        let limit = registry::reading(node).map_or(CEILING_FLOOR, |r| ceiling_of(&r));
        let over = |node: &str| -> Result<bool> { Ok(target_bytes(node)? > limit) };
        if over(node)? {
            step(node, "drop incremental/", "rm -rf target/debug/incremental")?;
            for _ in 0..8 {
                if !over(node)? {
                    break;
                }
                let oldest = ssh(node, "ls -1dtr target/*/ 2>/dev/null | grep -v '^target/debug/$' | head -1")?;
                let Some(d) = oldest.lines().next().map(str::trim).filter(|d| d.starts_with("target/") && !d.contains("..")) else { break };
                step(node, &format!("drop {d}"), &format!("rm -rf {}", shell_quote(d)))?;
            }
            if over(node)? {
                step(node, "drop target/", "rm -rf target")?;
            }
        }
        step(node, &format!("checkout {}", warm.branch), &format!(
            "git fetch --quiet origin && git checkout --quiet --force --detach {main} \
             && git reset --quiet --hard {main} && git clean -qfdx -e /target -e node_modules -e '/.midas*'"))?;
        let mut done = 0;
        for s in &w.steps {
            if step(node, s, &format!("nice -n 15 {s}")).is_err() {
                break; // main may be red; leave it warm as far as it got
            }
            done += 1;
        }
        if done == w.steps.len() {
            ssh(node, &format!("echo {main} > {MARK}"))?;
            for cmd in &w.optional {
                let _ = step_as(node, cmd, &format!("nice -n 15 bash -c {}", shell_quote(cmd)), true);
            }
            // Written whether or not they passed: a node that cannot run one
            // (a toolchain it lacks) must not be re-warmed for ever on that account.
            ssh(node, &format!("echo {main} > {MARK_OPTIONAL}"))?;
        }
        Ok(done)
    })();

    stop.store(true, Ordering::Relaxed);
    let _ = beat.join();
    {
        let mut reg = Locked::open()?;
        if reg.leases().get(node).is_some_and(|l| l["owner"] == OWNER) {
            reg.leases_mut().remove(node);
            reg.mark();
            reg.commit()?;
        }
    }
    let done = result?;
    events::emit("warm_done", json!({
        "node": node, "actor": OWNER, "to": main, "steps": done, "of": w.steps.len(),
        "seconds": started.elapsed().as_secs(),
    }));
    eprintln!("midas warm: {node} warmed to {} — {done}/{} steps in {}s", &main[..8], w.steps.len(), started.elapsed().as_secs());
    Ok(())
}

/// The checkout's build directory in bytes, 0 when there is none. `du -sk`, not
/// GNU's `-sb`: macOS's du has no `-b`, and reading its error as 0 kept the Mac
/// nodes from ever being trimmed (110 GB against the 24 GB ceiling, 2026-10-20).
fn target_bytes(node: &str) -> Result<u64> {
    let out = ssh(node, "[ -d target ] && du -sk target | cut -f1 || echo 0")?;
    let kb = out.trim().parse::<u64>().with_context(|| format!("du on {node} said {:?}", out.trim()))?;
    Ok(kb * 1024)
}

/// One logged step: what ran, for how long, and how it ended (with the tail of
/// its output when it failed — the part that says why).
fn step(node: &str, name: &str, cmd: &str) -> Result<()> {
    step_as(node, name, cmd, false)
}

/// A step, `optional` when its failure is expected on some nodes (a toolchain
/// one lacks): said in its event, so `status` does not count it as a failure.
fn step_as(node: &str, name: &str, cmd: &str, optional: bool) -> Result<()> {
    let t = Instant::now();
    let out = ssh_raw(node, cmd)?;
    let ok = out.status.success();
    let tail: String = {
        let all = format!("{}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr));
        let lines: Vec<&str> = all.lines().filter(|l| !l.trim().is_empty()).collect();
        lines[lines.len().saturating_sub(8)..].join("\n")
    };
    events::emit("warm_step", json!({
        "node": node, "actor": OWNER, "step": name, "ok": ok, "seconds": t.elapsed().as_secs(),
        "tail": if ok { None } else { Some(tail.clone()) }, "optional": optional.then_some(true),
    }));
    if !ok {
        bail!("{name} failed: {tail}");
    }
    Ok(())
}

/// A command in the node's own checkout, whatever repository was sent there
/// last. A node's session starts in that one (`node`, a checkout per
/// repository), so a deploy started after somebody built midas on vps-1 ran
/// `git fetch origin` in midas's copy, which has no remote, and failed at its
/// checkout (2026-10-23). Every warm and deploy step means the checkout.
pub(crate) fn ssh_raw(node: &str, cmd: &str) -> Result<std::process::Output> {
    let cmd = in_checkout(cmd);
    Command::new("ssh")
        .args(["-F", SSH_CONFIG, "-o", "BatchMode=yes", "-o", "ConnectTimeout=15", node, &cmd])
        .stdin(Stdio::null())
        .output()
        .context("running ssh")
}

pub(crate) fn in_checkout(cmd: &str) -> String {
    format!("cd {} && {cmd}", crate::node::CHECKOUT)
}

pub(crate) fn ssh(node: &str, cmd: &str) -> Result<String> {
    let out = ssh_raw(node, cmd)?;
    if !out.status.success() {
        bail!("`{cmd}` on {node}: {}", String::from_utf8_lossy(&out.stderr).trim());
    }
    Ok(String::from_utf8_lossy(&out.stdout).to_string())
}

fn git_mirror(repo: &str, args: &[&str]) -> Result<String> {
    let out = Command::new("git").arg("--git-dir").arg(crate::mirror::mirror_path(repo)).args(args).output()?;
    if !out.status.success() {
        bail!("git {}: {}", args.join(" "), String::from_utf8_lossy(&out.stderr).trim());
    }
    Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
}

pub(crate) fn shell_quote(s: &str) -> String {
    format!("'{}'", s.replace('\'', "'\\''"))
}


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

    const GB: u64 = 1_000_000_000;

    #[test]
    fn target_grows_as_far_as_the_disk_allows_within_the_floor_and_the_cap() {
        // A Mac at 30 GB with 85 GB free: room to spare, nothing to trim.
        assert_eq!(ceiling(30 * GB, Some(85 * GB)), CEILING_CAP);
        assert!(30 * GB <= ceiling(30 * GB, Some(85 * GB)));
        // The vps node at 29 GB with 21 GB free: 30 GB, keeping 20 free.
        assert_eq!(ceiling(29 * GB, Some(21 * GB)), 30 * GB);
        // A full disk never asks for less than the floor, and no reading means the floor.
        assert_eq!(ceiling(10 * GB, Some(5 * GB)), CEILING_FLOOR);
        assert_eq!(ceiling(30 * GB, None), CEILING_FLOOR);
    }
}