garage44.eu/jeroen/midas

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

.. /src/conf.rs

raw

//! The hub's settings: `/etc/midas/hub.conf`, written by `sudo midas hub setup`.
//!
//! One small JSON file, readable by the hub's user. Everything else the hub
//! keeps (`/srv/midas`) is state it maintains itself.

use std::fs;
use std::path::Path;

use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};

pub const HUB_CONF: &str = "/etc/midas/hub.conf";

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct HubConf {
    /// Where the hub answers: its WireGuard address and port.
    pub listen: String,
    /// The git server the mirror is fetched from, e.g. `ssh://git@code.example.org:2222`.
    pub forgejo_ssh: String,
    /// Its API, for the Forgejo proxy, e.g. `https://code.example.org/api/v1`.
    pub forgejo_api: String,
    /// The repositories nodes may fetch, `owner/name`.
    pub repos: Vec<String>,
    /// The public keys agents log into nodes with.
    #[serde(default)]
    pub agent_keys: Vec<String>,
    /// What keeping a node warm means for this workspace.
    #[serde(default)]
    pub warm: Warm,
    /// What `midas deploy <target>` builds and where it publishes it, from
    /// before each project said its own (`Project::deploy`): read as the first
    /// repository's.
    #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
    pub deploy: std::collections::BTreeMap<String, Deploy>,
    /// An address the hub's owner is reached at, which Web Push services ask a
    /// sender to name (`push.rs`). Nothing is mailed to it: midas mails nobody.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub contact: Option<String>,
    /// Each project's own part of the shared workflow skills (`skills/`), by
    /// repository, `owner/name`: what its landing gates on. A session reads its
    /// project's with `midas project`.
    #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
    pub projects: std::collections::BTreeMap<String, Project>,
    /// What the hub does with a build of midas its own deploy published
    /// (`midas-self-update`, release.rs): `hub`, run its `hub setup` as root
    /// as it comes (the default, and how it was until 2026-11-21); `signed`,
    /// only with a good signature by the release key in
    /// `/etc/midas/release.pub`; `off`, never — somebody installs it by hand.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub self_update: String,
}

/// What the shared `finish-branch` skill needs to know about one project. The
/// commands are the project's, so they live in its repository and this only
/// names them: changing a gate is a commit, not an edit of this file.
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Default)]
pub struct Project {
    /// The gate: a shell command run on a build node, in the checkout, at the
    /// rebased head. Exit 0 passes. `MIDAS_BASE` is the commit the branch
    /// leaves main at, for a gate that scopes itself by the diff.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub gate: Option<String>,
    /// Which nodes may gate it, as for `midas take`: a machine's name, `gpu`
    /// or `any` (the default), the fastest free one for the gate first.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub gate_nodes: Option<String>,
    /// Run here, before the rebase and before the gate, with `MIDAS_BASE` set
    /// to `origin/<main>`: refuses what git cannot see clash (cartopolis: two
    /// branches claiming one migration number). Exit 0 passes.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pre_land: Option<String>,
    /// The branch landings go to (default `main`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub main: Option<String>,
    /// What `midas deploy <target>` builds of this project and where it
    /// publishes it, by target name. Names are the workspace's, not the
    /// project's: `midas deploy` takes a name alone, so two projects cannot
    /// both have one.
    #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
    pub deploy: std::collections::BTreeMap<String, Deploy>,
}

/// One deploy target, with the project it belongs to: what [`HubConf::targets`] lists.
#[derive(Clone, Debug, PartialEq)]
pub struct Target {
    pub name: String,
    /// `owner/name`.
    pub repo: String,
    /// The branch it deploys from: the project's `main`.
    pub branch: String,
    pub deploy: Deploy,
}

