garage44.eu/jeroen/midas

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

.. /src/nodectl.rs

raw

//! `midas node status|start|stop|restart|logs|shell [<node>]`: the machine
//! owner's view of a node on this machine.
//!
//! `status` needs no sudo: the node's settings file and the process list are
//! readable by anyone, the firewall's state is a system service's, and the rest
//! comes from the hub. The others act as the node's own user, so they need root.
//! Without a name, the one node set up on this machine.

use std::fs;
use std::path::PathBuf;
use std::process::Command;

use anyhow::{anyhow, bail, Result};
use serde_json::Value;

use crate::setup::{self, NodeConf};

const MACOS: bool = cfg!(target_os = "macos");

/// The node named, or the only one set up here.
fn pick(node: Option<&str>) -> Result<NodeConf> {
    let name = match node {
        Some(n) => n.to_string(),
        None => {
            let mut here: Vec<String> = fs::read_dir("/etc/midas").into_iter().flatten().flatten()
                .filter_map(|e| {
                    let n = e.file_name().to_string_lossy().to_string();
                    n.strip_prefix("node-").and_then(|r| r.strip_suffix(".conf")).map(str::to_string)
                })
                .collect();
            here.sort();
            match here.len() {
                0 => bail!("no node is set up on this machine (sudo midas setup <node>)"),
                1 => here.remove(0),
                _ => bail!("more than one node here ({}): say which", here.join(", ")),
            }
        }
    };
    setup::stored(&name).ok_or_else(|| anyhow!("no node {name} set up on this machine"))
}

fn root() -> Result<()> {
    if unsafe { libc::geteuid() } != 0 {
        bail!("this acts as the node's own user: run it with sudo");
    }
    Ok(())
}

fn home(c: &NodeConf) -> PathBuf {
    if MACOS {
        PathBuf::from(format!("/Users/{}", c.user))
    } else {
        setup::passwd(&c.user).map(|(_, h)| h).unwrap_or_else(|| PathBuf::from(format!("/home/{}", c.user)))
    }
}

/// A command as the node's user (Linux: its systemd and podman reachable).
fn as_node(c: &NodeConf, prog: &str) -> Result<Command> {
    if MACOS {
        let p = setup::which(prog).ok_or_else(|| anyhow!("{prog} is not installed"))?;
        return Ok(crate::setup_macos::as_user(&c.user, &home(c), &p));
    }
    let (uid, h) = setup::passwd(&c.user).ok_or_else(|| anyhow!("no user {}", c.user))?;
    let mut cmd = setup::as_user(&c.user, uid, &h);
    cmd.arg(prog);
    Ok(cmd)
}

fn unit(c: &NodeConf) -> String {
    format!("midas-node-{}.service", c.node)
}

/// Is the node's container (or VM) running, from the process list.
fn running(c: &NodeConf) -> bool {
    let all = crate::procs::all();
    if MACOS {
        let vm = c.storage();
        all.iter().any(|p| p.cmd.contains("tart run") && p.cmd.contains(&vm))
    } else {
        let name = format!(" -n midas-node-{} ", c.node);
        all.iter().any(|p| p.cmd.starts_with("/usr/bin/conmon") && format!("{} ", p.cmd).contains(&name))
            || all.iter().any(|p| p.cmd.contains("conmon") && p.cmd.contains(&format!("midas-node-{}", c.node)))
    }
}

fn firewall_active(c: &NodeConf) -> bool {
    if MACOS {
        // Reading pf needs root; without it, say what can be said.
        setup::which("pfctl").and_then(|p| Command::new(p).args(["-a", &format!("com.apple/250.midas.{}", c.node), "-s", "rules"]).output().ok())
            .is_some_and(|o| o.status.success() && !o.stdout.is_empty())
    } else {
        Command::new("systemctl").args(["is-active", "--quiet", &setup::firewall_unit(&c.node)]).status()
            .is_ok_and(|s| s.success())
    }
}

