garage44.eu/jeroen/midas

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

.. /src/usage.rs

raw

//! What each node used over time: memory, load and disk, minute by minute — what
//! sizes the machines' nodes (how many on a box, how much memory each), which the
//! latest reading alone (`readings/<node>.json`, overwritten every minute) could
//! not say.
//!
//! The hub appends one line per heartbeat to `usage/YYYY-MM-DD.jsonl` (UTC days;
//! about 150 bytes a line, so some 200 kB a node a day), kept [`KEEP_DAYS`] days:
//!
//! * `mem`: process memory now (`mem_anon`), and `peak`, the highest of the
//!   node's ten-second samples since its last heartbeat (`node.rs`, a midas of
//!   2026-11-28 or later; older nodes send none and the minute's value stands);
//! * `lim`: what the node may use — its cgroup's limit, or a VM's memory;
//! * `load` (one-minute average) against `cpus`;
//! * `free` and `disk`: the work volume's free space and size; `target`: the
//!   build directory's size;
//! * `s`: open ssh sessions, so a quiet node is told from a busy one;
//! * `oom`: the cgroup's OOM kills since it started (Linux only).
//!
//! `GET /v1/usage?since=&step=` buckets them per node; `midas stats --nodes`
//! reads that.

use std::collections::BTreeMap;
use std::fs::{self, OpenOptions};
use std::io::Write;
use std::path::PathBuf;

use anyhow::Result;
use chrono::{TimeZone, Utc};
use serde_json::{json, Value};

use crate::registry;

/// How long lines are kept: long enough to see a pattern over weeks of work.
pub const KEEP_DAYS: i64 = 90;

fn dir() -> PathBuf {
    registry::root().join("usage")
}

fn day(t: i64) -> String {
    Utc.timestamp_opt(t, 0).single().unwrap_or_else(Utc::now).format("%Y-%m-%d").to_string()
}

fn day_file(t: i64) -> PathBuf {
    dir().join(format!("{}.jsonl", day(t)))
}

/// The line kept for one reading, at `t`.
pub fn line(node: &str, t: i64, r: &Value) -> Value {
    let mem = r["mem_anon"].as_u64().or(r["mem_used"].as_u64());
    json!({
        "t": t, "n": node, "mem": mem, "peak": r["mem_peak"].as_u64().or(mem), "lim": r["mem_max"],
        "load": r["load"], "cpus": r["cpus"], "free": r["disk_free"], "disk": r["disk_total"],
        "target": r["target_bytes"], "s": r["sessions"], "oom": r["oom_kills"],
    })
}

/// Keep a node's reading (the hub's heartbeat handler). A day's first line
/// also forgets the days past [`KEEP_DAYS`].
pub fn record(node: &str, r: &Value) -> Result<()> {
    let t = r["at"].as_i64().unwrap_or_else(registry::now);
    fs::create_dir_all(dir())?;
    let file = day_file(t);
    if !file.exists() {
        prune(t);
    }
    OpenOptions::new().create(true).append(true).open(file)?.write_all(format!("{}\n", line(node, t, r)).as_bytes())?;
    Ok(())
}

fn prune(t: i64) {
    let keep = day(t - KEEP_DAYS * 86400);
    for e in fs::read_dir(dir()).into_iter().flatten().flatten() {
        let name = e.file_name().to_string_lossy().to_string();
        if name.ends_with(".jsonl") && name < keep {
            let _ = fs::remove_file(e.path());
        }
    }
}

/// Every line from `from` to `to`, oldest first.
fn lines(from: i64, to: i64) -> Vec<Value> {
    let mut out = vec![];
    let mut d = from - from.rem_euclid(86400);
    while d <= to {
        if let Ok(text) = fs::read_to_string(day_file(d)) {
            out.extend(text.lines().filter_map(|l| serde_json::from_str::<Value>(l).ok())
                .filter(|v| v["t"].as_i64().is_some_and(|t| t >= from && t <= to)));
        }
        d += 86400;
    }
    out
}

/// One bucket of a node's lines, as an object: memory's peak (max), its p95 and
/// mean; the limit; load's mean, max and the share of minutes it was past the
/// CPUs; the least free disk; the largest build directory; the share of
/// minutes a session was open; OOM kills that happened in it; and how many
/// minutes it holds.
pub fn bucket(start: i64, s: &[&Value]) -> Value {
    let f = |k: &str| -> Vec<f64> { s.iter().filter_map(|v| v[k].as_f64()).collect() };
    let max = |v: &[f64]| v.iter().copied().reduce(f64::max);
    let min = |v: &[f64]| v.iter().copied().reduce(f64::min);
    let mean = |v: &[f64]| (!v.is_empty()).then(|| v.iter().sum::<f64>() / v.len() as f64);
    let share = |n: usize| (n as f64 / s.len().max(1) as f64 * 1000.0).round() / 1000.0;
    let mut peaks = f("peak");
    peaks.sort_by(f64::total_cmp);
    let p95 = (!peaks.is_empty()).then(|| peaks[((peaks.len() - 1) as f64 * 0.95).round() as usize]);
    let loads = f("load");
    let over = s.iter().filter(|v| matches!((v["load"].as_f64(), v["cpus"].as_f64()), (Some(l), Some(c)) if l > c)).count();
    let busy = s.iter().filter(|v| v["s"].as_u64().is_some_and(|n| n > 0)).count();
    let ooms: Vec<u64> = s.iter().filter_map(|v| v["oom"].as_u64()).collect();
    let oom: u64 = ooms.windows(2).map(|w| w[1].saturating_sub(w[0])).sum();
    let round = |x: Option<f64>| x.map(|x| (x * 100.0).round() / 100.0);
    json!({
        "t": start, "minutes": s.len(),
        "mem_peak": max(&peaks), "mem_p95": p95, "mem_mean": mean(&f("mem")).map(f64::round), "mem_lim": max(&f("lim")),
        "load_mean": round(mean(&loads)), "load_max": round(max(&loads)), "cpus": max(&f("cpus")), "over_cpus": share(over),
        "disk_free_min": min(&f("free")), "disk": max(&f("disk")), "target_max": max(&f("target")),
        "busy": share(busy), "oom_kills": oom,
    })
}

/// `GET /v1/usage`: each node's lines of the last `since` seconds in buckets of
/// `step` seconds (an hour unless said), oldest first, and the whole window as
/// one bucket per node.
pub fn read(since: i64, step: Option<i64>) -> Value {
    let to = registry::now();
    let from = to - since;
    let step = step.unwrap_or(3600).max(60);
    let all = lines(from, to);
    let mut by_node: BTreeMap<String, Vec<&Value>> = BTreeMap::new();
    for l in &all {
        by_node.entry(l["n"].as_str().unwrap_or("?").to_string()).or_default().push(l);
    }
    let mut nodes = serde_json::Map::new();
    for (node, ls) in by_node {
        let mut buckets: BTreeMap<i64, Vec<&Value>> = BTreeMap::new();
        for l in &ls {
            let t = l["t"].as_i64().unwrap_or(0);
            buckets.entry(t - t.rem_euclid(step)).or_default().push(l);
        }
        nodes.insert(node, json!({
            "whole": bucket(from, &ls),
            "buckets": buckets.iter().map(|(t, s)| bucket(*t, s)).collect::<Vec<_>>(),
        }));
    }
    json!({"from": from, "to": to, "step": step, "nodes": nodes})
}