/// One thing the workspace deploys (`midas deploy <target>`): built on a node from a
/// commit on the warm branch, then published on this machine by root. Every
/// field here is the root-owned config's — nothing an agent or a node sends
/// can change where anything is published or what is run as whom.
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct Deploy {
    /// The nodes that may build it, as for `midas take`: a machine's name,
    /// `gpu` or `any`. It must be one whose binaries run on this machine.
    pub machine: String,
    /// Run in the node's checkout, at the commit, in order.
    pub steps: Vec<String>,
    /// What to take from the checkout and where to put it.
    pub publish: Vec<Publish>,
    /// Run on this machine first, as `prepare_user`, with `STAGED` (which it may
    /// change) and `SHA`: what only this machine may do to an artifact — sign
    /// it with a key that must never reach a node, say. What it leaves in
    /// `STAGED` is checked again for links before anything else reads it.
    #[serde(default)]
    pub prepare: Vec<String>,
    /// Who `prepare` runs as: a user that may read what it needs (a signing
    /// key) and nothing more. `nobody` if unset.
    #[serde(default)]
    pub prepare_user: Option<String>,
    /// Run on this machine before anything is replaced, as `check_user`, with
    /// `STAGED` the directory the artifacts are in (at their `from` paths) and
    /// `SHA` the commit. Any failing stops the deploy with the old one serving.
    #[serde(default)]
    pub checks: Vec<String>,
    /// Who the checks run as: the service's own user, so a check reads what
    /// the service reads. `nobody` if unset.
    #[serde(default)]
    pub check_user: Option<String>,
    /// Written last, with the time: what a `.path` unit restarts the service on.
    #[serde(default)]
    pub restart_stamp: Option<String>,
    /// Deployed by the hub after landings, in batches (`ship.rs`), rather than
    /// only when somebody asks.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub after_landing: bool,
    /// It restarts what the sessions at work use (midas itself: the hub and
    /// the sessions runner): after landings it is announced to them this many
    /// seconds before it is asked for, and any of them may put it off a while
    /// (`midas deploy --defer`, ship.rs). A person's own deploy goes at once.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub announce_s: Option<i64>,
    /// What it is built from, as git pathspecs (`crates/atlas/web`, `:!docs`):
    /// after landings, a tip that changes none of them since what it serves is
    /// not built again — what it serves is that tip's already (ship.rs). Empty:
    /// every landing builds it.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub paths: Vec<String>,
    /// Built after a landing only when the landing picks it (`land --targets`,
    /// ship.rs), or once no session is at work: the web client's build costs
    /// seven minutes of a node that most landings do not need to see live.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub optional: bool,
    /// What it must stay in step with, as git pathspecs: a landing that
    /// changes any of them builds it whatever it picks (a client and the
    /// server it talks to share the wire protocol, `crates/core`).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub required_by: Vec<String>,
    /// Where it goes among the targets one node builds for one commit: lower
    /// first, ties as they were asked for. What people wait to see goes first:
    /// the web page went live seven minutes after the APK built before it
    /// (2026-10-29), which is installed by hand and can wait.
    #[serde(default, skip_serializing_if = "is_zero")]
    pub order: i32,
    /// What the hub watches of it once it serves (watch.rs): its service's
    /// memory, CPU and restarts, and whether it answers. Unset: not watched.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub watch: Option<Watch>,
}

/// How a deployed target is watched (watch.rs), sampled once a minute.
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Default)]
pub struct Watch {
    /// The systemd unit that serves it (`cartopolis-sim.service`): active or
    /// not, memory, CPU and restarts, from `systemctl show`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub unit: Option<String>,
    /// Addresses that must answer below 400 (a health path), asked from here.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub probes: Vec<String>,
    /// Above this many MB of memory it is shown as in trouble.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub memory_mb: Option<u64>,
    /// More restarts than this in an hour, and it is shown as in trouble.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub restarts_per_h: Option<u64>,
}

fn is_zero(n: &i32) -> bool {
    *n == 0
}

/// One artifact: a file or a directory in the checkout, and where it goes. A
/// file replaces `to` atomically; a directory is synchronised into `to`.
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct Publish {
    pub from: String,
    pub to: String,
}

impl Deploy {
    /// The rules a recipe must keep, checked when it is used rather than when
    /// it is written, so a bad edit to hub.conf refuses one deploy and breaks
    /// nothing else.
    pub fn check(&self) -> anyhow::Result<()> {
        use anyhow::bail;
        if self.steps.is_empty() || self.publish.is_empty() {
            bail!("a deploy needs steps and something to publish");
        }
        for p in &self.publish {
            let rel = Path::new(&p.from);
            if p.from.is_empty() || rel.is_absolute() || p.from.starts_with('-')
                || rel.components().any(|c| !matches!(c, std::path::Component::Normal(_))) {
                bail!("publish.from is a plain path inside the checkout, not {:?}", p.from);
            }
            let to = Path::new(&p.to);
            if !to.is_absolute() || to.components().any(|c| matches!(c, std::path::Component::ParentDir)) || to == Path::new("/") {
                bail!("publish.to is an absolute path, not {:?}", p.to);
            }
        }
        if let Some(s) = &self.restart_stamp {
            if !Path::new(s).is_absolute() {
                bail!("restart_stamp is an absolute path, not {s:?}");
            }
        }
        Ok(())
    }
}

