git clone https://garage44.eu/jeroen/midas.git.. /src/runners.rs
//! The sessions runners (`midas sessions run`): kept running, and seen.
//!
//! On 2026-11-19 at 20:58:44 UTC the runner died without a line in its log. An
//! agent had ended (a conversation that could not be loaded) and the runner wrote
//! the autopilot's next message to it: with SIGPIPE at its default (`main.rs`
//! restores it for every command) that write ended the runner. Its agents saw
//! their client go and ended too, and for nine hours the page still said
//! "thinking", nothing started, and the person's autopilots ran out unused. Three
//! things here, so that it cannot go unseen again:
//!
//! * **On the runner's machine**, `midas sessions run` is a small supervisor that
//! starts the runner proper as its child and starts it again when it ends. Each
//! stop is written down with its reason as `runner_stopped`: a new build, a
//! signal and who sent it, a panic and where, or, seen only by the supervisor,
//! a death the runner could not record (SIGKILL, a crash).
//! * **On the hub**, every runner's polls are stamped. One that has not asked for
//! work for [`AWAY_AFTER_S`] is *away* (`runner_away`): its sessions show as
//! paused on the page, and when it is back (`runner_back`) an autopilot it was
//! running gets the time back.
//! * `GET /v1/runners` reads the events back for the page: each runner now, its
//! stops, and the time it was away.
use std::collections::BTreeMap;
use std::process::Command;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Mutex;
use std::time::{Duration, Instant};
use serde_json::{json, Value};
use crate::events;
// ── The runner's side ────────────────────────────────────────────────────────
/// Set in the runner proper, by its supervisor: this process runs the sessions.
pub const CHILD_ENV: &str = "MIDAS_RUNNER_CHILD";
/// Who started it: `watch` (the host's timer), `supervisor` (after a stop), or
/// unset, by hand. A start after a new build is `build` (sessions.rs knows).
pub const STARTED_BY_ENV: &str = "MIDAS_RUNNER_STARTED_BY";
/// A supervisor started again on a new build: the child it had, still running.
const ADOPT_ENV: &str = "MIDAS_RUNNER_CHILD_PID";
/// How many sessions the runner is running now, for the record of a stop.
pub static SESSIONS: AtomicUsize = AtomicUsize::new(0);
/// The signals that ask a process to stop, which the runner and its supervisor
/// take on a thread of their own so that they can say who sent them.
const STOPS: [libc::c_int; 3] = [libc::SIGTERM, libc::SIGINT, libc::SIGHUP];
fn signal_name(sig: i32) -> String {
match sig {
libc::SIGTERM => "SIGTERM".into(),
libc::SIGINT => "SIGINT".into(),
libc::SIGHUP => "SIGHUP".into(),
libc::SIGKILL => "SIGKILL".into(),
libc::SIGPIPE => "SIGPIPE".into(),
libc::SIGSEGV => "SIGSEGV".into(),
libc::SIGABRT => "SIGABRT".into(),
libc::SIGBUS => "SIGBUS".into(),
n => format!("signal {n}"),
}
}
/// Blocks [`STOPS`] in this thread (and so in every thread started after it), and
/// waits for them on a thread of its own, calling `on` with the signal and its
/// sender's pid (0 where the platform does not say). Before any other thread starts.
fn take_stop_signals(on: impl Fn(i32, u32) + Send + 'static) {
// SAFETY: a signal set filled and installed as this thread's mask, before other threads exist.
let set = unsafe {
let mut set: libc::sigset_t = std::mem::zeroed();
libc::sigemptyset(&mut set);
for s in STOPS {
libc::sigaddset(&mut set, s);
}
libc::pthread_sigmask(libc::SIG_BLOCK, &set, std::ptr::null_mut());
set
};
std::thread::spawn(move || loop {
let (sig, pid) = wait_signal(&set);
if sig > 0 {
on(sig, pid);
}
});
}
#[cfg(target_os = "linux")]
fn wait_signal(set: &libc::sigset_t) -> (i32, u32) {
// SAFETY: sigwaitinfo on a set blocked in every thread, into a zeroed siginfo.
unsafe {
let mut info: libc::siginfo_t = std::mem::zeroed();
let sig = libc::sigwaitinfo(set, &mut info);
(sig, if sig > 0 { info.si_pid() as u32 } else { 0 })
}
}
/// macOS has no `sigwaitinfo`: the signal, without its sender.
#[cfg(not(target_os = "linux"))]
fn wait_signal(set: &libc::sigset_t) -> (i32, u32) {
let mut sig: libc::c_int = 0;
// SAFETY: sigwait on a set blocked in every thread.
let rc = unsafe { libc::sigwait(set, &mut sig) };
(if rc == 0 { sig } else { -1 }, 0)
}
/// Who sent a signal: its command line, and the session or service it runs for
/// (the `MIDAS_OWNER` in its environment, which every session's agent sets),
/// read while it may still be there.
fn sender(pid: u32) -> Value {
if pid == 0 {
return json!({});
}
let procs = crate::procs::all();
let Some(p) = procs.iter().find(|p| p.pid == pid) else {
return json!({"by_pid": pid, "by_cmd": null, "by_note": "gone before it could be read"});
};
let owner = std::fs::read(format!("/proc/{pid}/environ")).ok().and_then(|e| {
e.split(|b| *b == 0).find_map(|kv| kv.strip_prefix(b"MIDAS_OWNER=").map(|v| String::from_utf8_lossy(v).to_string()))
});
// Its parents, nearest first, to the machine's first process: what started it.
let mut chain = Vec::new();
let mut at = p.ppid;
while at > 1 && chain.len() < 6 {
let Some(q) = procs.iter().find(|q| q.pid == at) else { break };
chain.push(crate::util::short(&q.cmd, 120));
at = q.ppid;
}
json!({"by_pid": pid, "by_cmd": crate::util::short(&p.cmd, 300), "by_owner": owner, "by_parents": chain})
}
/// `midas sessions run`: the supervisor. Starts the runner proper as its child,
/// with the same arguments, and starts it again whenever it ends: at once after a
/// stop the runner wrote down itself, after a pause that grows while it keeps
/// ending within a minute. A signal to the supervisor stops both.
pub fn supervise(name: &str) -> anyhow::Result<i32> {
// SAFETY: ignoring SIGPIPE: a closed log must not end the process keeping the runner up.
unsafe { libc::signal(libc::SIGPIPE, libc::SIG_IGN) };
let stopping = std::sync::Arc::new(std::sync::atomic::AtomicI32::new(0));
let child = std::sync::Arc::new(std::sync::atomic::AtomicI32::new(0));
{
let (stopping, child, name) = (stopping.clone(), child.clone(), name.to_string());
take_stop_signals(move |sig, pid| {
let mut ev = sender(pid);
ev["runner"] = json!(name);
ev["reason"] = json!("signal");
ev["signal"] = json!(signal_name(sig));
ev["sessions"] = json!(null);
ev["supervisor"] = json!(true);
events::emit("runner_stopped", ev);
crate::util::log_line(&format!("{name}: {} from pid {pid}: stopping the runner and its supervisor", signal_name(sig)));
stopping.store(sig, Ordering::SeqCst);
let c = child.load(Ordering::SeqCst);
if c > 0 {
// SAFETY: the stop passed on to our own child.
unsafe { libc::kill(c, sig) };
}
});
}
let build = crate::sessions::Build::now();
// A runner from before this supervisor that started again on a new build becomes one: its
// first child is a start for that build, and the agents it names are not the child's to wait for.
let mut by = if std::env::var_os(crate::sessions::ORPHANS_ENV).is_some() { "build".to_string() }
else { std::env::var(STARTED_BY_ENV).unwrap_or_else(|_| "hand".into()) };
std::env::remove_var(crate::sessions::ORPHANS_ENV);
let mut quick = 0u32;
// A supervisor started again on a new build keeps the child it had.
let mut adopted: Option<i32> = std::env::var(ADOPT_ENV).ok().and_then(|p| p.parse().ok());
std::env::remove_var(ADOPT_ENV);
loop {
// Stopped while it waited to start the runner again: nothing to start.
if stopping.load(Ordering::SeqCst) != 0 {
return Ok(0);
}
let started = Instant::now();
let pid = match adopted.take() {
Some(pid) => pid,
None => {
let spawned = Command::new(&build.path).args(std::env::args_os().skip(1))
.env(CHILD_ENV, "1").env(STARTED_BY_ENV, &by).spawn();
match spawned {
Ok(c) => c.id() as i32,
Err(e) => {
crate::util::log_line(&format!("{name}: could not start the runner: {e}"));
std::thread::sleep(Duration::from_secs(30));
continue;
}
}
}
};
child.store(pid, Ordering::SeqCst);
let status = loop {
let mut st: libc::c_int = 0;
// Any child, without blocking: the runner, or an agent left by the runner this
// process was before it became a supervisor, which nobody else waits for.
// SAFETY: waitpid on our own children, without blocking.
let rc = unsafe { libc::waitpid(-1, &mut st, libc::WNOHANG) };
if rc == pid {
break Some(st);
}
if rc > 0 {
continue;
}
if rc < 0 {
break None;
}
// A new build: this supervisor starts again on it, keeping its child (`ADOPT_ENV`).
if build.replaced() && stopping.load(Ordering::SeqCst) == 0 {
use std::os::unix::process::CommandExt;
let e = Command::new(&build.path).args(std::env::args_os().skip(1)).env(ADOPT_ENV, pid.to_string()).exec();
crate::util::log_line(&format!("{name}: the supervisor could not start again on the new build: {e}"));
}
std::thread::sleep(Duration::from_millis(500));
};
child.store(0, Ordering::SeqCst);
if stopping.load(Ordering::SeqCst) != 0 {
return Ok(0);
}
let lived = started.elapsed();
// How it ended: a signal it could not catch (SIGKILL, a crash) it never wrote down.
match status {
Some(st) if libc::WIFSIGNALED(st) => {
let sig = libc::WTERMSIG(st);
events::emit("runner_stopped", json!({"runner": name, "reason": "killed", "signal": signal_name(sig),
"lived_s": lived.as_secs(), "seen_by": "supervisor"}));
crate::util::log_line(&format!("{name}: the runner died of {} after {} s; starting it again", signal_name(sig), lived.as_secs()));
}
Some(st) if libc::WIFEXITED(st) && libc::WEXITSTATUS(st) == 0 => {
events::emit("runner_stopped", json!({"runner": name, "reason": "exit", "code": 0, "lived_s": lived.as_secs(), "seen_by": "supervisor"}));
crate::util::log_line(&format!("{name}: the runner ended by itself after {} s; starting it again", lived.as_secs()));
}
// A stop it wrote down itself (a signal, a panic, an error).
Some(st) => crate::util::log_line(&format!("{name}: the runner ended (exit {}); starting it again", libc::WEXITSTATUS(st))),
None => crate::util::log_line(&format!("{name}: lost the runner (pid {pid}); starting another")),
}
quick = if lived < Duration::from_secs(60) { quick + 1 } else { 0 };
// The pause, in steps, so that a stop meanwhile is heard.
let pause = Instant::now() + Duration::from_secs(if quick > 0 { (1u64 << quick.min(6)).min(60) } else { 0 });
while Instant::now() < pause && stopping.load(Ordering::SeqCst) == 0 {
std::thread::sleep(Duration::from_millis(200));
}
by = "supervisor".into();
}
}
/// In the runner proper, before it starts any thread: a write to an agent gone is
/// an error, not its end; a stop signal and a panic are written down before it goes.
pub fn guard(name: &str) {
// SAFETY: ignoring SIGPIPE, so an agent gone is a write error (EPIPE), not our end.
unsafe { libc::signal(libc::SIGPIPE, libc::SIG_IGN) };
let me = name.to_string();
take_stop_signals(move |sig, pid| {
// Its supervisor passing a stop on has written it down already.
// SAFETY: getppid has no preconditions.
let parent = unsafe { libc::getppid() } as u32;
if pid != parent || std::env::var_os(CHILD_ENV).is_none() {
let mut ev = sender(pid);
ev["runner"] = json!(me);
ev["reason"] = json!("signal");
ev["signal"] = json!(signal_name(sig));
ev["sessions"] = json!(SESSIONS.load(Ordering::SeqCst));
events::emit("runner_stopped", ev);
crate::util::log_line(&format!("{me}: stopped by {} from pid {pid}", signal_name(sig)));
}
std::process::exit(128 + sig);
});
let me = name.to_string();
let default = std::panic::take_hook();
std::panic::set_hook(Box::new(move |info| {
default(info);
let at = info.location().map(|l| format!("{}:{}", l.file(), l.line())).unwrap_or_default();
let msg = info.payload().downcast_ref::<&str>().map(|s| s.to_string())
.or_else(|| info.payload().downcast_ref::<String>().cloned()).unwrap_or_default();
let thread = std::thread::current().name().unwrap_or("").to_string();
// Only the main thread's panic ends the runner; a session's thread ends that session.
let kind = if thread == "main" { "runner_stopped" } else { "runner_panic" };
events::emit(kind, json!({"runner": me, "reason": "panic", "where": at, "message": crate::util::short(&msg, 300),
"thread": thread, "sessions": SESSIONS.load(Ordering::SeqCst)}));
}));
}
// ── The hub's side ───────────────────────────────────────────────────────────
/// Not asking for work this long, a runner is away. A poll waits at most twenty
/// seconds for something to give, and the runner asks again at once.
pub const AWAY_AFTER_S: i64 = 90;
#[derive(Default)]
struct Seen {
/// Its last poll.
polled: i64,
/// Since when it is away, once that is noticed.
away: Option<i64>,
}
fn seen() -> std::sync::MutexGuard<'static, BTreeMap<String, Seen>> {
static SEEN: Mutex<BTreeMap<String, Seen>> = Mutex::new(BTreeMap::new());
SEEN.lock().unwrap_or_else(|p| p.into_inner())
}
/// A runner asked for work (`POST /v1/hosted/runner/poll`).
pub fn polled(runner: &str) {
let now = crate::registry::now();
let back = {
let mut s = seen();
let r = s.entry(runner.to_string()).or_default();
r.polled = now;
r.away.take()
};
if let Some(since) = back {
events::emit("runner_back", json!({"runner": runner, "since": since, "away_s": now - since}));
}
}
/// Since when this runner is away, if it is.
pub fn away_since(runner: &str) -> Option<i64> {
seen().get(runner).and_then(|r| r.away)
}
/// The hub's watch over its runners, every fifteen seconds: one that stopped
/// asking is away, said once. Nobody is mailed: the host's watch timer starts it
/// again, and the page shows the time it was away.
pub fn watch() {
loop {
std::thread::sleep(Duration::from_secs(15));
for (name, since) in notice(crate::registry::now()) {
let sessions = live_sessions(&name);
events::emit("runner_away", json!({"runner": name, "since": since, "sessions": sessions}));
}
}
}
/// The runners newly away by `now`, each with since when.
type Noticed = Vec<(String, i64)>;
fn notice(now: i64) -> Noticed {
let mut gone = Vec::new();
for (name, r) in seen().iter_mut() {
if r.away.is_none() && now - r.polled >= AWAY_AFTER_S {
r.away = Some(r.polled);
gone.push((name.clone(), r.polled));
}
}
gone
}
/// The sessions a runner has that are live: started, at work, or waiting on the person.
fn live_sessions(runner: &str) -> usize {
crate::sessions::list().as_array().into_iter().flatten()
.filter(|m| m["runner"] == runner && is_live(m)).count()
}
pub fn is_live(m: &Value) -> bool {
matches!(m["status"].as_str(), Some("starting" | "working" | "waiting" | "needs_permission"))
}
/// Each runner now, for the board: whether it is away and since when.
pub fn board() -> Vec<Value> {
seen().iter().map(|(name, r)| json!({"kind": "runner", "id": name, "name": name, "away": r.away})).collect()
}
const KINDS: [&str; 5] = ["runner_started", "runner_stopped", "runner_away", "runner_back", "runner_panic"];
/// `GET /v1/runners?since=S`: every runner's starts, stops and absences in the
/// last `since` seconds, oldest first, and each one now. An absence with no stop
/// written down near its start is an *unexplained* stop: the runner and its
/// supervisor both went without a word (the machine, the container, SIGKILL to both).
pub fn read(since_s: i64) -> Value {
let f = events::Filter { since: chrono::Duration::seconds(since_s), kinds: KINDS.iter().map(|k| k.to_string()).collect(),
node: None, actor: None };
let evs = events::read(&f);
let ts = |e: &Value| e["ts"].as_str().and_then(|t| chrono::DateTime::parse_from_rfc3339(t).ok()).map_or(0, |t| t.timestamp());
let now = crate::registry::now();
let mut stops = Vec::new();
let mut starts = Vec::new();
let mut panics = Vec::new();
let mut away: Vec<Value> = Vec::new();
for e in &evs {
let mut x = e.clone();
x["at"] = json!(ts(e));
match e["kind"].as_str() {
Some("runner_stopped") => stops.push(x),
Some("runner_started") => starts.push(x),
Some("runner_panic") => panics.push(x),
Some("runner_away") => away.push(json!({"runner": e["runner"], "from": e["since"], "to": null, "sessions": e["sessions"]})),
Some("runner_back") => {
match away.iter_mut().rev().find(|a| a["runner"] == e["runner"] && a["to"].is_null()) {
Some(a) => a["to"] = json!(ts(e)),
// Away since before the range: its start is in the event.
None => away.push(json!({"runner": e["runner"], "from": e["since"], "to": ts(e), "sessions": null})),
}
}
_ => {}
}
}
// An absence that the runner's own record does not account for: shown as a stop of its own.
for a in &away {
let from = a["from"].as_i64().unwrap_or(0);
let to = a["to"].as_i64().unwrap_or(now);
let said = stops.iter().any(|s| s["runner"] == a["runner"] && s["at"].as_i64().is_some_and(|t| t >= from - 60 && t <= to));
if !said {
stops.push(json!({"runner": a["runner"], "reason": "unexplained", "at": from, "sessions": a["sessions"]}));
}
}
stops.sort_by_key(|s| s["at"].as_i64().unwrap_or(0));
let runners: Vec<Value> = seen().iter().map(|(name, r)| {
let up_since = starts.iter().rev().find(|s| s["runner"] == name.as_str()).and_then(|s| s["at"].as_i64());
json!({"name": name, "polled": r.polled, "away": r.away, "up_since": up_since, "sessions": live_sessions(name)})
}).collect();
json!({"now": now, "since": now - since_s, "runners": runners, "stops": stops, "starts": starts, "away": away, "panics": panics})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_runner_that_stops_asking_is_away_once_and_back_when_it_asks() {
let name = "runner@test-away";
polled(name);
let t0 = seen()[name].polled;
let mine = |v: &Noticed| v.iter().filter(|(n, _)| n == name).count();
// Within the poll's wait: still there.
assert_eq!(mine(¬ice(t0 + AWAY_AFTER_S - 1)), 0);
assert_eq!(away_since(name), None);
// Past it: away since its last poll, said once.
assert_eq!(mine(¬ice(t0 + AWAY_AFTER_S)), 1);
assert_eq!(away_since(name), Some(t0));
assert_eq!(mine(¬ice(t0 + AWAY_AFTER_S + 15)), 0);
// It asks again: there, and away anew only after another silence.
polled(name);
assert_eq!(away_since(name), None);
}
#[test]
fn a_signal_reads_as_its_name() {
assert_eq!(signal_name(libc::SIGTERM), "SIGTERM");
assert_eq!(signal_name(libc::SIGPIPE), "SIGPIPE");
}
}