pub fn status(node: Option<&str>) -> Result<i32> {
    let c = pick(node)?;
    let up = running(&c);
    let fw = firewall_active(&c);
    println!("node {} on this machine (user {}, hub {})", c.node, c.user, c.hub);
    println!("  {} {}", if up { "✓" } else { "✗" }, if up { "running" } else { "not running — sudo midas node start" });
    let fw_note = if MACOS && unsafe { libc::geteuid() } != 0 { " (with sudo to read pf)" } else { "" };
    println!("  {} firewall {}{}", if fw { "✓" } else { "✗" }, if fw { "in force" } else { "not loaded" }, fw_note);
    let st = crate::hub::request(&format!("http://{}", c.hub), "GET", "/v1/state", None).ok()
        .and_then(|(code, b)| (code == 200).then_some(b))
        .and_then(|b| serde_json::from_str::<Value>(&b).ok());
    let Some(st) = st else {
        println!("  ✗ the hub at {} does not answer — {}", c.hub, crate::setup::hub_unreachable(&c.hub));
        return Ok(1);
    };
    let Some(n) = st["nodes"].as_array().into_iter().flatten().find(|n| n["id"] == c.node.as_str()) else {
        println!("  ✗ the hub does not know {} (an agent adds it: midas nodes add)", c.node);
        return Ok(1);
    };
    let r = &n["reading"];
    match r["at"].as_i64() {
        Some(at) => {
            let age = crate::registry::now() - at;
            println!("  {} heartbeat {}", if age <= 180 { "✓" } else { "✗" }, crate::cli::ago(at));
            println!("  · midas {} · load {} · {} GB free{}",
                r["version"].as_str().unwrap_or("?"),
                r["load"].as_f64().map(|l| format!("{l:.1}")).unwrap_or("?".into()),
                r["disk_free"].as_u64().map(|d| (d / 1_000_000_000).to_string()).unwrap_or("?".into()),
                r["warm"].as_str().map(|w| format!(" · warm at {}", crate::util::sha8(w))).unwrap_or_default());
        }
        None => println!("  ✗ no heartbeat yet"),
    }
    if let Some(d) = n["drained"]["why"].as_str() {
        println!("  · out of the pool: {d}");
    } else if n["enabled"] == false {
        println!("  · out of the pool until its next heartbeat");
    }
    match st["leases"].get(&c.node) {
        Some(l) => println!("  · {} · since {}", crate::cli::holding(l),
            l["claimed_at"].as_i64().map(crate::cli::ago).unwrap_or_default()),
        None => println!("  · free"),
    }
    Ok(if up && fw { 0 } else { 1 })
}

pub fn control(node: Option<&str>, action: &str) -> Result<i32> {
    root()?;
    let c = pick(node)?;
    if MACOS {
        for kind in ["vm", "forward"] {
            let target = format!("system/{}", crate::setup_macos::label(kind, &c.node));
            let plist = format!("/Library/LaunchDaemons/{}.plist", crate::setup_macos::label(kind, &c.node));
            let args: Vec<&str> = match action {
                "stop" => vec!["bootout", &target],
                "start" => vec!["bootstrap", "system", &plist],
                _ => vec!["kickstart", "-k", &target],
            };
            let _ = Command::new("launchctl").args(&args).status();
        }
    } else {
        let st = as_node(&c, "systemctl")?.args(["--user", action, &unit(&c)]).status()?;
        if !st.success() {
            bail!("systemctl {action} failed");
        }
    }
    println!("node {}: {action}{}", c.node, match action { "stop" => "ped (until it is started again or the machine boots)", "start" => "ed", _ => "ed" });
    Ok(0)
}

pub fn logs(node: Option<&str>, follow: bool) -> Result<i32> {
    root()?;
    let c = pick(node)?;
    let st = if MACOS {
        let h = home(&c);
        let mut cmd = Command::new("tail");
        cmd.args(["-n", "100"]);
        if follow {
            cmd.arg("-f");
        }
        cmd.arg(h.join(format!("vm-{}.log", c.node))).arg(h.join(format!("forward-{}.log", c.node))).status()?
    } else {
        // As root: a system user's journal lives in the system journal, which
        // the user itself may not read.
        let mut cmd = Command::new("journalctl");
        cmd.arg(format!("_SYSTEMD_USER_UNIT={}", unit(&c))).args(["-n", "100", "--no-pager"]);
        if follow {
            cmd.arg("-f");
        }
        cmd.status()?
    };
    Ok(st.code().unwrap_or(1))
}

pub fn shell(node: Option<&str>) -> Result<i32> {
    root()?;
    let c = pick(node)?;
    if MACOS {
        bail!("a shell inside a macOS node goes over ssh, with a key the node accepts; there is no console shell yet");
    }
    let st = as_node(&c, "podman")?
        .args(["exec", "-it", "-u", "build", "-w", "/work/checkout", &format!("midas-node-{}", c.node), "bash"])
        .status()?;
    Ok(st.code().unwrap_or(1))
}