/// The warmer's work: check out `branch` of the first repository and run
/// `steps` in it, cheapest first, stopping at the first that fails; then the
/// `optional` ones, whose failure is logged and otherwise ignored (a node that
/// lacks a toolchain for one).
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct Warm {
    #[serde(default = "main_branch")]
    pub branch: String,
    #[serde(default)]
    pub steps: Vec<String>,
    #[serde(default)]
    pub optional: Vec<String>,
    /// Other steps for the nodes on a particular machine — a Mac builds the
    /// iOS target, not the Linux one. Keyed by machine name.
    #[serde(default)]
    pub machines: std::collections::BTreeMap<String, Steps>,
}

/// One machine's own warm steps.
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Default)]
pub struct Steps {
    #[serde(default)]
    pub steps: Vec<String>,
    #[serde(default)]
    pub optional: Vec<String>,
}

impl Warm {
    /// The steps for a node on `machine`.
    pub fn for_machine(&self, machine: &str) -> Steps {
        self.machines.get(machine).cloned()
            .unwrap_or_else(|| Steps { steps: self.steps.clone(), optional: self.optional.clone() })
    }
}

fn main_branch() -> String {
    "main".into()
}

impl Default for Warm {
    fn default() -> Self {
        Warm { branch: main_branch(), steps: vec![], optional: vec![], machines: Default::default() }
    }
}

impl Default for HubConf {
    /// Nothing about any particular network: `midas hub setup` asks for the
    /// rest the first time.
    fn default() -> Self {
        HubConf {
            listen: String::new(),
            forgejo_ssh: String::new(),
            forgejo_api: String::new(),
            repos: vec![],
            agent_keys: vec![],
            warm: Warm::default(),
            deploy: Default::default(),
            contact: None,
            projects: Default::default(),
            self_update: String::new(),
        }
    }
}

/// The hub's settings (empty where there is no file: only the hub reads them).
/// `MIDAS_HUB_CONF` names another file: a scratch hub of one's own, with projects (docs/development.md).
pub fn hub() -> HubConf {
    let path = std::env::var("MIDAS_HUB_CONF").ok().filter(|p| !p.is_empty()).unwrap_or_else(|| HUB_CONF.to_string());
    let mut c = read(Path::new(&path)).ok().flatten().unwrap_or_default();
    // The repositories the hub hosts itself are projects like any other
    // (hosted.rs): their landing is the hub's to write, not this file's — an
    // imported one's too, which this file may still name from its Forgejo days.
    // Their deploys are this file's alone: root publishes them, and root trusts
    // nothing the hub's user can write (docs/development.md, Security).
    if crate::registry::is_hub() {
        for (repo, r) in crate::hosted::repos() {
            if !c.repos.iter().any(|x| x.trim_end_matches(".git") == repo) {
                c.repos.push(repo.clone());
            }
            if let Ok(p) = serde_json::from_value::<Project>(r["project"].clone()) {
                let e = c.projects.entry(repo).or_default();
                (e.gate, e.gate_nodes, e.pre_land, e.main) = (p.gate, p.gate_nodes, p.pre_land, p.main);
            }
        }
    }
    c
}

pub fn read(path: &Path) -> Result<Option<HubConf>> {
    match fs::read_to_string(path) {
        Ok(t) => Ok(Some(serde_json::from_str(&t).with_context(|| format!("{} is not valid", path.display()))?)),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
        Err(e) => Err(e).with_context(|| format!("reading {}", path.display())),
    }
}

impl HubConf {
    /// `http://<listen>`: the address everything else reaches the hub on.
    pub fn url(&self) -> String {
        format!("http://{}", self.listen)
    }

    pub fn ip(&self) -> &str {
        self.listen.rsplit_once(':').map(|(ip, _)| ip).unwrap_or(&self.listen)
    }

    /// `owner/name.git`, the form the mirror and git clients use.
    pub fn allows(&self, repo_git: &str) -> bool {
        self.repos.iter().any(|r| format!("{}.git", r.trim_end_matches(".git")) == repo_git)
    }

