garage44.eu/jeroen/midas

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

.. /src/power.rs

raw

//! What each machine draws, over time.
//!
//! **On the machine** (`midas node power`, a root service `sudo midas setup`
//! installs next to the node): once a minute, the chip's power in watts, sent
//! to the hub. It runs on the machine itself and not in the node, because a VM
//! sees no power sensor, and because a node that is stopped should still be
//! counted for what its machine draws meanwhile. Where it comes from:
//!
//! * a Mac: `powermetrics` (root only), its "Combined Power (CPU + GPU + ANE)"
//!   averaged over the minute;
//! * Linux with an AMD APU (the Steam Deck): amdgpu's `power1_average`, the
//!   whole package, CPU and GPU;
//! * other Linux: RAPL's package energy counters, read twice a minute apart.
//!
//! None of these is what the wall socket sees: memory, disk, fans and the power
//! supply's loss come on top. A machine with none of them (a cloud VM) sends
//! nothing, and the service ends.
//!
//! **On the hub**: `POST /v1/power` from a machine's WireGuard address (the one
//! its nodes have), one line per sample in `power/YYYY-MM-DD.jsonl` (UTC days,
//! kept for good: some 90 kB a machine a day), and `GET /v1/power?since=&step=`
//! for the page — per machine, the average watts and the watt-hours of each
//! `step` seconds.

use std::collections::BTreeMap;
use std::fs::{self, OpenOptions};
use std::io::{BufRead, BufReader, Write};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};

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

use crate::registry;

/// How often a machine reports.
pub const INTERVAL_S: u64 = 60;
/// A sample stands for the time to the next one, but not longer than this: a
/// longer gap is a machine asleep or off, and counts as nothing drawn.
const MAX_SPAN_S: i64 = 2 * INTERVAL_S as i64;
/// Where setup puts the midas the service runs, so a later `cargo build` of the
/// owner's checkout does not change it underfoot.
pub const BIN: &str = "/var/lib/midas/power/midas";

// ── On the machine ───────────────────────────────────────────────────────────

/// `midas node power --hub http://ADDR:PORT`: report until stopped.
pub fn report(hub: &str) -> Result<i32> {
    let hub = if hub.starts_with("http://") { hub.to_string() } else { format!("http://{hub}") };
    if cfg!(target_os = "macos") {
        // powermetrics fails now and then (another one running, a wake from sleep): start it again.
        let h = hub.clone();
        std::thread::spawn(move || loop {
            if let Err(e) = powermetrics(&h) {
                eprintln!("midas power: {e:#}; again in a minute");
            }
            std::thread::sleep(Duration::from_secs(INTERVAL_S));
        });
        // And the VMs, stopped while nobody uses them (sleep.rs).
        let mut asked = std::collections::HashMap::new();
        loop {
            crate::sleep::follow(&hub, &mut asked);
            std::thread::sleep(Duration::from_secs(crate::sleep::POLL_S));
        }
    }
    let mut rapl = Rapl::default();
    let mut sent = false;
    loop {
        let start = Instant::now();
        match linux_watts(&mut rapl) {
            Some((w, source)) => {
                send(&hub, w, source);
                sent = true;
            }
            // Ends cleanly, so systemd does not start it again.
            None if !sent && rapl.none() => {
                eprintln!("midas power: this machine has no power sensor midas can read (amdgpu, RAPL); nothing to report");
                return Ok(0);
            }
            // RAPL's first reading, which only primes it, or a read that failed.
            None => {}
        }
        std::thread::sleep(Duration::from_secs(INTERVAL_S).saturating_sub(start.elapsed()));
    }
}

fn send(hub: &str, w: f64, source: &str) {
    let body = json!({"w": (w * 100.0).round() / 100.0, "source": source, "interval_s": INTERVAL_S}).to_string();
    match crate::hub::request(hub, "POST", "/v1/power", Some(&body)) {
        Ok((204, _)) => {}
        Ok((code, text)) => eprintln!("midas power: the hub answered {code}: {}", text.trim()),
        Err(e) => eprintln!("midas power: the hub did not answer: {e:#}"),
    }
}

