garage44.eu/jeroen/midas

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

.. /src/events.rs

raw

//! The event log: what midas decided, and what went wrong, as JSON lines.
//!
//! Until midas, every node incident was diagnosed by reading session
//! transcripts. This is the record that makes those questions answerable from
//! one place. Two rules:
//!
//! * **Never let logging break the tool.** Every write is best-effort; a full
//!   disk or an unreachable hub costs the event, not the claim.
//! * **Nothing secret.** No tokens, keys or file contents — names, paths, sizes,
//!   exit statuses and the last lines of a failing command's output.
//!
//! **One log, on the hub** (`<state>/log/events-YYYY-MM-DD.jsonl`, kept
//! [`KEEP_DAYS`]). The hub writes its own events there; every other process
//! sends its events to the hub (`client::send_event`), and `midas log` reads
//! them back from it. A node also keeps a copy on its own volume.

use std::fs::{self, OpenOptions};
use std::io::{BufRead, BufReader, Write};
use std::path::{Path, PathBuf};
use std::sync::Once;

use chrono::{DateTime, Duration, NaiveDate, Utc};
use serde_json::{json, Map, Value};

pub const KEEP_DAYS: i64 = 90;

fn dir(root: &Path) -> PathBuf {
    root.join("log")
}

fn file_for(root: &Path, day: NaiveDate) -> PathBuf {
    dir(root).join(format!("events-{}.jsonl", day.format("%Y-%m-%d")))
}

/// Record one event, wherever this process is.
pub fn emit(kind: &str, fields: Value) {
    let ev = build(kind, fields);
    if crate::registry::is_hub() {
        let _ = write_line(&crate::registry::root(), &ev);
        crate::builds::observe(&ev);
        // The board is made again from the log: the page sees this now.
        crate::ws::nudge();
    } else {
        crate::client::send_event(&ev);
    }
}

/// Record an event in a log of this process's own (a node keeps one on its volume).
pub fn emit_at(root: &Path, kind: &str, fields: Value) -> Value {
    let ev = build(kind, fields);
    let _ = write_line(root, &ev);
    ev
}

/// A logged event as read back. Lines written before 2026-10-14 name the node
/// `slot` (every node now sends `node`); the log keeps them until they age
/// out, mid-January 2027, and this can go then.
fn normalise(mut ev: Value) -> Value {
    if let Some(o) = ev.as_object_mut() {
        if let Some(s) = o.remove("slot") {
            o.entry("node").or_insert(s);
        }
    }
    ev
}

/// The kinds the hub acts on when it sees them (`builds::observe`): a lease
/// released, a landing counted, a deploy's outcome believed, the history
/// files written. One posted to `/v1/events` is taken only from a caller key,
/// or for `ssh_session` from the node it names — anything else on the tunnel
/// may post a line into the log, and no more.
pub fn drives_state(kind: &str) -> bool {
    matches!(kind, "ssh_session" | "claim" | "gave_up" | "node_added" | "node_removed" | "landing_done"
        | "session_start" | "session_end" | "session_label" | "deploy_published" | "deploy_failed")
}

/// An event that arrived from elsewhere (a node, an agent), into the hub's log.
pub fn record(ev: &Value) {
    // Nodes send their fields without a time (they keep their own log too); a
    // line with no `ts` is skipped by every query, which is how a whole day of
    // node events went missing from `midas log` (2026-10-11).
    let mut ev = ev.clone();
    if ev.get("ts").is_none_or(|t| !t.is_string()) {
        ev["ts"] = json!(Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true));
    }
    let _ = write_line(&crate::registry::root(), &ev);
    crate::builds::observe(&ev);
    crate::ws::nudge();
}

pub(crate) fn build(kind: &str, fields: Value) -> Value {
    let mut ev = Map::new();
    ev.insert("ts".into(), json!(Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true)));
    ev.insert("kind".into(), json!(kind));
    if let Value::Object(f) = fields {
        for (k, v) in f {
            if !v.is_null() {
                ev.entry(k).or_insert(v);
            }
        }
    }
    // Read once: it was a file read for every event written.
    static HOST: std::sync::OnceLock<String> = std::sync::OnceLock::new();
    let host = HOST.get_or_init(|| fs::read_to_string("/etc/hostname").unwrap_or_default().trim().to_string());
    ev.entry("host").or_insert(json!(host));
    Value::Object(ev)
}