    /// A project's settings, with what is unset filled in (`midas project`):
    /// `null` for a repository the hub does not mirror.
    pub fn project(&self, repo: &str) -> Option<serde_json::Value> {
        let repo = repo.trim_end_matches(".git");
        if !self.repos.iter().any(|r| r.trim_end_matches(".git") == repo) {
            return None;
        }
        let p = self.projects.get(repo).cloned().unwrap_or_default();
        let targets: Vec<serde_json::Value> = self.targets().into_iter().filter(|t| t.repo == repo)
            .map(|t| serde_json::json!({"target": t.name, "machine": t.deploy.machine, "after_landing": t.deploy.after_landing,
                                        "paths": t.deploy.paths, "optional": t.deploy.optional, "required_by": t.deploy.required_by}))
            .collect();
        Some(serde_json::json!({
            "repo": repo,
            // Where its git lives: the hub (hosted.rs), or Forgejo.
            "host": if crate::registry::is_hub() && crate::hosted::is_hosted(repo) { "midas" } else { "forgejo" },
            "gate": p.gate,
            "gate_nodes": p.gate_nodes.unwrap_or_else(|| "any".into()),
            "pre_land": p.pre_land,
            "main": p.main.unwrap_or_else(|| "main".into()),
            "deploy": targets,
        }))
    }

    /// The first repository, `owner/name`: the one nodes keep warm, and whose
    /// checkout is each node's own.
    pub fn first_repo(&self) -> Option<String> {
        self.repos.first().map(|r| r.trim_end_matches(".git").to_string())
    }

    /// Every deploy target in the workspace, each with its project: those of
    /// `projects`, and the old top-level `deploy` section as the first
    /// repository's. A project the hub does not mirror has none.
    pub fn targets(&self) -> Vec<Target> {
        let branch = |repo: &str| self.projects.get(repo).and_then(|p| p.main.clone()).unwrap_or_else(main_branch);
        let mut out = vec![];
        if let Some(first) = self.first_repo() {
            out.extend(self.deploy.iter().map(|(n, d)| Target { name: n.clone(), repo: first.clone(), branch: branch(&first), deploy: d.clone() }));
        }
        for (repo, p) in &self.projects {
            let repo = repo.trim_end_matches(".git");
            if !self.repos.iter().any(|r| r.trim_end_matches(".git") == repo) {
                continue;
            }
            out.extend(p.deploy.iter().map(|(n, d)| Target { name: n.clone(), repo: repo.to_string(), branch: branch(repo), deploy: d.clone() }));
        }
        out
    }

    /// One target by name; an error names the ones there are, or the projects
    /// that both claim it (which refuses that name until one is renamed).
    pub fn target(&self, name: &str) -> anyhow::Result<Target> {
        let mut found: Vec<Target> = self.targets().into_iter().filter(|t| t.name == name).collect();
        match found.len() {
            1 => Ok(found.remove(0)),
            0 => {
                let names: Vec<String> = self.targets().into_iter().map(|t| t.name).collect();
                anyhow::bail!("no deploy target {name:?} (hub.conf has {names:?})")
            }
            _ => {
                let repos: Vec<String> = found.into_iter().map(|t| t.repo).collect();
                anyhow::bail!("deploy target {name:?} is in more than one project ({}): rename one in hub.conf", repos.join(", "))
            }
        }
    }