/// One powermetrics run, sampling every minute, sending each sample.
fn powermetrics(hub: &str) -> Result<()> {
    let mut child = Command::new("/usr/bin/powermetrics")
        .args(["--samplers", "cpu_power,gpu_power,ane_power", "-i", &(INTERVAL_S * 1000).to_string()])
        .stdout(Stdio::piped())
        .stderr(Stdio::inherit())
        .spawn()
        .context("starting powermetrics")?;
    let out = child.stdout.take().context("powermetrics' output")?;
    let mut p = Powermetrics::default();
    for line in BufReader::new(out).lines() {
        if let Some(w) = p.line(&line?) {
            send(hub, w, "powermetrics");
        }
    }
    let status = child.wait()?;
    bail!("powermetrics ended ({status})")
}

/// powermetrics' text, a sample at a time. Each sample says "Combined Power
/// (CPU + GPU + ANE): N mW"; an older one has only the parts, which are added
/// up when the next sample begins.
#[derive(Default)]
pub struct Powermetrics {
    parts: Option<f64>,
    combined: bool,
}

impl Powermetrics {
    /// Watts, when a line completes a sample.
    pub fn line(&mut self, line: &str) -> Option<f64> {
        let l = line.trim();
        if l.starts_with("*** Sampled system activity") {
            let parts = self.parts.take();
            let had = std::mem::replace(&mut self.combined, false);
            return parts.filter(|_| !had).map(|mw| mw / 1000.0);
        }
        let mw = |rest: &str| rest.trim().strip_suffix("mW").and_then(|v| v.trim().parse::<f64>().ok());
        if let Some(rest) = l.strip_prefix("Combined Power (CPU + GPU + ANE):") {
            let v = mw(rest)?;
            self.combined = true;
            self.parts = None;
            return Some(v / 1000.0);
        }
        for p in ["CPU Power:", "GPU Power:", "ANE Power:"] {
            if let Some(v) = l.strip_prefix(p).and_then(mw) {
                if !self.combined {
                    self.parts = Some(self.parts.unwrap_or(0.0) + v);
                }
            }
        }
        None
    }
}

/// RAPL's package counters (µJ, wrapping at their range) and when each was read.
#[derive(Default)]
struct Rapl {
    last: Option<(Instant, Vec<(PathBuf, u64)>)>,
    checked: bool,
    found: bool,
}

impl Rapl {
    fn none(&self) -> bool {
        self.checked && !self.found
    }
    fn packages() -> Vec<PathBuf> {
        let Ok(rd) = fs::read_dir("/sys/class/powercap") else { return vec![] };
        let mut out: Vec<PathBuf> = rd.flatten().map(|e| e.path())
            .filter(|p| {
                let n = p.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
                // The top level (intel-rapl:0), not its subzones (intel-rapl:0:0); AMD's driver uses the same names.
                n.matches(':').count() == 1
                    && fs::read_to_string(p.join("name")).is_ok_and(|t| t.trim().starts_with("package"))
            })
            .collect();
        out.sort();
        out
    }
    /// Watts since the last call, or None the first time.
    fn watts(&mut self) -> Option<f64> {
        let read = |p: &Path, f: &str| fs::read_to_string(p.join(f)).ok().and_then(|t| t.trim().parse::<u64>().ok());
        let now: Vec<(PathBuf, u64)> = Self::packages().into_iter()
            .filter_map(|p| read(&p, "energy_uj").map(|e| (p, e)))
            .collect();
        self.checked = true;
        if now.is_empty() {
            return None;
        }
        self.found = true;
        let at = Instant::now();
        let prev = self.last.replace((at, now.clone()));
        let (then, before) = prev?;
        let secs = at.duration_since(then).as_secs_f64();
        if secs < 1.0 {
            return None;
        }
        let mut uj = 0u64;
        for (p, e) in &now {
            let Some((_, b)) = before.iter().find(|(q, _)| q == p) else { continue };
            uj += if e >= b { e - b } else { read(p, "max_energy_range_uj").unwrap_or(0).saturating_sub(*b) + e };
        }
        Some(uj as f64 / 1e6 / secs)
    }
}

