//! A Mac node's VM shut down while nobody uses it, and started again when //! somebody waits for one. //! //! Measured on the mini (power.rs, 2026-11-15 to 19): 17 W all night with //! nobody building, because each idle macOS guest keeps a core busy (audiomxd //! ~75 %, configd ~40 %; `tart run --no-audio` still gives the guest a null //! speaker, and changed nothing). A VM that is not running costs nothing. //! //! **The hub decides** (`tick`, every 30 s): a node its machine says it can //! stop, free for `IDLE_S` — no lease, no ssh session, no bot, not drained, //! nobody waiting for it — is marked `asleep`. Anybody waiting who could take //! it, a lease, or a drain (an update needs the VM up) clears the mark. //! //! **The machine does it** (`midas node power`, as root, on the Mac): every //! 15 s it tells the hub which VMs it runs (`POST /v1/sleep`, from its own //! address) and is told which to keep running. It asks the guest to shut //! down (SIGUSR2 to `tart run`: `requestStop`, never a hard stop) and starts //! the launchd job again on the way back. The job restarts only a VM that //! failed (`KeepAlive` on an unsuccessful exit), so a shutdown asked for stays //! down. Waking costs the VM's boot and first heartbeat: a minute or two. //! //! An asleep node is out of the pool like an offline one (no heartbeat), but //! said as asleep, and not reported as a problem. Linux nodes are not stopped. use std::collections::HashSet; use anyhow::Result; use serde_json::{json, Map, Value}; use crate::events; use crate::registry::{self, Locked}; /// How long a node stays free before its VM is shut down: the person's choice, 2026-11-19. pub const IDLE_S: i64 = 3600; /// A machine that has not asked for this long is not answering for its VMs: /// its nodes are left running. const HOST_FRESH_S: i64 = 120; /// How often the machine asks. pub const POLL_S: u64 = 15; /// `POST /v1/sleep` from a machine: `{"vms": [node, …]}` → `{"nodes": {node: "run" | "sleep"}}`. pub fn host(peer: &str, body: &Value) -> Result<(u16, Value)> { let Some(machine) = crate::power::machine_at(peer) else { return Ok((403, json!({"error": format!("{peer} is no machine of the workspace's")}))); }; let mut reg = Locked::open()?; let mine: Vec = body["vms"].as_array().into_iter().flatten().filter_map(Value::as_str) .filter(|id| reg.node(id).is_some_and(|n| n["machine"] == machine.as_str())) .map(str::to_string) .collect(); if !reg.state["sleep_hosts"].is_object() { reg.state["sleep_hosts"] = json!({}); } reg.state["sleep_hosts"][&machine] = json!({"vms": mine, "at": registry::now()}); reg.mark(); reg.commit()?; let nodes: Map = mine.iter() .map(|id| (id.clone(), json!(if reg.node(id).is_some_and(|n| n["asleep"].is_object()) { "sleep" } else { "run" }))) .collect(); Ok((200, json!({"nodes": nodes}))) } /// Whether anything uses the node or wants it: what keeps it awake. fn in_use(reg: &Locked, n: &Value, t: i64) -> Option { let id = n["id"].as_str().unwrap_or(""); if let Some(l) = reg.leases().get(id) { return Some(format!("held by {}", l["owner"].as_str().unwrap_or("?"))); } if n["drained"].is_object() { return Some("drained".into()); } if let Some((who, _)) = reg.waiters().iter().find(|(_, w)| registry::wants(w, n)) { return Some(format!("{who} waits for a node")); } // What the node said last, if it said it lately: an asleep node's last word is old. let r = registry::reading(id).filter(|r| r["at"].as_i64().is_some_and(|a| t - a <= 180)); if r.as_ref().is_some_and(|r| r["sessions"].as_u64().unwrap_or(0) > 0) { return Some("an ssh session is open".into()); } if r.as_ref().is_some_and(|r| r["bot"]["running"] == true) { return Some("a bot runs".into()); } None } /// The hub's half, every 30 s: mark nodes free for an hour asleep, and wake /// the ones something wants. pub fn tick() -> Result<()> { let mut reg = Locked::open()?; let t = registry::now(); let can_sleep: HashSet = reg.state["sleep_hosts"].as_object().into_iter().flatten() .filter(|(_, h)| h["at"].as_i64().is_some_and(|a| t - a <= HOST_FRESH_S)) .flat_map(|(_, h)| h["vms"].as_array().cloned().unwrap_or_default()) .filter_map(|v| v.as_str().map(str::to_string)) .collect(); if !reg.state["sleep"].is_object() { reg.state["sleep"] = json!({}); } let mut changed = false; let mut said: Vec<(&str, Value)> = Vec::new(); for n in reg.nodes().clone() { let id = n["id"].as_str().unwrap_or("").to_string(); let asleep = n["asleep"].is_object(); if !can_sleep.contains(&id) { // Nobody on the machine to wake it: never leave it marked asleep. if asleep { wake(&mut reg, &id); said.push(("node_wake", json!({"node": id, "why": "its machine stopped asking"}))); changed = true; } continue; } let busy = in_use(®, &n, t); let free_since = reg.state["sleep"][&id]["free_since"].as_i64(); match busy { Some(why) => { if free_since.is_some() { reg.state["sleep"].as_object_mut().unwrap().remove(&id); changed = true; } if asleep { wake(&mut reg, &id); said.push(("node_wake", json!({"node": id, "why": why}))); changed = true; } } None => { let Some(since) = free_since else { reg.state["sleep"][&id] = json!({"free_since": t}); changed = true; continue; }; if !asleep && n["enabled"] == true && t - since >= IDLE_S { if let Some(o) = reg.node_mut(&id) { o["asleep"] = json!({"since": t}); } said.push(("node_sleep", json!({"node": id, "why": format!("free for {} min", (t - since) / 60)}))); changed = true; } } } } if changed { reg.mark(); reg.commit()?; } for (kind, ev) in said { events::emit(kind, ev); } Ok(()) } fn wake(reg: &mut Locked, id: &str) { if let Some(o) = reg.node_mut(id).and_then(Value::as_object_mut) { o.remove("asleep"); } } // ── On the machine ─────────────────────────────────────────────────────────── /// The machine's half (macOS): keep each VM's launchd job as the hub says. /// `asked` remembers when a shutdown was asked for, so it is not asked again /// every 15 s while the guest shuts down. pub fn follow(hub: &str, asked: &mut std::collections::HashMap) { let vms: Vec = crate::setup::all_stored().into_iter().map(|c| c.node).collect(); if vms.is_empty() { return; } let body = json!({"vms": vms}).to_string(); let answer = match crate::hub::request(hub, "POST", "/v1/sleep", Some(&body)) { Ok((200, text)) => serde_json::from_str::(&text).unwrap_or_default(), Ok((code, text)) => return eprintln!("midas sleep: the hub answered {code}: {}", text.trim()), Err(e) => return eprintln!("midas sleep: the hub did not answer: {e:#}"), }; for (node, want) in answer["nodes"].as_object().into_iter().flatten() { let label = crate::setup_macos::label("vm", node); let target = format!("system/{label}"); let print = std::process::Command::new("launchctl").args(["print", &target]).output(); let loaded = print.as_ref().is_ok_and(|o| o.status.success()); let running = print.as_ref().is_ok_and(|o| String::from_utf8_lossy(&o.stdout).contains("state = running")); match want.as_str() { Some("sleep") if running => { if asked.get(node).is_some_and(|at| at.elapsed().as_secs() < 300) { continue; } // `tart run` asks the guest to shut down on SIGUSR2; SIGTERM would stop it hard. let ok = std::process::Command::new("launchctl").args(["kill", "SIGUSR2", &target]).status() .is_ok_and(|s| s.success()); eprintln!("midas sleep: {node}: asked its VM to shut down{}", if ok { "" } else { " — launchctl kill failed" }); asked.insert(node.clone(), std::time::Instant::now()); } Some("run") if !running => { asked.remove(node); let ok = if loaded { std::process::Command::new("launchctl").args(["kickstart", &target]).status() } else { std::process::Command::new("launchctl") .args(["bootstrap", "system", &format!("/Library/LaunchDaemons/{label}.plist")]).status() }.is_ok_and(|s| s.success()); eprintln!("midas sleep: {node}: started its VM{}", if ok { "" } else { " — launchctl failed" }); } _ => {} } } }