git clone https://garage44.eu/jeroen/midas.git.. /src/watch.rs
//! Watching what is deployed: each target's service over time, beside the
//! deploys that changed it (`docs/mockups/service-watch/`).
//!
//! midas knew which commit each target serves and which landings went into it
//! (ship.rs), called a landing live the moment it was published, and stopped
//! looking: a simulator restarting every five minutes, or memory climbing for
//! a week, was found by whoever tripped over it. So the hub samples, once a
//! minute, every target whose hub.conf entry has a `watch`:
//!
//! * its systemd unit (`systemctl show`): active or not, memory, CPU (as a
//! share of one core, from the counter's rise since the last sample) and
//! restarts — readable by the hub's own user, no journal or root needed;
//! * its probes: addresses that must answer below 400, asked with curl from
//! here, and how long each took;
//! * the machine: memory, load, and the free space of every filesystem a
//! target publishes to.
//!
//! One line per target and minute in `watch/YYYY-MM-DD.jsonl` (UTC days, a few
//! hundred kB a day for a handful of targets), kept [`KEEP_DAYS`] days. `GET
//! /v1/watch?since=&step=` buckets them for the page's Services tab, with what
//! each target serves, its state now and the deploys in the window — each with
//! the landings it carried, which is what nothing outside midas could draw.
//!
//! A target changing state (ok, trouble, down, unknown) is logged
//! (`watch_changed`): what incidents and the agents put on them will build on.
//! Only deploy targets are watched, not everything on the machine, and only
//! from the machine itself, so the machine going down is not seen (the
//! person's choices, 2026-11-18).
use std::collections::BTreeMap;
use std::fs::{self, OpenOptions};
use std::io::Write;
use std::os::unix::fs::MetadataExt;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::Mutex;
use std::time::Duration;
use anyhow::Result;
use chrono::{DateTime, TimeZone, Utc};
use serde_json::{json, Value};
use crate::conf::{Target, Watch};
use crate::{events, registry};
/// How often everything is sampled.
pub const INTERVAL_S: u64 = 60;
/// How long samples are kept.
const KEEP_DAYS: i64 = 14;
/// A sample older than this says nothing about now.
const FRESH_S: i64 = 3 * INTERVAL_S as i64;
/// How long a probe may take before it counts as no answer.
const PROBE_TIMEOUT_S: u64 = 10;
/// Each unit's CPU counter at the last sample, and when: its rise is the CPU used.
static CPU: Mutex<BTreeMap<String, (u64, i64)>> = Mutex::new(BTreeMap::new());
/// Each target's state at the last sample, to log a change once.
static STATE: Mutex<BTreeMap<String, String>> = Mutex::new(BTreeMap::new());
/// The hub's watcher thread: sample, forget what is too old, sleep.
pub fn run() {
loop {
let t = registry::now();
if let Err(e) = sample_all(t) {
events::emit("error", json!({"what": format!("watching the deploy targets: {e:#}")}));
}
std::thread::sleep(Duration::from_secs(INTERVAL_S));
}
}
fn watched() -> Vec<(Target, Watch)> {
crate::conf::hub().targets().into_iter().filter_map(|t| t.deploy.watch.clone().map(|w| (t, w))).collect()
}
fn sample_all(t: i64) -> Result<()> {
let targets = watched();
if targets.is_empty() {
return Ok(());
}
let recent = samples(t - 3600, t);
let mut lines = vec![];
for (target, w) in &targets {
let mut line = json!({"t": t, "target": target.name});
if let Some(unit) = &w.unit {
match unit_now(unit) {
Some(u) => {
line["active"] = json!(u.active);
line["mem"] = json!(u.mem);
line["restarts"] = json!(u.restarts);
line["cpu"] = json!(u.cpu_ns.and_then(|ns| cpu_share(unit, ns, t)));
}
// Not read at all (no systemd here, or the bus refused): that says nothing about the unit.
None => line["unread"] = json!(true),
}
}
line["probes"] = json!(w.probes.iter().map(|url| {
let (code, ms) = probe(url);
json!({"u": url, "c": code, "ms": ms})
}).collect::<Vec<_>>());
log_change(&target.name, w, &line, &recent, t);
lines.push(line);
}
lines.push(json!({"t": t, "machine": machine_now(&targets)}));
append(t, &lines)?;
prune(t);
Ok(())
}
// ── One sample ───────────────────────────────────────────────────────────────
#[derive(Debug, Default, PartialEq)]
struct Unit {
active: String,
mem: Option<u64>,
cpu_ns: Option<u64>,
restarts: Option<u64>,
}
fn unit_now(unit: &str) -> Option<Unit> {
let out = Command::new("systemctl")
.args(["show", unit, "-p", "ActiveState,MemoryCurrent,CPUUsageNSec,NRestarts"])
.output().ok()?;
out.status.success().then(|| parse_show(&String::from_utf8_lossy(&out.stdout)))
}
/// `systemctl show`'s `Key=value` lines. A value systemd has not (`[not set]`,
/// or the all-ones it prints for "infinity") is none.
fn parse_show(text: &str) -> Unit {
let mut u = Unit::default();
for line in text.lines() {
let Some((k, v)) = line.split_once('=') else { continue };
let n = v.parse::<u64>().ok().filter(|n| *n != u64::MAX);
match k {
"ActiveState" => u.active = v.to_string(),
"MemoryCurrent" => u.mem = n,
"CPUUsageNSec" => u.cpu_ns = n,
"NRestarts" => u.restarts = n,
_ => {}
}
}
u
}
/// The share of one core a unit used since its last sample, in percent: none
/// at the first, or after the counter went back (the unit started again).
fn cpu_share(unit: &str, ns: u64, t: i64) -> Option<f64> {
let mut prev = CPU.lock().unwrap_or_else(|e| e.into_inner());
let last = prev.insert(unit.to_string(), (ns, t));
let (was, at) = last?;
(ns >= was && t > at).then(|| ((ns - was) as f64 / ((t - at) as f64 * 1e9) * 1000.0).round() / 10.0)
}
/// Ask an address: its status (0 for no answer) and how long it took, in ms.
fn probe(url: &str) -> (u16, Option<u64>) {
let out = Command::new("curl")
.args(["-s", "-o", "/dev/null", "--max-time", &PROBE_TIMEOUT_S.to_string(), "-w", "%{http_code} %{time_total}", "--url", url])
.output();
let Ok(out) = out else { return (0, None) };
parse_probe(&String::from_utf8_lossy(&out.stdout))
}
fn parse_probe(text: &str) -> (u16, Option<u64>) {
let mut it = text.split_whitespace();
let code = it.next().and_then(|c| c.parse::<u16>().ok()).unwrap_or(0);
let ms = it.next().and_then(|s| s.parse::<f64>().ok()).filter(|_| code != 0).map(|s| (s * 1000.0).round() as u64);
(code, ms)
}
fn answered(code: u64) -> bool {
(1..400).contains(&code)
}
/// The machine: memory, load, and each filesystem a target publishes to (and
/// the hub's state's), once per filesystem.
fn machine_now(targets: &[(Target, Watch)]) -> Value {
let meminfo = fs::read_to_string("/proc/meminfo").unwrap_or_default();
let kb = |key: &str| meminfo.lines().find_map(|l| l.strip_prefix(key)?.trim().strip_suffix("kB")?.trim().parse::<u64>().ok());
let load = fs::read_to_string("/proc/loadavg").ok().and_then(|l| l.split_whitespace().next()?.parse::<f64>().ok());
let mut places: Vec<PathBuf> = vec![registry::root()];
places.extend(targets.iter().flat_map(|(t, _)| t.deploy.publish.iter().map(|p| PathBuf::from(&p.to))));
let mut seen = vec![];
let mut disks = vec![];
for p in places {
let Some(p) = existing(&p) else { continue };
let Ok(dev) = fs::metadata(&p).map(|m| m.dev()) else { continue };
if seen.contains(&dev) {
continue;
}
seen.push(dev);
if let Some((free, size)) = crate::util::disk_space(&p) {
disks.push(json!({"p": p, "free": free, "size": size}));
}
}
json!({
"mem_total": kb("MemTotal:").map(|k| k * 1024),
"mem_used": kb("MemTotal:").zip(kb("MemAvailable:")).map(|(t, a)| t.saturating_sub(a) * 1024),
"load": load, "disks": disks,
})
}
/// The path, or the nearest of its parents that exists: a target's file need not be there yet.
fn existing(p: &Path) -> Option<PathBuf> {
p.ancestors().find(|a| a.exists()).map(Path::to_path_buf)
}
// ── State ────────────────────────────────────────────────────────────────────
/// What a target's last sample says, and why: `down` (the unit not active, or
/// a probe not answered), `trouble` (over a limit), or `ok`; `unknown` when the unit
/// could not be read.
fn judge(w: &Watch, last: &Value, restarts_h: Option<u64>) -> (&'static str, String) {
if last["unread"] == true {
return ("unknown", format!("could not read {}", w.unit.as_deref().unwrap_or("the unit")));
}
let active = last["active"].as_str();
if let Some(a) = active.filter(|a| *a != "active") {
return ("down", format!("{} is {a}", w.unit.as_deref().unwrap_or("the unit")));
}
let failing: Vec<String> = last["probes"].as_array().into_iter().flatten()
.filter(|p| !answered(p["c"].as_u64().unwrap_or(0)))
.map(|p| match p["c"].as_u64().unwrap_or(0) {
0 => format!("{} does not answer", p["u"].as_str().unwrap_or("")),
c => format!("{} answers {c}", p["u"].as_str().unwrap_or("")),
})
.collect();
if !failing.is_empty() {
return ("down", failing.join("; "));
}
if let (Some(max), Some(mem)) = (w.memory_mb, last["mem"].as_u64()) {
if mem > max * 1024 * 1024 {
return ("trouble", format!("{} MB of memory, over its {max} MB", mem / 1024 / 1024));
}
}
if let (Some(max), Some(n)) = (w.restarts_per_h, restarts_h) {
if n > max {
return ("trouble", format!("restarted {n} times in the last hour, over its {max}"));
}
}
("ok", String::new())
}
/// Restarts in the last hour, from the samples' running count: each rise is a
/// restart, and a fall (the count starting again with the unit) is none.
fn restarts_since(samples: &[&Value], from: i64) -> Option<u64> {
let counts: Vec<u64> = samples.iter().filter(|s| s["t"].as_i64().unwrap_or(0) >= from).filter_map(|s| s["restarts"].as_u64()).collect();
(!counts.is_empty()).then(|| counts.windows(2).map(|w| w[1].saturating_sub(w[0])).sum())
}
fn log_change(target: &str, w: &Watch, line: &Value, recent: &[Value], t: i64) {
let mine: Vec<&Value> = recent.iter().filter(|s| s["target"] == target).chain(std::iter::once(line)).collect();
let (state, why) = judge(w, line, restarts_since(&mine, t - 3600));
let mut states = STATE.lock().unwrap_or_else(|e| e.into_inner());
let was = states.insert(target.to_string(), state.to_string());
// The hub starting again is no change: only a state that is not ok is said then.
if was.as_deref() != Some(state) && (was.is_some() || state != "ok") {
events::emit("watch_changed", json!({"target": target, "from": was, "to": state, "why": why}));
}
}
// ── Storing ──────────────────────────────────────────────────────────────────
fn dir() -> PathBuf {
registry::root().join("watch")
}
fn day_file(t: i64) -> PathBuf {
let d = Utc.timestamp_opt(t, 0).single().unwrap_or_else(Utc::now).format("%Y-%m-%d");
dir().join(format!("{d}.jsonl"))
}
fn append(t: i64, lines: &[Value]) -> Result<()> {
fs::create_dir_all(dir())?;
let text: String = lines.iter().map(|l| format!("{l}\n")).collect();
// One write for the minute's lines (builds.rs `append_to`).
OpenOptions::new().create(true).append(true).open(day_file(t))?.write_all(text.as_bytes())?;
Ok(())
}
fn prune(t: i64) {
let keep = Utc.timestamp_opt(t - KEEP_DAYS * 86400, 0).single().map(|d| d.format("%Y-%m-%d").to_string()).unwrap_or_default();
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 samples(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
}
// ── Reading ──────────────────────────────────────────────────────────────────
/// One bucket of a target's samples: `[start, memory MB (max), CPU % (mean),
/// probe ms (max), up (0 when any sample was down, else 1), restarts]`.
fn bucket(start: i64, s: &[&Value]) -> Value {
let max = |f: &dyn Fn(&Value) -> Option<f64>| s.iter().filter_map(|v| f(v)).fold(None, |a: Option<f64>, x| Some(a.map_or(x, |a| a.max(x))));
let cpus: Vec<f64> = s.iter().filter_map(|v| v["cpu"].as_f64()).collect();
let mem = max(&|v| v["mem"].as_f64().map(|b| (b / 1024.0 / 1024.0).round()));
let ms = max(&|v| v["probes"].as_array()?.iter().filter_map(|p| p["ms"].as_f64()).reduce(f64::max));
let up = s.iter().all(|v| {
v["active"].as_str().is_none_or(|a| a == "active")
&& v["probes"].as_array().is_none_or(|ps| ps.iter().all(|p| answered(p["c"].as_u64().unwrap_or(0))))
});
let counts: Vec<u64> = s.iter().filter_map(|v| v["restarts"].as_u64()).collect();
let restarts: u64 = counts.windows(2).map(|w| w[1].saturating_sub(w[0])).sum();
json!([start, mem, (!cpus.is_empty()).then(|| (cpus.iter().sum::<f64>() / cpus.len() as f64 * 10.0).round() / 10.0), ms, up as u8, restarts])
}
fn buckets(s: &[&Value], from: i64, step: i64) -> Vec<Value> {
let mut by: BTreeMap<i64, Vec<&Value>> = BTreeMap::new();
for v in s {
let t = v["t"].as_i64().unwrap_or(0);
by.entry(from + (t - from).div_euclid(step) * step).or_default().push(v);
}
by.into_iter().map(|(b, s)| bucket(b, &s)).collect()
}
fn ts(e: &Value) -> Option<i64> {
e["ts"].as_str().and_then(|t| DateTime::parse_from_rfc3339(t).ok()).map(|t| t.timestamp())
}
/// The deploys of `target` published from `from` on, each with the landings it
/// brought: those that the commit it published has and the one before it had not.
fn deploys(target: &Target, evs: &[Value], landed: &[Value], from: i64) -> Vec<Value> {
let mut before: Option<String> = None;
let mut out = vec![];
for e in evs.iter().filter(|e| e["kind"] == "deploy_published" && e["target"] == target.name.as_str()) {
let (Some(sha), Some(t)) = (e["sha"].as_str(), ts(e)) else { continue };
if t >= from {
// One git process for the deploy, not one per landing (ship::added);
// the first deploy in the log, with nothing before it, asks each.
let added = before.as_deref().and_then(|b| crate::ship::added(&target.repo, b, sha));
let new = |s: &str| match &added {
Some(a) => a.contains(s),
None => crate::ship::contains(&target.repo, sha, s)
&& !before.as_deref().is_some_and(|b| crate::ship::contains(&target.repo, b, s)),
};
let carried: Vec<Value> = landed.iter()
.filter(|l| ts(l).is_some_and(|lt| lt <= t))
.filter(|l| l["sha"].as_str().is_some_and(new))
.map(|l| json!({"session": l["actor"], "branch": l["branch"], "sha": l["sha"]}))
.collect();
out.push(json!({"t": t, "sha": sha, "by": e["actor"], "landings": carried}));
}
before = Some(sha.to_string());
}
out
}
/// `GET /v1/watch?since=S&step=T`: every watched target's state now, what it
/// serves, its samples by `step` over the last `since` seconds and the deploys
/// in them; and the machine's.
pub fn read(since_s: i64, step_s: Option<i64>) -> Value {
let to = registry::now();
let since_s = since_s.clamp(3600, KEEP_DAYS * 86400);
let step = step_s.unwrap_or(match since_s {
s if s <= 6 * 3600 => 60,
s if s <= 2 * 86400 => 300,
_ => 3600,
}).clamp(60, 86400);
let from = to - since_s;
let all = samples(from.min(to - 3600), to);
let evs = events::read_at(®istry::root(), &events::Filter {
since: chrono::Duration::days(KEEP_DAYS + 1), kinds: vec!["deploy_published".into(), "deploy_skipped".into(), "landing_done".into()], node: None, actor: None,
});
let last = crate::ship::last_deploys(&evs);
let landed: Vec<Value> = evs.iter().filter(|e| e["kind"] == "landing_done" && e["outcome"] == "landed").cloned().collect();
let targets: Vec<Value> = watched().into_iter().map(|(target, w)| {
let mine: Vec<&Value> = all.iter().filter(|s| s["target"] == target.name.as_str()).collect();
let now = mine.last().filter(|s| to - s["t"].as_i64().unwrap_or(0) <= FRESH_S);
let restarts_h = restarts_since(&mine, to - 3600);
let (state, why) = match now {
Some(s) => judge(&w, s, restarts_h),
None => ("unknown", "no sample in the last three minutes".to_string()),
};
let window: Vec<&Value> = mine.iter().copied().filter(|s| s["t"].as_i64().unwrap_or(0) >= from).collect();
json!({
"name": target.name, "repo": target.repo, "unit": w.unit, "probes": w.probes,
"memory_mb": w.memory_mb, "restarts_per_h": w.restarts_per_h,
"state": state, "why": why, "now": now, "restarts_h": restarts_h,
"serves": last.get(&target.name).and_then(|l| l.published.clone()),
"points": buckets(&window, from, step),
"deploys": deploys(&target, &evs, &landed, from),
})
}).collect();
let machine: Vec<Value> = all.iter().filter(|s| s.get("machine").is_some() && s["t"].as_i64().unwrap_or(0) >= from).collect::<Vec<_>>()
.chunk_by(|a, b| (a["t"].as_i64().unwrap_or(0) - from).div_euclid(step) == (b["t"].as_i64().unwrap_or(0) - from).div_euclid(step))
.map(|c| {
let b = from + (c[0]["t"].as_i64().unwrap_or(0) - from).div_euclid(step) * step;
let mem = c.iter().filter_map(|s| s["machine"]["mem_used"].as_f64()).fold(0.0, f64::max);
let load = c.iter().filter_map(|s| s["machine"]["load"].as_f64()).fold(0.0, f64::max);
json!([b, (mem / 1024.0 / 1024.0).round(), load])
})
.collect();
let machine_now = all.iter().rev().find(|s| s.get("machine").is_some()).map(|s| s["machine"].clone());
json!({"from": from, "to": to, "step": step, "targets": targets, "machine": {"now": machine_now, "points": machine}})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn systemctl_show_is_read_and_its_infinity_is_none() {
let u = parse_show("ActiveState=active\nMemoryCurrent=178790400\nCPUUsageNSec=18446744073709551615\nNRestarts=2\n");
assert_eq!(u, Unit {active: "active".into(), mem: Some(178790400), cpu_ns: None, restarts: Some(2)});
assert_eq!(parse_show("MemoryCurrent=[not set]\n").mem, None);
}
#[test]
fn a_probe_with_no_answer_has_no_time() {
assert_eq!(parse_probe("200 0.042817"), (200, Some(43)));
assert_eq!(parse_probe("000 10.001"), (0, None));
assert_eq!(parse_probe(""), (0, None));
}
#[test]
fn cpu_is_the_counters_rise_as_a_share_of_one_core() {
assert_eq!(cpu_share("test-a.service", 1_000_000_000, 100), None, "nothing to compare the first with");
assert_eq!(cpu_share("test-a.service", 31_000_000_000, 160), Some(50.0));
assert_eq!(cpu_share("test-a.service", 5, 220), None, "the unit started again");
}
#[test]
fn a_target_is_down_before_it_is_in_trouble() {
let w = Watch {unit: Some("sim.service".into()), probes: vec!["http://x/health".into()], memory_mb: Some(100), restarts_per_h: Some(2)};
let ok = json!({"active": "active", "mem": 50 << 20, "probes": [{"u": "http://x/health", "c": 200, "ms": 4}]});
assert_eq!(judge(&w, &ok, Some(0)).0, "ok");
assert_eq!(judge(&w, &ok, Some(3)).0, "trouble");
let fat = json!({"active": "active", "mem": 200 << 20, "probes": []});
assert_eq!(judge(&w, &fat, None), ("trouble", "200 MB of memory, over its 100 MB".into()));
let refused = json!({"active": "active", "mem": 200 << 20, "probes": [{"u": "http://x/health", "c": 502}]});
assert_eq!(judge(&w, &refused, None), ("down", "http://x/health answers 502".into()));
let stopped = json!({"active": "failed", "probes": []});
assert_eq!(judge(&w, &stopped, None), ("down", "sim.service is failed".into()));
let unread = json!({"unread": true, "probes": [{"u": "http://x/health", "c": 200, "ms": 4}]});
assert_eq!(judge(&w, &unread, None), ("unknown", "could not read sim.service".into()), "no systemd to ask is not a unit down");
}
#[test]
fn restarts_are_the_counts_rises_and_a_fall_is_none() {
let s: Vec<Value> = [(0, 1), (60, 1), (120, 3), (180, 0), (240, 1)].iter().map(|(t, r)| json!({"t": t, "restarts": r})).collect();
let refs: Vec<&Value> = s.iter().collect();
assert_eq!(restarts_since(&refs, 0), Some(3));
assert_eq!(restarts_since(&refs, 1000), None);
}
#[test]
fn a_bucket_is_down_when_any_of_its_minutes_was() {
let a = json!({"t": 0, "active": "active", "mem": 100 << 20, "cpu": 10.0, "probes": [{"c": 200, "ms": 5}]});
let b = json!({"t": 60, "active": "active", "mem": 120 << 20, "cpu": 20.0, "probes": [{"c": 0}]});
assert_eq!(bucket(0, &[&a, &b]), json!([0, 120.0, 15.0, 5.0, 0, 0]));
assert_eq!(bucket(0, &[&a]), json!([0, 100.0, 10.0, 5.0, 1, 0]));
}
}