/// amdgpu's package power on an APU, else RAPL's.
fn linux_watts(rapl: &mut Rapl) -> Option<(f64, &'static str)> {
    if let Some(w) = amdgpu_watts() {
        return Some((w, "amdgpu"));
    }
    rapl.watts().map(|w| (w, "rapl"))
}

/// The hwmon of an amdgpu that shares the machine's memory (an APU: little or
/// no VRAM of its own), whose power is the whole package's. A discrete card's
/// is only the card's, so it is not taken for the machine.
fn amdgpu_watts() -> Option<f64> {
    for e in fs::read_dir("/sys/class/hwmon").ok()?.flatten() {
        let p = e.path();
        if fs::read_to_string(p.join("name")).map(|n| n.trim() != "amdgpu").unwrap_or(true) {
            continue;
        }
        let vram: u64 = fs::read_to_string(p.join("device/mem_info_vram_total")).ok()
            .and_then(|t| t.trim().parse().ok()).unwrap_or(0);
        if vram > 4 << 30 {
            continue;
        }
        for f in ["power1_average", "power1_input"] {
            if let Some(uw) = fs::read_to_string(p.join(f)).ok().and_then(|t| t.trim().parse::<f64>().ok()) {
                return Some(uw / 1e6);
            }
        }
    }
    None
}

/// Put this midas where the service runs it: written beside, then renamed,
/// so a running service keeps the file it has open.
pub fn place_binary() -> Result<()> {
    let me = std::env::current_exe().context("finding this midas")?;
    let bin = Path::new(BIN);
    fs::create_dir_all(bin.parent().unwrap())?;
    let tmp = bin.with_extension("new");
    fs::copy(&me, &tmp).context("copying midas for the power service")?;
    fs::set_permissions(&tmp, std::os::unix::fs::PermissionsExt::from_mode(0o755))?;
    fs::rename(&tmp, bin)?;
    Ok(())
}

/// The systemd unit on a Linux machine. Root, for RAPL's counters; nothing else.
pub fn unit(hub: &str) -> String {
    format!(
        "# Written by `midas setup`: this machine's power, to the hub once a minute (power.rs).\n\
         [Unit]\nDescription=midas: report this machine's power to the hub\n\
         After=network-online.target\nWants=network-online.target\n\n\
         [Service]\nExecStart={BIN} node power --hub http://{hub}\nRestart=on-failure\nRestartSec=60\n\
         NoNewPrivileges=yes\nProtectSystem=strict\nProtectHome=yes\nPrivateTmp=yes\nPrivateDevices=yes\n\
         ProtectKernelTunables=yes\nProtectKernelModules=yes\nProtectControlGroups=yes\nCapabilityBoundingSet=\n\
         RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX\nMemoryMax=64M\n\n\
         [Install]\nWantedBy=multi-user.target\n"
    )
}

pub const UNIT: &str = "midas-power.service";

// ── On the hub ───────────────────────────────────────────────────────────────

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

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"))
}

/// The machine whose nodes have this WireGuard address.
pub fn machine_at(peer: &str) -> Option<String> {
    registry::nodes().into_iter()
        .find(|n| n["address"].as_str() == Some(peer))
        .and_then(|n| n["machine"].as_str().map(str::to_string))
}

/// `POST /v1/power`: a machine's sample.
pub fn record(peer: &str, body: &Value) -> Result<(u16, Value)> {
    let Some(machine) = machine_at(peer) else {
        return Ok((403, json!({"error": format!("{peer} is no machine of the workspace's")})));
    };
    let Some(w) = body["w"].as_f64().filter(|w| w.is_finite() && *w >= 0.0 && *w < 5000.0) else {
        return Ok((400, json!({"error": "w: watts, a number"})));
    };
    let source = body["source"].as_str().unwrap_or("").chars().take(20).collect::<String>();
    let t = registry::now();
    append(t, &machine, w, &source)?;
    Ok((204, Value::Null))
}

fn append(t: i64, machine: &str, w: f64, source: &str) -> Result<()> {
    fs::create_dir_all(dir())?;
    let line = json!({"t": t, "m": machine, "w": w, "s": source});
    let mut f = OpenOptions::new().create(true).append(true).open(day_file(t))?;
    // One write, the line with its newline (builds.rs `append_to`).
    f.write_all(format!("{line}\n").as_bytes())?;
    Ok(())
}