    /// The projects deployed after landings, `owner/name`, the first repository's first.
    pub fn shipped_repos(&self) -> Vec<String> {
        let mut out: Vec<String> = vec![];
        for t in self.targets().into_iter().filter(|t| t.deploy.after_landing) {
            if !out.contains(&t.repo) {
                out.push(t.repo);
            }
        }
        out
    }
}

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

    #[test]
    fn a_deploy_recipe_publishes_only_from_the_checkout_to_absolute_places() {
        let ok = |from: &str, to: &str| Deploy {
            machine: "vps".into(), steps: vec!["cargo build".into()],
            publish: vec![Publish { from: from.into(), to: to.into() }],
            prepare: vec![], prepare_user: None, checks: vec![], check_user: None, restart_stamp: None, after_landing: false, announce_s: None, paths: vec![], optional: false, required_by: vec![], order: 0, watch: None,
        }.check().is_ok();
        assert!(ok("target/release/atlas", "/data/cartopolis/atlas/atlas"));
        assert!(ok("dist", "/data/cartopolis/site/viewer"));
        assert!(!ok("../etc/passwd", "/x"), "not out of the checkout");
        assert!(!ok("/etc/passwd", "/x"));
        assert!(!ok("target/../../x", "/x"), "nor out of it half-way");
        assert!(!ok("--files-from=x", "/x"), "nothing tar could read as an option");
        assert!(!ok("dist", "relative/place"));
        assert!(!ok("dist", "/"));
        assert!(!ok("dist", "/data/../etc"));
        let c: HubConf = serde_json::from_str(r#"{"listen": "10.44.0.1:4791", "forgejo_ssh": "", "forgejo_api": "", "repos": [],
            "deploy": {"sim": {"machine": "vps", "steps": ["cargo build"], "publish": [{"from": "a", "to": "/b"}]}}}"#).unwrap();
        assert_eq!(c.deploy["sim"].check_user, None);
    }

    #[test]
    fn a_project_says_what_it_gates_on_and_the_rest_is_filled_in() {
        let c: HubConf = serde_json::from_str(r#"{"listen": "", "forgejo_ssh": "", "forgejo_api": "",
            "repos": ["acme/cartopolis", "acme/midas"],
            "projects": {"acme/cartopolis": {"gate": "tools/verify-branch", "pre_land": "bun tools/check-numbers.ts"}}}"#).unwrap();
        let p = c.project("acme/cartopolis.git").unwrap();
        assert_eq!(p["gate"], "tools/verify-branch");
        assert_eq!(p["gate_nodes"], "any");
        assert_eq!(p["main"], "main");
        let m = c.project("acme/midas").unwrap();
        assert!(m["gate"].is_null(), "a mirrored project with nothing set has no gate, not an error");
        assert!(c.project("someone/else").is_none(), "nor is one the hub does not mirror a project");
        let back: HubConf = serde_json::from_str(&serde_json::to_string(&c).unwrap()).unwrap();
        assert_eq!(back, c, "`hub setup` writes the file back whole");
    }

    #[test]
    fn each_project_says_its_own_deploys_and_the_old_section_is_the_first_ones() {
        let c: HubConf = serde_json::from_str(r#"{"listen": "", "forgejo_ssh": "", "forgejo_api": "",
            "repos": ["acme/cartopolis", "acme/dardasha", "acme/midas"],
            "deploy": {"sim": {"machine": "vps", "steps": ["b"], "publish": [{"from": "a", "to": "/b"}], "after_landing": true}},
            "projects": {
                "acme/dardasha": {"main": "trunk", "deploy": {"dardasha": {"machine": "vps", "steps": ["b"], "publish": [{"from": "a", "to": "/c"}], "after_landing": true}}},
                "acme/midas": {"deploy": {"hub": {"machine": "vps", "steps": ["b"], "publish": [{"from": "a", "to": "/d"}]}}},
                "someone/else": {"deploy": {"x": {"machine": "vps", "steps": ["b"], "publish": [{"from": "a", "to": "/e"}]}}}
            }}"#).unwrap();
        let sim = c.target("sim").unwrap();
        assert_eq!((sim.repo.as_str(), sim.branch.as_str()), ("acme/cartopolis", "main"));
        let d = c.target("dardasha").unwrap();
        assert_eq!((d.repo.as_str(), d.branch.as_str()), ("acme/dardasha", "trunk"), "from the project's own main");
        assert!(c.target("x").is_err(), "a project the hub does not mirror deploys nothing");
        assert_eq!(c.shipped_repos(), ["acme/cartopolis", "acme/dardasha"], "midas's is by hand only");
        assert_eq!(c.project("acme/dardasha").unwrap()["deploy"][0]["target"], "dardasha");
        let mut twice = c.clone();
        twice.projects.get_mut("acme/midas").unwrap().deploy.insert("sim".into(), sim.deploy.clone());
        assert!(twice.target("sim").unwrap_err().to_string().contains("more than one project"));
    }

    #[test]
    fn a_machine_can_have_its_own_warm_steps() {
        let w: Warm = serde_json::from_str(r#"{"steps": ["cargo check"], "machines": {"mini": {"steps": ["cargo check --target aarch64-apple-ios"]}}}"#).unwrap();
        assert_eq!(w.branch, "main");
        assert_eq!(w.for_machine("mini").steps, vec!["cargo check --target aarch64-apple-ios"]);
        assert_eq!(w.for_machine("server").steps, vec!["cargo check"], "everyone else gets the common steps");
    }
}