From 5890e7335bbc4a111da1fd2063818551d9f95156 Mon Sep 17 00:00:00 2001 From: atlas Date: Sun, 22 Nov 2026 20:44:16 +0100 Subject: [PATCH] nix: render migrate.json and wrap swarmctl with kubectl --- nix/host-modules/k8s/default.nix | 4 +- nix/host-modules/k8s/migrate.nix | 141 ++++++++++++++++++++++++++ nix/host-modules/lib/paths-within.nix | 11 ++ nix/host-modules/swarm-nats.nix | 13 +++ nix/module-eval/k8s.nix | 123 ++++++++++++++++++++++ 5 files changed, 291 insertions(+), 1 deletion(-) create mode 100644 nix/host-modules/k8s/migrate.nix create mode 100644 nix/host-modules/lib/paths-within.nix diff --git a/nix/host-modules/k8s/default.nix b/nix/host-modules/k8s/default.nix index 57cb7bce7..3392ae4b6 100644 --- a/nix/host-modules/k8s/default.nix +++ b/nix/host-modules/k8s/default.nix @@ -1,6 +1,7 @@ # Kubernetes manifests for the swarm services this host deploys, rendered by # ./render.nix from their systemd units, and the per-service switch that moves -# a service between its host unit and the cluster (./runtime.nix). Rendering +# a service between its host unit and the cluster (./runtime.nix), and what +# `swarmctl migrate` reads of both (./migrate.nix). Rendering # alone changes no unit and applies nothing. docs/4-implementation/k8s/manifests.md # and runtime.md have the design. { @@ -24,6 +25,7 @@ in { imports = [ ./host-services.nix + ./migrate.nix ./node.nix ./pod-logs.nix ./runtime.nix diff --git a/nix/host-modules/k8s/migrate.nix b/nix/host-modules/k8s/migrate.nix new file mode 100644 index 000000000..429564de1 --- /dev/null +++ b/nix/host-modules/k8s/migrate.nix @@ -0,0 +1,141 @@ +# What `swarmctl migrate` reads of this host: `/etc/hyperhive/migrate.json`, and +# the environment that tells `swarmctl` which `kubectl` and kubeconfig to use. +# Imported by ./default.nix. docs/4-implementation/k8s/migrate.md has the design. +# +# The file has one entry per service that has a `runtime` option: the +# option's path, the runtime the configuration wants, the host units that run +# the service when it is on the host, and, where the service keeps state in a +# volume, that state: the claim, the mount in the pod, where the data lives +# on the host, and what a copy leaves out. Paths are computed here, never +# derived by `swarmctl`. Both exist only on a host with the node +# (./node.nix): without a cluster there is nothing to read. +{ + lib, + pkgs, + config, + ... +}: +let + cfg = config.services.hyperhive.k8s; + deployCfg = config.services.hyperhive.deploy; + node = deployCfg.k8s; + controllerCfg = deployCfg.swarm-controller; + natsCfg = deployCfg.nats; + + # The path of a unit's state directory in a pod, which ./render.nix mounts + # the claim at. + stateMount = unit: "/var/lib/${unit.serviceConfig.StateDirectory}"; + + pathsWithin = import ../lib/paths-within.nix { inherit lib; }; + + controllerStateDir = "/var/lib/swarm-controller"; + + # `option` is the service's name under `services.hyperhive.deploy`. `state` + # is null for a service with no state volume. `hostPath` is null where the + # copy has no source: the speech-to-text cache is not moved, and the pod + # starts with an empty one. + # + # The claim is `-state`, as ./render.nix and ../swarm-nats.nix name + # it. + stateTable = { + swarm-controller = { + option = "swarm-controller"; + state = { + mount = stateMount controllerCfg.unit; + hostPath = controllerStateDir; + # The pod issues its own leaf with its own store login, so a bao + # identity an operator keeps in this directory stays behind. + excludes = pathsWithin controllerStateDir [ + controllerCfg.baoClientCertFile + controllerCfg.baoClientKeyFile + ]; + }; + }; + swarm-nats = { + option = "nats"; + state = { + mount = natsCfg.storeDir; + hostPath = "/var/lib/nixos-containers/swarm-nats${natsCfg.storeDir}"; + excludes = [ ]; + }; + }; + swarm-notify-router = { + option = "notify-router"; + state = null; + }; + swarm-stt = { + option = "stt"; + state = { + mount = stateMount deployCfg.stt.unit; + hostPath = null; + excludes = [ ]; + }; + }; + swarm-review-classifier = { + option = "review-classifier"; + state = null; + }; + swarm-claude-login = { + option = "claude-login"; + state = null; + }; + swarm-ci-metrics = { + option = "ci-metrics"; + state = { + mount = stateMount deployCfg.ci-metrics.unit; + # A DynamicUser unit's state directory is under `private`, behind a + # symlink at the path the unit names. + hostPath = "/var/lib/private/swarm-ci-metrics"; + excludes = [ ]; + }; + }; + }; + + entry = + name: switch: + let + row = stateTable.${name}; + in + { + option = "services.hyperhive.deploy.${row.option}.runtime"; + inherit (switch) runtime; + hostUnits = lib.toList switch.hostUnit; + state = lib.mapNullable (s: s // { claim = "${name}-state"; }) row.state; + }; + + migrateJson = { + inherit (cfg) namespace; + services = lib.mapAttrs entry cfg.rendered.switches; + }; + + # The `swarmctl` wrapper's variables. The same `kubectl` that ./runtime.nix + # runs, with the cluster's admin kubeconfig. + kubeEnv = { + SWARMCTL_KUBECTL = "${pkgs.kubectl}/bin/kubectl"; + SWARMCTL_KUBECONFIG = "/etc/rancher/k3s/k3s.yaml"; + }; + + # `swarmctl` where the controller's module does not install one. + swarmctlKube = pkgs.symlinkJoin { + name = "swarmctl-kube"; + paths = [ deployCfg.swarm-controller.swarmctlPackage ]; + nativeBuildInputs = [ pkgs.makeWrapper ]; + postBuild = '' + wrapProgram $out/bin/swarmctl ${ + lib.concatStringsSep " " ( + lib.mapAttrsToList (name: value: "--set ${name} ${lib.escapeShellArg value}") kubeEnv + ) + } + ''; + }; +in +{ + config = lib.mkIf (node.enable && cfg.enable) { + environment.etc."hyperhive/migrate.json".text = builtins.toJSON migrateJson; + + # The controller module's wrapper carries these where the controller is + # enabled, which it stays at `runtime = "k8s"`. + services.hyperhive.deploy.swarm-controller.swarmctlEnvironment = kubeEnv; + environment.systemPackages = lib.mkIf (!controllerCfg.enable) [ swarmctlKube ]; + }; +} diff --git a/nix/host-modules/lib/paths-within.nix b/nix/host-modules/lib/paths-within.nix new file mode 100644 index 000000000..17e79e2ea --- /dev/null +++ b/nix/host-modules/lib/paths-within.nix @@ -0,0 +1,11 @@ +# `pathsWithin dir paths`: the entries of `paths` that sit under `dir`, relative +# to it. A null entry, and a path elsewhere (or `dir` itself), is left out. +{ lib }: +dir: paths: +lib.concatMap ( + path: + let + prefix = "${dir}/"; + in + lib.optional (path != null && lib.hasPrefix prefix path) (lib.removePrefix prefix path) +) paths diff --git a/nix/host-modules/swarm-nats.nix b/nix/host-modules/swarm-nats.nix index f390ea611..9126a38ff 100644 --- a/nix/host-modules/swarm-nats.nix +++ b/nix/host-modules/swarm-nats.nix @@ -1262,6 +1262,19 @@ in k8s.freshState = import ./lib/fresh-state-option.nix { inherit lib; } "nats"; + storeDir = lib.mkOption { + type = lib.types.str; + readOnly = true; + internal = true; + default = natsSystem.services.nats.settings.jetstream.store_dir; + description = '' + The JetStream store's directory inside the container, and the path the + pod mounts its volume at. The host's copy of it is this path under + `/var/lib/nixos-containers/swarm-nats`, which + ../host-modules/k8s/migrate.nix names for `swarmctl migrate`. + ''; + }; + unit = lib.mkOption { type = lib.types.raw; readOnly = true; diff --git a/nix/module-eval/k8s.nix b/nix/module-eval/k8s.nix index 78a67ae09..286af0ab0 100644 --- a/nix/module-eval/k8s.nix +++ b/nix/module-eval/k8s.nix @@ -271,6 +271,7 @@ let && usesSecret { projected.sources = [ { secret.name = "x"; } ]; } && !(usesSecret { projected.sources = [ { configMap.name = "x"; } ]; }); + migrateOf = c: builtins.fromJSON c.environment.etc."hyperhive/migrate.json".text; routerUnit = c: c.services.hyperhive.deploy.notify-router.unit; manifestNames = c: lib.sort lib.lessThan (lib.attrNames c.services.k3s.manifests); routerPrune = withNode.systemd.services.swarm-notify-router-k8s-prune; @@ -1854,6 +1855,128 @@ let && has "-t raw -A nixos-fw-nats -p tcp --dport 4222 -m addrtype --dst-type LOCAL -j DROP" onCluster.networking.firewall.extraCommands && has "-t raw -F nixos-fw-nats" onCluster.networking.firewall.extraStopCommands; } + { + # Each state block is read against what the render makes: the claim is + # the PVC's name and the mount is where the state gate looks. The + # stateless services are the control that an entry can carry no state. + name = "migrate.json names every service, with a state block exactly for the ones whose pod has a state volume"; + ok = + let + services = (migrateOf withNode).services; + stateful = [ + "swarm-controller" + "swarm-nats" + "swarm-stt" + "swarm-ci-metrics" + ]; + stateless = [ + "swarm-notify-router" + "swarm-review-classifier" + "swarm-claude-login" + ]; + objs = render withNode; + gateDir = + n: + let + o = objs."${n}/deployment" or objs."${n}/cronjob"; + spec = if o.kind == "CronJob" then o.spec.jobTemplate.spec.template.spec else o.spec.template.spec; + gate = lib.head (lib.filter (c: c.name == "state-gate") spec.initContainers); + in + (lib.head (lib.filter (e: e.name == "STATE_GATE_DIR") gate.env)).value; + in + lib.sort lib.lessThan (lib.attrNames services) == lib.sort lib.lessThan (stateful ++ stateless) + && lib.all ( + n: + let + s = services.${n}.state; + in + s != null + && s.claim == objs."${n}/persistentvolumeclaim".metadata.name + && s.mount == gateDir n + && s ? hostPath + && s ? excludes + ) stateful + && lib.all (n: services.${n}.state == null && !(objs ? "${n}/persistentvolumeclaim")) stateless + && lib.all (n: lib.hasPrefix "services.hyperhive.deploy." services.${n}.option) ( + lib.attrNames services + ); + } + { + name = "migrate.json gives the host path of each state, the host units of each service and the runtime the configuration wants"; + ok = + let + host = (migrateOf withNode).services; + cluster = (migrateOf onCluster).services; + in + (migrateOf withNode).namespace == "hyperhive" + && host.swarm-controller.state.hostPath == "/var/lib/swarm-controller" + && host.swarm-nats.state.hostPath == "/var/lib/nixos-containers/swarm-nats/var/lib/nats" + && host.swarm-nats.state.mount == "/var/lib/nats" + # A DynamicUser unit's data is under `private`. + && host.swarm-ci-metrics.state.hostPath == "/var/lib/private/swarm-ci-metrics" + && host.swarm-stt.state.hostPath == null + && + host.swarm-ci-metrics.hostUnits == [ + "swarm-ci-metrics.timer" + "swarm-ci-metrics.service" + ] + && host.swarm-nats.hostUnits == [ "container@swarm-nats.service" ] + && host.swarm-ci-metrics.option == "services.hyperhive.deploy.ci-metrics.runtime" + && lib.all (s: s.runtime == "host") (lib.attrValues host) + # The runtime follows the option: the cluster fixture has every one on k8s. + && lib.all (s: s.runtime == "k8s") (lib.attrValues cluster) + && cluster.swarm-nats.state == host.swarm-nats.state; + } + { + # A pure function, so the case needs no host of its own. A path inside the + # directory is the presence control; a path elsewhere, a null and the + # directory itself are left out. + name = "the controller's bao identity is excluded from its copy only where it sits in the state directory"; + ok = + let + within = import ../host-modules/lib/paths-within.nix { inherit lib; }; + dir = "/var/lib/swarm-controller"; + in + within dir [ + "/var/lib/swarm-controller/bao-client.pem" + "/var/lib/swarm-controller/sub/key.pem" + ] == [ + "bao-client.pem" + "sub/key.pem" + ] + && + within dir [ + "/var/lib/swarm-bao-pki/controller.pem" + null + dir + "/var/lib/swarm-controller-tls/x.pem" + ] == [ ] + # The module's own default puts them outside it. + && (migrateOf withNode).services.swarm-controller.state.excludes == [ ]; + } + { + name = "swarmctl is wrapped with kubectl and the cluster's kubeconfig, by one wrapper per host"; + ok = + let + env = c: c.services.hyperhive.deploy.swarm-controller.swarmctlEnvironment; + wrappers = + c: + map lib.getName ( + lib.filter (p: lib.hasPrefix "swarmctl-" (lib.getName p)) c.environment.systemPackages + ); + in + (env withNode).SWARMCTL_KUBECTL == "${pkgs.kubectl}/bin/kubectl" + && (env withNode).SWARMCTL_KUBECONFIG == "/etc/rancher/k3s/k3s.yaml" + # The controller's own wrapper carries them where the controller is + # enabled; elsewhere the k8s module installs one. + && wrappers withNode == [ "swarmctl-configured" ] + && wrappers nodeNoBridge == [ "swarmctl-kube" ] + # Without the node there is no cluster to name, though the manifests render. + && allLocal.services.hyperhive.k8s.enable + && !(env allLocal ? SWARMCTL_KUBECTL) + && !(allLocal.environment.etc ? "hyperhive/migrate.json") + && wrappers allLocal == [ "swarmctl-configured" ]; + } ]; in runGroup "k8s" cases