/// The samples from `from` on, per machine, oldest first: (time, watts, source).
fn samples(from: i64, to: i64) -> BTreeMap<String, Vec<(i64, f64, String)>> {
    let mut out: BTreeMap<String, Vec<(i64, f64, String)>> = BTreeMap::new();
    let mut d = from - from.rem_euclid(86400);
    while d <= to {
        if let Ok(text) = fs::read_to_string(day_file(d)) {
            for v in text.lines().filter_map(|l| serde_json::from_str::<Value>(l).ok()) {
                let (Some(t), Some(m), Some(w)) = (v["t"].as_i64(), v["m"].as_str(), v["w"].as_f64()) else { continue };
                if t >= from && t <= to {
                    out.entry(m.to_string()).or_default().push((t, w, v["s"].as_str().unwrap_or("").to_string()));
                }
            }
        }
        d += 86400;
    }
    for s in out.values_mut() {
        s.sort_by_key(|x| x.0);
    }
    out
}

/// Per bucket of `step` seconds from `from`: (bucket start, average watts,
/// watt-hours). Each sample counts for the time to the next one, at most
/// `MAX_SPAN_S`, so a machine asleep or off adds nothing; the last counts until
/// `to`, as far. A bucket with no samples is left out.
pub fn buckets(samples: &[(i64, f64)], from: i64, to: i64, step: i64) -> Vec<(i64, f64, f64)> {
    let mut acc: BTreeMap<i64, (f64, f64)> = BTreeMap::new(); // bucket → (watt-seconds, seconds)
    for (i, (t, w)) in samples.iter().enumerate() {
        let end = samples.get(i + 1).map(|n| n.0).unwrap_or(to).min(t + MAX_SPAN_S);
        // A sample's span may cross into the next bucket: split it.
        let mut a = *t;
        while a < end {
            let b0 = from + (a - from).div_euclid(step) * step;
            let b = end.min(b0 + step);
            let e = acc.entry(b0).or_default();
            e.0 += w * (b - a) as f64;
            e.1 += (b - a) as f64;
            a = b;
        }
    }
    acc.into_iter()
        .filter(|(_, (_, s))| *s > 0.0)
        .map(|(b, (ws, s))| (b, ws / s, ws / 3600.0))
        .collect()
}

/// `GET /v1/power?since=S&step=T`: each machine's last sample (if from the
/// last three minutes) and its buckets.
pub fn read(since_s: i64, step_s: Option<i64>) -> Value {
    let to = registry::now();
    let since_s = since_s.clamp(3600, 366 * 86400);
    let step = step_s.unwrap_or(if since_s <= 2 * 86400 { 300 } else { 3600 }).clamp(60, 86400);
    let from = to - since_s;
    let mut machines = serde_json::Map::new();
    for (m, s) in samples(from - MAX_SPAN_S, to) {
        let last = s.last().cloned();
        let tw: Vec<(i64, f64)> = s.iter().map(|x| (x.0, x.1)).collect();
        let points: Vec<Value> = buckets(&tw, from, to, step).into_iter()
            .filter(|p| p.0 >= from - step)
            .map(|(b, w, wh)| json!([b, (w * 10.0).round() / 10.0, (wh * 100.0).round() / 100.0]))
            .collect();
        machines.insert(m, json!({
            "now": last.as_ref().filter(|l| to - l.0 <= 180).map(|l| json!({"w": l.1, "at": l.0})),
            "source": last.map(|l| l.2),
            "points": points,
        }));
    }
    json!({"from": from, "to": to, "step": step, "machines": machines})
}