fn write_line(root: &Path, ev: &Value) -> std::io::Result<()> {
    let d = dir(root);
    fs::create_dir_all(&d)?;
    let today = Utc::now().date_naive();
    prune_once(root, today);
    let mut f = OpenOptions::new().create(true).append(true).open(file_for(root, today))?;
    let mut line = serde_json::to_string(ev)?;
    line.push('\n');
    // One write call per line: O_APPEND keeps concurrent writers' lines whole.
    f.write_all(line.as_bytes())
}

/// Today's log, as its length and modification time: different after any
/// process writes an event (the board's cue that something changed).
pub fn stamp(root: &Path) -> (u64, i64) {
    let m = fs::metadata(file_for(root, Utc::now().date_naive())).ok();
    let mtime = m.as_ref().and_then(|m| m.modified().ok())
        .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()).map_or(0, |d| d.as_millis() as i64);
    (m.map_or(0, |m| m.len()), mtime)
}

/// Delete day files older than [`KEEP_DAYS`], at most once per process.
fn prune_once(root: &Path, today: NaiveDate) {
    static ONCE: Once = Once::new();
    ONCE.call_once(|| {
        let Ok(rd) = fs::read_dir(dir(root)) else { return };
        for e in rd.flatten() {
            let name = e.file_name().to_string_lossy().to_string();
            let Some(day) = name.strip_prefix("events-").and_then(|n| n.strip_suffix(".jsonl"))
                .and_then(|d| NaiveDate::parse_from_str(d, "%Y-%m-%d").ok()) else { continue };
            if today - day > Duration::days(KEEP_DAYS) {
                let _ = fs::remove_file(e.path());
            }
        }
    });
}

pub struct Filter {
    pub since: Duration,
    pub kinds: Vec<String>,
    pub node: Option<String>,
    pub actor: Option<String>,
}

impl Filter {
    /// The same filter as a query string, for asking the hub.
    pub fn query(&self) -> String {
        let mut q = format!("since={}", self.since.num_seconds());
        if !self.kinds.is_empty() {
            q.push_str(&format!("&kind={}", self.kinds.join(",")));
        }
        if let Some(s) = &self.node {
            q.push_str(&format!("&node={s}"));
        }
        if let Some(a) = &self.actor {
            q.push_str(&format!("&actor={a}"));
        }
        q
    }

    pub fn from_query(q: &str) -> Filter {
        let get = |k: &str| q.split('&').find_map(|p| p.strip_prefix(&format!("{k}="))).map(str::to_string);
        Filter {
            // No further back than the log keeps: a huge `since` (an open GET's) panicked in chrono,
            // and a merely large one walked millions of days looking for their files.
            since: Duration::seconds(get("since").and_then(|s| s.parse::<i64>().ok()).unwrap_or(7200)
                .clamp(0, (KEEP_DAYS + 1) * 86_400)),
            kinds: get("kind").map(|k| k.split(',').map(str::to_string).collect()).unwrap_or_default(),
            node: get("node"),
            actor: get("actor"),
        }
    }
}

/// Every event matching `f`, oldest first: from the files on the hub, from the
/// hub everywhere else.
pub fn read(f: &Filter) -> Vec<Value> {
    if crate::registry::is_hub() {
        read_at(&crate::registry::root(), f)
    } else {
        crate::client::events(f).unwrap_or_default()
    }
}

pub fn read_at(root: &Path, f: &Filter) -> Vec<Value> {
    let now = Utc::now();
    let from = now - f.since;
    let mut out = Vec::new();
    // Every line is written compact (`write_line`), so one of the kinds asked for
    // shows as `"<kind>"` in it: lines without one are skipped unparsed. The board
    // asks for two weeks of deploys each time it is made, and parsing every line
    // of that held up each change on the page by half a second.
    let quoted: Vec<String> = f.kinds.iter().map(|k| format!("\"{k}\"")).collect();
    let mut day = from.date_naive();
    while day <= now.date_naive() {
        for line in candidates(&file_for(root, day), &quoted).iter() {
            let Ok(ev) = serde_json::from_str::<Value>(line).map(normalise) else { continue };
            let ts = ev["ts"].as_str().and_then(|t| DateTime::parse_from_rfc3339(t).ok());
            if ts.is_none_or(|t| t.with_timezone(&Utc) < from)
                || (!f.kinds.is_empty() && !f.kinds.iter().any(|k| ev["kind"] == k.as_str()))
                || f.node.as_ref().is_some_and(|s| ev["node"] != s.as_str())
                || f.actor.as_ref().is_some_and(|a| !ev["actor"].as_str().is_some_and(|x| x.contains(a.as_str())))
            {
                continue;
            }
            out.push(ev);
        }
        day = day.succ_opt().unwrap();
    }
    out
}