/// `midas power`: what each machine draws now, and used the last day and week.
pub fn show(json_out: bool) -> Result<i32> {
    let week = crate::client::get("/v1/power?since=604800&step=3600")?;
    if json_out {
        println!("{}", serde_json::to_string_pretty(&week)?);
        return Ok(0);
    }
    let to = week["to"].as_i64().unwrap_or_else(registry::now);
    let ms = week["machines"].as_object().cloned().unwrap_or_default();
    if ms.is_empty() {
        println!("No machine reports its power yet: its owner runs `sudo midas setup <node>` again to start the service.");
        return Ok(0);
    }
    for (m, v) in ms {
        let pts = v["points"].as_array().cloned().unwrap_or_default();
        let wh = |since: i64| -> f64 {
            pts.iter().filter(|p| p[0].as_i64().unwrap_or(0) >= to - since).map(|p| p[2].as_f64().unwrap_or(0.0)).sum()
        };
        let now = v["now"]["w"].as_f64().map(|w| format!("{w:.1} W now")).unwrap_or_else(|| "not reporting".into());
        println!("{m}: {now} · last day {:.2} kWh (avg {:.1} W) · last week {:.2} kWh · from {}",
            wh(86400) / 1000.0, wh(86400) / 24.0, wh(7 * 86400) / 1000.0, v["source"].as_str().unwrap_or("?"));
    }
    println!("The chip's power (CPU, GPU), not the wall socket's.");
    Ok(0)
}

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

    #[test]
    fn powermetrics_gives_the_combined_power_of_each_sample() {
        let text = "*** Sampled system activity (Fri Nov 14 10:00:00 2026 +0100) (60000.12ms elapsed) ***\n\
                    \n**** Processor usage ****\n\nCPU Power: 1200 mW\nGPU Power: 300 mW\nANE Power: 0 mW\n\
                    Combined Power (CPU + GPU + ANE): 1500 mW\n\n**** GPU usage ****\n\nGPU HW active residency:   3.10%\n\
                    *** Sampled system activity (Fri Nov 14 10:01:00 2026 +0100) (60000.10ms elapsed) ***\n\
                    Combined Power (CPU + GPU + ANE): 4250 mW\n";
        let mut p = Powermetrics::default();
        let got: Vec<f64> = text.lines().filter_map(|l| p.line(l)).collect();
        assert_eq!(got, vec![1.5, 4.25]);
    }

    #[test]
    fn without_a_combined_line_the_parts_are_added_when_the_next_sample_starts() {
        let text = "*** Sampled system activity (a) ***\nCPU Power: 1000 mW\nGPU Power: 500 mW\n\
                    *** Sampled system activity (b) ***\n";
        let mut p = Powermetrics::default();
        let got: Vec<f64> = text.lines().filter_map(|l| p.line(l)).collect();
        assert_eq!(got, vec![1.5]);
    }

    #[test]
    fn energy_counts_each_sample_until_the_next_and_a_gap_as_nothing() {
        // 10 W for an hour, sampled each minute; then the machine sleeps for an hour; then 20 W for a minute.
        let mut s: Vec<(i64, f64)> = (0..60).map(|i| (i * 60, 10.0)).collect();
        s.push((7200, 20.0));
        let b = buckets(&s, 0, 7260, 3600);
        assert_eq!(b.iter().map(|x| x.0).collect::<Vec<_>>(), vec![0, 3600, 7200]);
        // The hour: 10 Wh.
        assert!((b[0].2 - 10.0).abs() < 1e-9, "{:?}", b[0]);
        assert!((b[0].1 - 10.0).abs() < 1e-9);
        // The last sample before the sleep stands for two minutes at most: one of them falls in the next hour.
        assert!((b[1].2 - 10.0 * 60.0 / 3600.0).abs() < 1e-9, "{:?}", b[1]);
        // After the sleep: one minute at 20 W, up to `to`.
        assert!((b[2].2 - 20.0 * 60.0 / 3600.0).abs() < 1e-9, "{:?}", b[2]);
        assert!((b[2].1 - 20.0).abs() < 1e-9);
    }

    #[test]
    fn a_span_across_a_bucket_edge_is_split() {
        let b = buckets(&[(250, 12.0), (310, 12.0)], 0, 370, 300);
        assert_eq!(b.iter().map(|x| x.0).collect::<Vec<_>>(), vec![0, 300]);
        assert!((b[0].2 - 12.0 * 50.0 / 3600.0).abs() < 1e-9);
        assert!((b[1].2 - 12.0 * 70.0 / 3600.0).abs() < 1e-9);
    }
}