/// A day file's lines that may be one of the kinds asked for (all of them when none are
/// named). Kept while the file stays as it was: a past day's never changes, and the
/// deploy views asked for two weeks of the log several times a minute, ten megabytes a
/// time, for the few lines that are deploys.
fn candidates(path: &Path, quoted: &[String]) -> std::sync::Arc<Vec<String>> {
    use std::collections::HashMap;
    use std::sync::{Arc, Mutex};
    type Key = (std::path::PathBuf, Vec<String>);
    static CACHE: Mutex<Option<HashMap<Key, ((u64, Option<std::time::SystemTime>), Arc<Vec<String>>)>>> = Mutex::new(None);
    let Ok(meta) = fs::metadata(path) else { return Arc::new(Vec::new()) };
    let stamp = (meta.len(), meta.modified().ok());
    let key = (path.to_path_buf(), quoted.to_vec());
    // Every kind is every line: not worth keeping a copy of.
    let keep = !quoted.is_empty();
    if keep {
        let cache = CACHE.lock().unwrap_or_else(|p| p.into_inner());
        if let Some((s, lines)) = cache.as_ref().and_then(|c| c.get(&key)) {
            if *s == stamp {
                return lines.clone();
            }
        }
    }
    let lines: Vec<String> = fs::File::open(path)
        .map(|f| {
            BufReader::new(f).lines().map_while(Result::ok)
                .filter(|line| quoted.is_empty() || quoted.iter().any(|q| line.contains(q.as_str())))
                .collect()
        })
        .unwrap_or_default();
    let lines = Arc::new(lines);
    if keep {
        let mut cache = CACHE.lock().unwrap_or_else(|p| p.into_inner());
        let c = cache.get_or_insert_with(HashMap::new);
        // Kinds come from a handful of callers; a bound all the same.
        if c.len() > 512 {
            c.clear();
        }
        c.insert(key, (stamp, lines.clone()));
    }
    lines
}

/// One event as one human line: `10-11 15:13:02 claim cpu-1 gate-x — purpose=…`.
pub fn render(ev: &Value) -> String {
    let ts = ev["ts"].as_str().and_then(|t| DateTime::parse_from_rfc3339(t).ok())
        .map(|t| t.with_timezone(&chrono::Local).format("%m-%d %H:%M:%S").to_string())
        .unwrap_or_else(|| "?".into());
    let mut s = format!("{ts} {:<14}", ev["kind"].as_str().unwrap_or("?"));
    if let Some(node) = ev["node"].as_str() {
        s.push_str(&format!(" {node}"));
    }
    if let Some(a) = ev["actor"].as_str() {
        s.push_str(&format!(" {a}"));
    }
    let skip = ["ts", "kind", "node", "actor", "host", "uid", "pid", "via_hub_from"];
    let rest: Vec<String> = ev.as_object().into_iter().flatten()
        .filter(|(k, _)| !skip.contains(&k.as_str()))
        .map(|(k, v)| match v { Value::String(x) => format!("{k}={x}"), other => format!("{k}={other}") })
        .collect();
    if !rest.is_empty() {
        s.push_str(" — ");
        s.push_str(&rest.join(" "));
    }
    s
}

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

    #[test]
    fn a_kind_filter_finds_its_events_and_only_them() {
        let root = std::env::temp_dir().join(format!("midas-events-kinds-{}", std::process::id()));
        let _ = fs::remove_dir_all(&root);
        emit_at(&root, "deploy_published", json!({"deploy": "d1"}));
        // Its kind as another field's value: read past the cheap test, still not one.
        emit_at(&root, "note", json!({"text": "deploy_published", "about": "deploy_published"}));
        emit_at(&root, "claim", json!({"node": "vps-1"}));
        let f = |kinds: &[&str]| Filter { since: Duration::hours(1), kinds: kinds.iter().map(|k| k.to_string()).collect(), node: None, actor: None };
        let got = read_at(&root, &f(&["deploy_published"]));
        assert_eq!(got.len(), 1);
        assert_eq!(got[0]["deploy"], "d1");
        assert_eq!(read_at(&root, &f(&["claim", "note"])).len(), 2);
        assert_eq!(read_at(&root, &f(&[])).len(), 3, "no kinds: every event");
        let _ = fs::remove_dir_all(&root);
    }
}