diff --git a/docs/2-handbook/swarm/services.md b/docs/2-handbook/swarm/services.md index ca2d2e314..9625be707 100644 --- a/docs/2-handbook/swarm/services.md +++ b/docs/2-handbook/swarm/services.md @@ -249,8 +249,9 @@ The notification router, in a `swarm-notify-router` container on the host that sets `deploy.notify-router.enable`. Run one: it handles each issue's events in order. It turns forge events (assigning an issue or pull request, closing it, a failed CI run on a pull request) into todos for the agents they concern, and an -agent that's down gets its todos when it's back. The flows and the delivery -path: +agent that's down gets its todos when it's back. Set +`deploy.notify-router.runtime = "k8s"` to run it as a pod in the host's cluster +instead of the container. The flows and the delivery path: [`notify-router.md`](../../4-implementation/swarm/notify-router.md), and [Host setup](../../4-implementation/swarm/notify-router.md#host-setup). diff --git a/docs/4-implementation/k8s/manifests.md b/docs/4-implementation/k8s/manifests.md index ccca880ef..95c74f572 100644 --- a/docs/4-implementation/k8s/manifests.md +++ b/docs/4-implementation/k8s/manifests.md @@ -6,8 +6,8 @@ the systemd unit each service runs today. A host with `services.hyperhive.k8s.enable` gets them as `system.build.k8sManifests`, a directory with one YAML file per object, and the images their pods run as `system.build.k8sImages`, which [the cluster node](node.md) loads. Rendering -changes no unit, and nothing in this module applies the manifests to a -cluster. +changes no unit. [The runtime switch](runtime.md) applies a service's manifests +to the cluster, when the service's `runtime` says `"k8s"`. ## Options @@ -77,9 +77,10 @@ A credential that holds a public CA file isn't a secret. `swarm-notify-router`'s `notify-router-bao-server-ca` comes from the ConfigMap `hyperhive-ca-trust`, key `bao-server-ca.pem`, and its trust bundles from the key `trust-bundle.pem`. The manifests only name the ConfigMap, because the hive CA exists only at -runtime, and nothing here creates it. A service with both kinds of credential -gets one projected volume that merges the Secret's keys and the ConfigMap's into -the credential directory. +runtime. [The runtime switch](runtime.md#what-k8s-changes) publishes it from the +host's files. A service with both kinds of credential gets one +projected volume that merges the Secret's keys and the ConfigMap's into the +credential directory. ## Pods diff --git a/docs/4-implementation/k8s/node.md b/docs/4-implementation/k8s/node.md index d7ade75dc..7f788aa72 100644 --- a/docs/4-implementation/k8s/node.md +++ b/docs/4-implementation/k8s/node.md @@ -38,7 +38,8 @@ The cluster starts with no hyperhive workload. Each service keeps running as its systemd unit, and nothing applies the services' manifests: two copies of `swarm-notify-router`, `swarm-ci-metrics` or `swarm-controller` would share one queue consumer, one cursor or one swarm. A service's objects go into the -cluster when that service moves in (see [`swarmctl migrate`](migrate.md)). +cluster when its `runtime` is `"k8s"` ([the runtime switch](runtime.md), which +[`swarmctl migrate`](migrate.md) drives). With the option off, the host's configuration is the one it has without the module. diff --git a/docs/4-implementation/k8s/runtime.md b/docs/4-implementation/k8s/runtime.md new file mode 100644 index 000000000..d5eb72220 --- /dev/null +++ b/docs/4-implementation/k8s/runtime.md @@ -0,0 +1,88 @@ +# Where a service runs: the runtime switch + +A swarm service with a `runtime` option runs in one of two places: as its host +unit, or as a pod in the host's cluster. `services.hyperhive.deploy..runtime` +is `"host"` (the default) or `"k8s"`. The service runs once per swarm, so the +option moves it and never copies it: the host unit and the pod never run +together, because they would share one queue consumer and one set of buckets. +`swarm-notify-router` has the option today, and the other services that run in +the cluster follow the same pattern. + +## Options + +- `services.hyperhive.deploy.notify-router.runtime` (default `"host"`). + `"k8s"` needs `services.hyperhive.deploy.k8s.enable` on the same host, and the + evaluation fails without it. + +With `"host"`, a host without [the cluster node](node.md) renders the same +configuration as before the option existed. With the node on and every service +on `"host"`, the cluster holds no service objects. + +## What `"k8s"` changes + +- **The host unit goes.** The configuration has no `swarm-notify-router` + container, no credential hand-ins for it and no journal forwarder for it. +- **The service's objects go in.** The [rendered manifests](manifests.md) reach + the cluster through `services.k3s.manifests`, one file per service plus the + namespace. The cluster applies a file when its link appears in the manifests + directory. +- **The pod reads the unit the container ran.** The unit comes from the + container's own configuration, evaluated on its own when the host has no + container, so the pod's environment is the unit's environment either way. +- **The host publishes the CA files.** `hyperhive-k8s-ca-trust.service` applies + the `hyperhive-ca-trust` ConfigMap from the host's files, with no manual step: + - `trust-bundle.pem`: the hive's trust bundle, where the gateway is + self-signed; + - `bao-server-ca.pem`: the secret store's server CA + (`deploy.bao.serverCaFile`). + + Both are public certificates. The unit waits for the cluster and for the + files, and a pod that mounts the ConfigMap waits in `ContainerCreating` until + the unit has run. A path unit watches both files and runs the unit again when + either changes, with no manual step. A running pod doesn't see a changed + trust bundle until it restarts, because the kubelet doesn't update `subPath` + mounts. + +## One copy at a time + +`switch-to-configuration` stops every unit the new configuration drops, and waits +for each stop, before it activates the new configuration. The activation links +the manifests. Switching to `"k8s"` therefore stops the container before the +cluster can apply the pod. + +The cluster doesn't delete what a manifest created after the manifest goes away, +and it keeps the file's link in its manifests directory. Switching back to +`"host"` therefore needs a step of its own. `-k8s-prune.service` belongs +to every configuration that has the node and the service on `"host"`, and the +service's host unit requires it and starts after it: + +1. If the manifest's link exists, rename it to `.yaml.pruning`, so the + cluster doesn't apply it again. The rename also records what remains to + delete. With no link, nothing went in, so the unit does nothing and needs no + cluster. +2. Wait for the cluster's API, then delete the service's Deployment, CronJob and + ServiceAccount (selected by `app.kubernetes.io/name`), and wait until its pods + have gone. A pod exits 0 within its termination grace period. +3. Delete the cluster's AddOn for the file, so that a later switch to `"k8s"` + applies the same manifest again. Then remove the renamed link. + +A failed step fails the unit, and the host unit doesn't start: the service stays +down and never doubles. A rerun resumes from the renamed link. Persistent volume +claims stay; `swarmctl migrate finish` deletes them. + +## State + +`swarm-notify-router` keeps nothing on the host. Its durable consumer on the +forge events stream and its `notify-router-state` bucket live in the queue, so a +switch in either direction copies nothing, and the router continues from the +consumer's position. + +## Validation + +`module-eval-k8s` checks that the host render with `"host"` holds the container, +no cluster manifests and no CA objects. With `"k8s"` it checks that no container +remains, that the manifests sit in `services.k3s.manifests`, and that the +evaluation refuses `"k8s"` without the node. The VM test `k8s-runtime-switch` +runs a router against the real secret store and a queue. It switches from the +host to the cluster and back, checks each step for exactly one copy, and asserts +that the pod logs in, routes an event, and exits 0 when deleted. diff --git a/docs/4-implementation/swarm/notify-router.md b/docs/4-implementation/swarm/notify-router.md index a2675abb1..2467e5999 100644 --- a/docs/4-implementation/swarm/notify-router.md +++ b/docs/4-implementation/swarm/notify-router.md @@ -441,6 +441,11 @@ that sets `deploy.notify-router.enable`. `allSwarmServices` defaults it on wherever the host has the router's store identity, on the review classifier's terms. Run one: it handles each issue's events in order. +With `deploy.notify-router.runtime = "k8s"` on a host that runs the cluster +(`deploy.k8s.enable`), the router runs as a pod and the host has no container. +The router keeps nothing on the host, so the switch copies nothing; see +[the runtime switch](../k8s/runtime.md). + swarm-controller keeps every `issues` and `pull_request` delivery, and every failed or cancelled CI run, from its instance-wide hooks in the `SWARM_EVENTS` stream. The router reads that diff --git a/nix/host-modules/deploy.nix b/nix/host-modules/deploy.nix index 291e36b69..66e1630e8 100644 --- a/nix/host-modules/deploy.nix +++ b/nix/host-modules/deploy.nix @@ -812,6 +812,9 @@ in unassigned, and cleared when the issue or pull request closes. Run it on one host: it handles each issue's events in order. + Set {option}`services.hyperhive.deploy.notify-router.runtime` to `k8s` + to run it as a pod in the host's cluster instead. + On by default where {option}`services.hyperhive.deploy.allSwarmServices` is set and this host has the router's store identity (the pair diff --git a/nix/host-modules/k8s/default.nix b/nix/host-modules/k8s/default.nix index 4f95d8118..57cb7bce7 100644 --- a/nix/host-modules/k8s/default.nix +++ b/nix/host-modules/k8s/default.nix @@ -1,7 +1,8 @@ # Kubernetes manifests for the swarm services this host deploys, rendered by -# ./render.nix from their systemd units. Rendering only: nothing here applies -# them or changes a unit. docs/4-implementation/k8s/manifests.md has the -# design. +# ./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 +# alone changes no unit and applies nothing. docs/4-implementation/k8s/manifests.md +# and runtime.md have the design. { pkgs, lib, @@ -25,6 +26,7 @@ in ./host-services.nix ./node.nix ./pod-logs.nix + ./runtime.nix ]; options.services.hyperhive.k8s = { @@ -39,7 +41,9 @@ in The manifests reference their Secrets by name only. Rendering only: the host's units stay as they are, and nothing - applies the manifests to a cluster. + applies the manifests to a cluster. A service with a `runtime` option + is applied when it says `k8s`, on a host with + {option}`services.hyperhive.deploy.k8s.enable`. ''; }; @@ -48,9 +52,26 @@ in default = "hyperhive"; description = "The Kubernetes namespace the rendered objects live in."; }; + + rendered = lib.mkOption { + type = lib.types.raw; + readOnly = true; + internal = true; + description = '' + What ./runtime.nix moves services with: each enabled service's + objects and switch, the namespace object, and the CA ConfigMap's name + and host files. + ''; + }; }; config = lib.mkIf cfg.enable { + services.hyperhive.k8s.rendered = { + inherit (rendered) caConfigMap caSources switches; + services = withoutContext rendered.services; + namespaceObject = withoutContext rendered.objects.namespace; + }; + # The images those pods run, for a node to load: ./node.nix. system.build.k8sImages = rendered.images; diff --git a/nix/host-modules/k8s/node.nix b/nix/host-modules/k8s/node.nix index 9f5d826f9..80f407b13 100644 --- a/nix/host-modules/k8s/node.nix +++ b/nix/host-modules/k8s/node.nix @@ -3,8 +3,8 @@ # all-local swarm. docs/4-implementation/k8s/node.md has the design. # # The node holds the images of the services ./render.nix renders and has no -# registry. No service's objects are applied: a service's host unit keeps -# running, and its objects go in when the service moves in. +# registry. No service's objects are applied until its `runtime` is `k8s` +# (./runtime.nix): until then its host unit runs. { config, lib, @@ -59,9 +59,10 @@ in that runs the swarm's services, which is the one `services.hyperhive.deploy.singleHostSwarm` names. - The cluster starts with no hyperhive workload: the services keep - running as systemd units. Its secrets are encrypted at rest, and - traefik and metrics-server stay off. Pods and services take their + The cluster starts with no hyperhive workload: a service keeps + running as its systemd unit unless its `runtime` option is `k8s`. + Its secrets are encrypted at rest, and traefik and metrics-server + stay off. Pods and services take their addresses from {option}`services.hyperhive.deploy.k8s.podCidr` and {option}`services.hyperhive.deploy.k8s.serviceCidr`. The firewall trusts the pod network's interfaces (`cni0`, `flannel.1`), so the node @@ -130,6 +131,17 @@ in tokens and the one that signs them, which differ after a rotation. ''; }; + + manifestDir = lib.mkOption { + type = lib.types.str; + readOnly = true; + internal = true; + default = "${dataDir}/server/manifests"; + description = '' + The directory k3s applies manifests from, which + {option}`services.k3s.manifests` links its files into. + ''; + }; }; config = lib.mkIf cfg.enable { diff --git a/nix/host-modules/k8s/render.nix b/nix/host-modules/k8s/render.nix index e2ac5f6a8..379ca2289 100644 --- a/nix/host-modules/k8s/render.nix +++ b/nix/host-modules/k8s/render.nix @@ -1,7 +1,8 @@ # The Kubernetes objects that run each in-cluster swarm service this host # deploys, read from that service's systemd unit as this host renders it. # Imported by ./default.nix, which writes the objects out as YAML. Returns -# `objects` and the `images` the pods run. +# `objects`, the `images` the pods run, and what ./runtime.nix moves services +# with. # # The pod takes the unit's environment, credential ids, state and runtime # directories, and timer. Every file the unit names is mounted at the path the @@ -26,12 +27,23 @@ let k8sCfg = hyperhiveCfg.k8s; baoDeployCfg = deployCfg.bao; podAuth = import ../lib/bao-pod-auth.nix; + caTrust = import ../lib/hive-ca-trust.nix { + inherit lib; + tlsCfg = deployCfg.hive-controller.tls; + gatewayCfg = hyperhiveCfg.gateway; + }; # The ConfigMap that holds the public CA files the pods trust, and its keys. # A CA certificate is public, so it travels as a ConfigMap, never a Secret. + # The file behind each key lives on the host: `caSources` names it, and + # ./runtime.nix publishes the ConfigMap from those files. caConfigMap = "hyperhive-ca-trust"; trustBundleKey = "trust-bundle.pem"; baoServerCaKey = "bao-server-ca.pem"; + caSources = { + ${trustBundleKey} = if caTrust.useSelfSigned then caTrust.caHostPath else null; + ${baoServerCaKey} = baoDeployCfg.serverCaFile; + }; # `serviceUser` is the user every image runs its daemon as. Mounted files are # group-owned by its group through `fsGroup`. @@ -61,6 +73,9 @@ let # /readyz listener; the controller serves /readyz on its unix socket only, # which the kubelet cannot probe. `publicCredentials` maps the ids of the # credentials that hold a public CA file to their key in the CA ConfigMap. + # `switch` is null for a service that always runs on the host, and for one + # with a `runtime` option names the option's value and the host unit that + # runs the service when it is `"host"`. services = { swarm-controller = { inherit (deployCfg.swarm-controller) enable package; @@ -69,14 +84,19 @@ let healthEnv = null; etcFiles = [ "hyperhive/swarm-controller.json" ]; publicCredentials = { }; + switch = null; }; swarm-notify-router = { inherit (deployCfg.notify-router) enable package; - unit = config.containers.swarm-notify-router.config.systemd.services.swarm-notify-router; + unit = deployCfg.notify-router.unit; kind = "Deployment"; healthEnv = "SWARM_NOTIFY_ROUTER_HEALTH_ADDR"; etcFiles = [ ]; publicCredentials.notify-router-bao-server-ca = baoServerCaKey; + switch = { + inherit (deployCfg.notify-router) runtime; + hostUnit = "container@swarm-notify-router.service"; + }; }; swarm-ci-metrics = { inherit (deployCfg.ci-metrics) enable package; @@ -86,6 +106,7 @@ let healthEnv = null; etcFiles = [ ]; publicCredentials = { }; + switch = null; }; }; @@ -544,4 +565,15 @@ in # The image each enabled service's pod runs: what a node has to hold, # since there is no registry to pull from. images = lib.mapAttrsToList (_: w: w.image) enabled; + + # What ./runtime.nix moves services with. `switches` holds the services that + # have a runtime option and is cheap to read: it names the units that a + # switch adds or removes, so it cannot depend on rendering a unit. `services` + # holds the objects. `caSources` is the host file behind each key of the CA + # ConfigMap, null where there is none. + switches = lib.mapAttrs (_: svc: svc.switch) ( + lib.filterAttrs (_: svc: svc.enable && svc.switch != null) services + ); + services = lib.mapAttrs (_: w: { inherit (w) objects; }) enabled; + inherit caConfigMap caSources; } diff --git a/nix/host-modules/k8s/runtime.nix b/nix/host-modules/k8s/runtime.nix new file mode 100644 index 000000000..0d9708119 --- /dev/null +++ b/nix/host-modules/k8s/runtime.nix @@ -0,0 +1,140 @@ +# Which of a service's two homes runs it: its host unit, or its objects in the +# cluster. A service with a `runtime` option (`swarm-notify-router`) is on the +# cluster when the option says `"k8s"`, and then only: its host unit is gone +# from the configuration, and its manifests are in `services.k3s.manifests`. +# The cluster does not remove what a manifest created once the manifest is +# gone, so a service back on the host has its objects deleted before its host +# unit starts. docs/4-implementation/k8s/runtime.md has the design. +{ + config, + lib, + pkgs, + ... +}: +let + cfg = config.services.hyperhive.k8s; + node = config.services.hyperhive.deploy.k8s; + rendered = cfg.rendered; + + onCluster = lib.filterAttrs (_: s: s.runtime == "k8s") rendered.switches; + onHost = lib.filterAttrs (_: s: s.runtime == "host") rendered.switches; + + kubectl = "${pkgs.kubectl}/bin/kubectl"; + kubeconfig = "/etc/rancher/k3s/k3s.yaml"; + + # Runs `command` until it succeeds, for at most `seconds`. + waitFor = seconds: description: command: '' + echo "waiting for ${description}" >&2 + timeout ${toString seconds} ${pkgs.bash}/bin/bash -c ${lib.escapeShellArg "until ${command}; do sleep 2; done"} + ''; + apiReady = waitFor 600 "the cluster's API" "${kubectl} get --raw /readyz >/dev/null 2>&1"; + + caFiles = lib.filterAttrs (_: path: path != null) rendered.caSources; +in +{ + config = lib.mkIf (node.enable && cfg.enable) ( + lib.mkMerge [ + (lib.mkIf (onCluster != { }) { + # The cluster applies each file of the manifests directory when it + # appears: a service's objects go in when its host unit has stopped, + # because `switch-to-configuration` stops every unit the new + # configuration drops before it activates the new configuration, and + # the files are linked in by the activation. + services.k3s.manifests = { + hyperhive-namespace.content = rendered.namespaceObject; + } + // lib.mapAttrs (name: _: { + content = lib.attrValues rendered.services.${name}.objects; + }) onCluster; + }) + + # The pods' CA files are public, so the host publishes them as they are. + # A pod waits in ContainerCreating until this has run. The unit has no + # `RemainAfterExit`, so the path unit below starts it again whenever a + # file changes. + (lib.mkIf (onCluster != { } && caFiles != { }) { + systemd.services.hyperhive-k8s-ca-trust = { + description = "publish the hive's CA files to the cluster's pods"; + wantedBy = [ "multi-user.target" ]; + after = [ + "k3s.service" + "hive-tls-ca.service" + "swarm-bao-pki.service" + ]; + serviceConfig = { + Type = "oneshot"; + Restart = "on-failure"; + RestartSec = "10s"; + SyslogIdentifier = "hyperhive-k8s-ca-trust"; + }; + environment.KUBECONFIG = kubeconfig; + script = '' + set -euo pipefail + ${apiReady} + ${waitFor 600 "the namespace" "${kubectl} get namespace ${cfg.namespace} >/dev/null 2>&1"} + ${lib.concatMapStrings (path: waitFor 600 "${path}" "[ -s ${lib.escapeShellArg path} ]") ( + lib.attrValues caFiles + )} + ${kubectl} --namespace ${cfg.namespace} create configmap ${rendered.caConfigMap} \ + ${ + lib.concatStringsSep " " ( + lib.mapAttrsToList (key: path: "--from-file=${key}=${lib.escapeShellArg path}") caFiles + ) + } \ + --dry-run=client --output=yaml \ + | ${kubectl} --namespace ${cfg.namespace} apply --server-side --force-conflicts --filename=- + ''; + }; + systemd.paths.hyperhive-k8s-ca-trust = { + wantedBy = [ "multi-user.target" ]; + pathConfig.PathChanged = lib.attrValues caFiles; + }; + }) + + # A service back on the host first loses its objects. The unit that + # starts the host copy requires this one, so the pod is gone before the + # host copy starts, and a failure here leaves the host copy stopped. + # + # Its marker is the manifest's link in the cluster's manifests + # directory, which nothing else removes: no link, nothing was applied, + # and the unit needs no cluster. The link is renamed first, so the + # cluster cannot apply it again, and the rename is the record of what is + # left to delete. Deleting the AddOn the cluster keeps for the file lets + # a later switch to the cluster apply the same manifest again. + (lib.mkIf (onHost != { }) { + systemd.services = lib.mapAttrs' ( + name: s: + lib.nameValuePair "${name}-k8s-prune" { + description = "delete ${name}'s objects from the cluster before its host unit starts"; + after = [ "k3s.service" ]; + before = [ s.hostUnit ]; + requiredBy = [ s.hostUnit ]; + serviceConfig = { + Type = "oneshot"; + RemainAfterExit = true; + SyslogIdentifier = "${name}-k8s-prune"; + }; + environment.KUBECONFIG = kubeconfig; + script = '' + set -euo pipefail + link=${node.manifestDir}/${name}.yaml + pending=$link.pruning + if [ -e "$link" ] || [ -L "$link" ]; then + mv -f "$link" "$pending" + fi + if [ ! -e "$pending" ] && [ ! -L "$pending" ]; then + exit 0 + fi + ${apiReady} + ${kubectl} --namespace ${cfg.namespace} delete deployment,cronjob,serviceaccount \ + --selector=app.kubernetes.io/name=${name} \ + --cascade=foreground --wait=true --timeout=180s --ignore-not-found + ${kubectl} --namespace kube-system delete addons.k3s.cattle.io ${name} --ignore-not-found + rm -f "$pending" + ''; + } + ) onHost; + }) + ] + ); +} diff --git a/nix/host-modules/lib/hive-ca-trust.nix b/nix/host-modules/lib/hive-ca-trust.nix index a65949479..6fd237823 100644 --- a/nix/host-modules/lib/hive-ca-trust.nix +++ b/nix/host-modules/lib/hive-ca-trust.nix @@ -45,7 +45,7 @@ let bundlePathFor = name: "${bundleDirFor name}/trust-bundle.pem"; in { - inherit useSelfSigned caContainerPath; + inherit useSelfSigned caContainerPath caHostPath; # Where `trustBundle` below puts the assembled bundle, for the callers # that must NAME it rather than just have it exported. `SSL_CERT_FILE` is diff --git a/nix/host-modules/swarm-notify-router.nix b/nix/host-modules/swarm-notify-router.nix index 3fbc99f91..aed0657e7 100644 --- a/nix/host-modules/swarm-notify-router.nix +++ b/nix/host-modules/swarm-notify-router.nix @@ -5,6 +5,11 @@ # each agent's subject of `ROUTER_TODOS`, which the agent's harness applies. # docs/4-implementation/swarm/notify-router.md has the design. # +# With `deploy.notify-router.runtime = "k8s"` the host has no container: the +# router runs as a pod in the host's cluster, which ../host-modules/k8s renders +# from the unit this file defines. docs/4-implementation/k8s/runtime.md has +# the switch. +# # Its own network namespace on the bridge, as ./swarm-claude-login.nix has: it # reaches the swarm services by name and nothing on the host's loopback. It # talks only to the queue, the store and authelia, so it can run on any host. @@ -79,6 +84,121 @@ let forwarderCredential = id: "/run/credentials/${forwarderUnit}.service/${id}"; privateNetwork = true; + + onK8s = cfg.runtime == "k8s"; + + # The module the container runs: its own NixOS system on the host's bridge, + # or, with the router on the cluster, only the source of the unit the pod is + # rendered from (`deploy.notify-router.unit`). + containerConfig = + { lib, ... }: + { + imports = [ + ../container-modules/swarm-container.nix + ../container-modules/swarm-journal-forwarder.nix + caBundleModule + ]; + + services.hyperhive.swarmContainer = { + inherit privateNetwork; + writesOwnResolvConf = false; + }; + networking.nameservers = [ networkCfg.bridgeIp ]; + networking.interfaces.eth0.useDHCP = true; + + users.users.${unit} = { + isSystemUser = true; + group = unit; + }; + users.groups.${unit} = { }; + + # Authenticated as the daemon's own OIDC client, whose secret its + # store identity already reads: one identity for the whole container. + services.hyperhive.swarmJournalForwarder = { + enable = true; + serviceName = "notify-router"; + endpoint = forwarderEndpoint; + inherit clientId; + tokenUrl = "${autheliaCfg.url}/api/oidc/token"; + telemetryPort = forwarderTelemetryPort; + otlpMetricsPort = forwarderOtlpPort; + store = { + package = baoDeploy.package; + addr = "https://${baoCfg.domain}:${toString baoCfg.port}"; + secretPath = "secret/swarm/services/${clientId}/oidc/client"; + clientCertFile = forwarderCredential "notify-router-bao-cert"; + clientKeyFile = forwarderCredential "notify-router-bao-key"; + caFile = + if storeFiles ? notify-router-bao-server-ca then + forwarderCredential "notify-router-bao-server-ca" + else + null; + }; + }; + systemd.services.${forwarderUnit}.serviceConfig.LoadCredential = lib.attrNames storeFiles; + + systemd.services.${unit} = { + description = "route forge events to agents' todo lists"; + wantedBy = [ "multi-user.target" ]; + wants = [ "network-online.target" ]; + after = [ "network-online.target" ]; + environment = { + BAO_ADDR = "https://${baoCfg.domain}:${toString baoCfg.port}"; + BAO_CLIENT_CERT = credential "notify-router-bao-cert"; + BAO_CLIENT_KEY = credential "notify-router-bao-key"; + SWARM_NOTIFY_ROUTER_NATS_URL = "tls://${natsCfg.domain}:${toString natsCfg.port}"; + SWARM_NOTIFY_ROUTER_OIDC_TOKEN_ENDPOINT = "${autheliaCfg.url}/api/oidc/token"; + SWARM_NOTIFY_ROUTER_OIDC_CLIENT_ID = clientId; + OTEL_EXPORTER_OTLP_ENDPOINT = "http://127.0.0.1:${toString forwarderOtlpPort}"; + OTEL_EXPORTER_OTLP_PROTOCOL = "http/protobuf"; + OTEL_RESOURCE_ATTRIBUTES = "service.name=hyperhive-notify-router,swarm=${ + if hyperhiveCfg.swarm.name == null then "unknown" else hyperhiveCfg.swarm.name + }"; + } + // lib.optionalAttrs (storeFiles ? notify-router-bao-server-ca) { + BAO_CACERT = credential "notify-router-bao-server-ca"; + } + // lib.optionalAttrs caTrust.useSelfSigned { + SWARM_NOTIFY_ROUTER_OIDC_CA_FILE = caTrust.bundlePathFor machine; + }; + serviceConfig = { + ExecStart = "${cfg.package}/bin/swarm-notify-router"; + User = unit; + Group = unit; + UMask = "0077"; + # Bare ids: the system credentials nspawn handed in. + LoadCredential = lib.attrNames storeFiles; + Restart = "on-failure"; + RestartSec = "10s"; + SyslogIdentifier = unit; + }; + }; + }; + + # The container's system, evaluated as `containers..config` evaluates + # it, for a host that has no such container. + podSystem = + (import "${pkgs.path}/nixos/lib/eval-config.nix" { + modules = [ + ( + { options, ... }: + { + config = { + nixpkgs = + if options.nixpkgs ? hostPlatform then + { inherit (pkgs.stdenv) hostPlatform; } + else + { localSystem = pkgs.stdenv.hostPlatform; }; + boot.isNspawnContainer = true; + networking.hostName = lib.mkDefault machine; + networking.useDHCP = false; + }; + } + ) + containerConfig + ]; + system = null; + }).config; in { options.services.hyperhive.swarm.notify-router.clientId = lib.mkOption { @@ -99,146 +219,118 @@ in description = "The notification router daemon package."; }; - config = lib.mkIf cfg.enable { - assertions = [ - { - assertion = haveClientIdentity; - message = '' - services.hyperhive.deploy.notify-router.enable requires the router's - swarm-secret-store client identity: set both - - services.hyperhive.deploy.bao.notifyRouterClientCertFile - services.hyperhive.deploy.bao.notifyRouterClientKeyFile - - The router reads its queue client secret with it. - - Both default to the pair glue-bao-tls.nix mints when - services.hyperhive.deploy.bao.enable is true (the host that runs the - store). Otherwise copy notify-router.pem and notify-router-key.pem - from the store host's /var/lib/swarm-bao-pki/ and name them in those - two options. - ''; - } - { - assertion = lib.all oneWord (lib.attrValues storeFiles); - message = '' - The notification router's store identity paths must not contain - whitespace: nspawn's --load-credential receives them through - nixos-container's unquoted extra flags. - ''; - } + options.services.hyperhive.deploy.notify-router.runtime = lib.mkOption { + type = lib.types.enum [ + "host" + "k8s" ]; - - # The container hangs off the bridge, takes its address from the gateway's - # DHCP and resolves through its dnsmasq. - services.hyperhive.network.enable = lib.mkDefault true; - services.hyperhive.gateway.enable = lib.mkDefault true; - services.hyperhive.gateway.dns.enable = lib.mkDefault true; - - # nspawn fails to start the container when a credential source is - # missing, so where this host mints the leaf the container waits for it. - systemd.services."container@${machine}" = lib.mkMerge [ - caTrust.containerOrdering - (rootfsCheck.warnOnly machine) - { after = [ "swarm-bao-pki.service" ]; } - ]; - - containers.${machine} = { - autoStart = true; - # The daemon keeps its state in the queue: its consumer's position and - # its per-issue snapshots. - ephemeral = false; - # No `--link-journal=host`: the journal stays in the guest, where the - # container's own forwarder reads it (../container-modules/swarm-journal-forwarder.nix). - extraFlags = lib.mapAttrsToList (id: source: "--load-credential=${id}:${source}") storeFiles; - inherit privateNetwork; - hostBridge = networkCfg.bridgeName; - bindMounts = caTrust.bindMount; - - config = - { lib, ... }: - { - imports = [ - ../container-modules/swarm-container.nix - ../container-modules/swarm-journal-forwarder.nix - caBundleModule - ]; - - services.hyperhive.swarmContainer = { - inherit privateNetwork; - writesOwnResolvConf = false; - }; - networking.nameservers = [ networkCfg.bridgeIp ]; - networking.interfaces.eth0.useDHCP = true; - - users.users.${unit} = { - isSystemUser = true; - group = unit; - }; - users.groups.${unit} = { }; - - # Authenticated as the daemon's own OIDC client, whose secret its - # store identity already reads: one identity for the whole container. - services.hyperhive.swarmJournalForwarder = { - enable = true; - serviceName = "notify-router"; - endpoint = forwarderEndpoint; - inherit clientId; - tokenUrl = "${autheliaCfg.url}/api/oidc/token"; - telemetryPort = forwarderTelemetryPort; - otlpMetricsPort = forwarderOtlpPort; - store = { - package = baoDeploy.package; - addr = "https://${baoCfg.domain}:${toString baoCfg.port}"; - secretPath = "secret/swarm/services/${clientId}/oidc/client"; - clientCertFile = forwarderCredential "notify-router-bao-cert"; - clientKeyFile = forwarderCredential "notify-router-bao-key"; - caFile = - if storeFiles ? notify-router-bao-server-ca then - forwarderCredential "notify-router-bao-server-ca" - else - null; - }; - }; - systemd.services.${forwarderUnit}.serviceConfig.LoadCredential = lib.attrNames storeFiles; - - systemd.services.${unit} = { - description = "route forge events to agents' todo lists"; - wantedBy = [ "multi-user.target" ]; - wants = [ "network-online.target" ]; - after = [ "network-online.target" ]; - environment = { - BAO_ADDR = "https://${baoCfg.domain}:${toString baoCfg.port}"; - BAO_CLIENT_CERT = credential "notify-router-bao-cert"; - BAO_CLIENT_KEY = credential "notify-router-bao-key"; - SWARM_NOTIFY_ROUTER_NATS_URL = "tls://${natsCfg.domain}:${toString natsCfg.port}"; - SWARM_NOTIFY_ROUTER_OIDC_TOKEN_ENDPOINT = "${autheliaCfg.url}/api/oidc/token"; - SWARM_NOTIFY_ROUTER_OIDC_CLIENT_ID = clientId; - OTEL_EXPORTER_OTLP_ENDPOINT = "http://127.0.0.1:${toString forwarderOtlpPort}"; - OTEL_EXPORTER_OTLP_PROTOCOL = "http/protobuf"; - OTEL_RESOURCE_ATTRIBUTES = "service.name=hyperhive-notify-router,swarm=${ - if hyperhiveCfg.swarm.name == null then "unknown" else hyperhiveCfg.swarm.name - }"; - } - // lib.optionalAttrs (storeFiles ? notify-router-bao-server-ca) { - BAO_CACERT = credential "notify-router-bao-server-ca"; - } - // lib.optionalAttrs caTrust.useSelfSigned { - SWARM_NOTIFY_ROUTER_OIDC_CA_FILE = caTrust.bundlePathFor machine; - }; - serviceConfig = { - ExecStart = "${cfg.package}/bin/swarm-notify-router"; - User = unit; - Group = unit; - UMask = "0077"; - # Bare ids: the system credentials nspawn handed in. - LoadCredential = lib.attrNames storeFiles; - Restart = "on-failure"; - RestartSec = "10s"; - SyslogIdentifier = unit; - }; - }; - }; - }; + default = "host"; + description = '' + Where the notification router runs: `host` in its `swarm-notify-router` + container, or `k8s` as a pod in this host's cluster + ({option}`services.hyperhive.deploy.k8s.enable`), which the host's + configuration must enable. The router runs once per swarm, so a switch + moves it: the container goes and its objects are applied, or the objects + are deleted and the container returns. The router keeps nothing on the + host: its consumer and state bucket live in the queue. + ''; }; + + options.services.hyperhive.deploy.notify-router.unit = lib.mkOption { + type = lib.types.raw; + readOnly = true; + internal = true; + default = + if onK8s then + podSystem.systemd.services.${unit} + else + config.containers.${machine}.config.systemd.services.${unit}; + description = '' + The router's evaluated systemd unit, which the cluster's manifests are + rendered from (../host-modules/k8s/render.nix). It is the unit the + container runs, taken from the container's configuration, or from the + same configuration evaluated alone when the router runs in the cluster + and the host has no container. + ''; + }; + + config = lib.mkMerge [ + { + assertions = [ + { + assertion = !onK8s || hyperhiveCfg.deploy.k8s.enable; + message = '' + services.hyperhive.deploy.notify-router.runtime = "k8s" needs the + cluster: set services.hyperhive.deploy.k8s.enable on this host, or + leave the router's runtime at "host". + ''; + } + ]; + } + + (lib.mkIf cfg.enable { + assertions = [ + { + assertion = haveClientIdentity; + message = '' + services.hyperhive.deploy.notify-router.enable requires the router's + swarm-secret-store client identity: set both + + services.hyperhive.deploy.bao.notifyRouterClientCertFile + services.hyperhive.deploy.bao.notifyRouterClientKeyFile + + The router reads its queue client secret with it. + + Both default to the pair glue-bao-tls.nix mints when + services.hyperhive.deploy.bao.enable is true (the host that runs the + store). Otherwise copy notify-router.pem and notify-router-key.pem + from the store host's /var/lib/swarm-bao-pki/ and name them in those + two options. + ''; + } + { + assertion = lib.all oneWord (lib.attrValues storeFiles); + message = '' + The notification router's store identity paths must not contain + whitespace: nspawn's --load-credential receives them through + nixos-container's unquoted extra flags. + ''; + } + ]; + + # The container hangs off the bridge, and the cluster's pods reach the + # host's services through it. + services.hyperhive.network.enable = lib.mkDefault true; + }) + + (lib.mkIf (cfg.enable && !onK8s) { + # The container takes its address from the gateway's DHCP and resolves + # through its dnsmasq. + services.hyperhive.gateway.enable = lib.mkDefault true; + services.hyperhive.gateway.dns.enable = lib.mkDefault true; + + # nspawn fails to start the container when a credential source is + # missing, so where this host mints the leaf the container waits for it. + systemd.services."container@${machine}" = lib.mkMerge [ + caTrust.containerOrdering + (rootfsCheck.warnOnly machine) + { after = [ "swarm-bao-pki.service" ]; } + ]; + + containers.${machine} = { + autoStart = true; + # The daemon keeps its state in the queue: its consumer's position and + # its per-issue snapshots. + ephemeral = false; + # No `--link-journal=host`: the journal stays in the guest, where the + # container's own forwarder reads it (../container-modules/swarm-journal-forwarder.nix). + extraFlags = lib.mapAttrsToList (id: source: "--load-credential=${id}:${source}") storeFiles; + inherit privateNetwork; + hostBridge = networkCfg.bridgeName; + bindMounts = caTrust.bindMount; + + config = containerConfig; + }; + }) + ]; } diff --git a/nix/module-eval/k8s.nix b/nix/module-eval/k8s.nix index b0c15e4a1..e3fb0f033 100644 --- a/nix/module-eval/k8s.nix +++ b/nix/module-eval/k8s.nix @@ -39,7 +39,7 @@ let # The all-local host with the node on. It does not set # `services.hyperhive.k8s.enable`: the node turns the rendering on. - withNode = hiveWithController { + nodeSettings = { deploy.singleHostSwarm = true; deploy.k8s.enable = true; deploy.victorialogs.authPackage = marker "logs"; @@ -47,6 +47,18 @@ let deploy.victoriametrics.authPackage = marker "metrics"; deploy.victoriametrics.agentAuthPackage = marker "metrics-agent"; }; + withNode = hiveWithController nodeSettings; + + # The same host with the router in the cluster, so it has no container. A + # second full host, because the claim is about what the configuration + # drops; the other cases of this group read `withNode`. + onCluster = hiveWithController ( + lib.recursiveUpdate nodeSettings { deploy.notify-router.runtime = "k8s"; } + ); + + # A host that asks for the cluster with no node. + runtimeRefused = hive { deploy.notify-router.runtime = "k8s"; }; + runtimeRefusals = lib.filter (a: !a.assertion) runtimeRefused.assertions; # A node every assertion refuses: no rendering, a pod range containing the # hive bridge's subnet, and a service range inside the pod range. @@ -173,6 +185,10 @@ let renders = config: (builtins.tryEval (builtins.deepSeq (builtins.toJSON (render config)) true)).success; + 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; + clusterRouterSpec = (render onCluster)."swarm-notify-router/deployment".spec.template.spec; cases = [ { # Each service's own credential path is the control: the comparison @@ -205,32 +221,6 @@ let && (lib.head (podSpec "swarm-controller").volumes).secret.secretName == "swarm-controller-credentials"; } - { - # The controller's pod is the control for the Secret lookup: its - # credentials still come from one. - name = "the router's CA file comes from the CA ConfigMap and its pod mounts no Secret"; - ok = - let - volumes = (podSpec "swarm-notify-router").volumes; - credentials = lib.findFirst (v: v.name == "credentials") null volumes; - sources = credentials.projected.sources; - in - credentials != null - && lib.length sources == 1 - && (lib.head sources).configMap.name == "hyperhive-ca-trust" - && - map (i: [ - i.key - i.path - ]) (lib.head sources).configMap.items == [ - [ - "bao-server-ca.pem" - "notify-router-bao-server-ca" - ] - ] - && !(lib.any (v: v ? secret) volumes) - && lib.any (v: v ? secret) (podSpec "swarm-controller").volumes; - } { name = "the poller's CronJob runs on its timer's interval and deadline, never overlapping"; ok = @@ -306,7 +296,7 @@ let # granter's role unit (which enables the login's auth mount) starts the # same command, and the manifests are the same derivation as without the # node. - name = "the node changes no unit, container, timer or manifest of the all-local host"; + name = "the node adds only k3s, the jwt unit and the router's prune unit to the all-local host, and changes no container, timer or manifest"; ok = let names = a: lib.attrNames a; @@ -316,8 +306,11 @@ let && names allLocal.containers == names withNode.containers && lib.subtractLists (names withNode.systemd.services) (names allLocal.systemd.services) == [ ] && lib.elem "k3s" added - && lib.all (n: lib.hasPrefix "k3s" n || n == "swarm-bao-k8s-jwt-policy") added + && lib.all ( + n: lib.hasPrefix "k3s" n || n == "swarm-bao-k8s-jwt-policy" || n == "swarm-notify-router-k8s-prune" + ) added && lib.elem "swarm-bao-k8s-jwt-policy" added + && lib.elem "swarm-notify-router-k8s-prune" added && lib.all ( @@ -666,6 +659,101 @@ let && !(lib.elem 8208 fw.allowedTCPPorts) && !(lib.elem 8208 withNode.services.hyperhive.network.exposeHostPorts); } + { + # The host with the router on it is the control for every absence below: + # it holds the container, the prune unit and the pieces the cluster + # case lacks. + name = "a router on the host keeps its container, the node adds no manifest and no CA unit, and its prune unit runs before the container"; + ok = + withNode.containers ? swarm-notify-router + && withNode.systemd.services ? "container@swarm-notify-router" + && manifestNames withNode == [ "coredns-custom" ] + && !(withNode.systemd.services ? hyperhive-k8s-ca-trust) + && routerPrune.before == [ "container@swarm-notify-router.service" ] + && routerPrune.requiredBy == [ "container@swarm-notify-router.service" ] + && lib.hasInfix "swarm-notify-router.yaml" routerPrune.script + && allLocal.services.k3s.manifests == { } + && !(allLocal.systemd.services ? swarm-notify-router-k8s-prune) + && !(allLocal.systemd.services ? hyperhive-k8s-ca-trust); + } + { + name = "a router in the cluster leaves the host no container and no prune unit, and applies the namespace and its objects"; + ok = + !(onCluster.containers ? swarm-notify-router) + && !(onCluster.systemd.services ? "container@swarm-notify-router") + && !(onCluster.systemd.services ? swarm-notify-router-k8s-prune) + && + manifestNames onCluster == [ + "coredns-custom" + "hyperhive-namespace" + "swarm-notify-router" + ] + && onCluster.services.k3s.manifests.hyperhive-namespace.content.kind == "Namespace" + && + lib.sort lib.lessThan (map (o: o.kind) onCluster.services.k3s.manifests.swarm-notify-router.content) + == [ + "Deployment" + "ServiceAccount" + ]; + } + { + name = "the router's manifests and its unit are the same whether the container or the stand-alone evaluation supplies the unit"; + ok = + (routerUnit withNode).environment ? SWARM_NOTIFY_ROUTER_NATS_URL + && (routerUnit onCluster).environment == (routerUnit withNode).environment + && (routerUnit onCluster).serviceConfig.ExecStart == (routerUnit withNode).serviceConfig.ExecStart + && + (routerUnit onCluster).serviceConfig.LoadCredential == (routerUnit withNode) + .serviceConfig.LoadCredential + && render onCluster == render withNode; + } + { + # The controller's pod is the control for the Secret lookup: its + # credentials still come from one. + name = "the router's CA file comes from the ConfigMap the host publishes, and the pod mounts no Secret"; + ok = + let + volumes = clusterRouterSpec.volumes; + credentials = lib.findFirst (v: v.name == "credentials") null volumes; + sources = credentials.projected.sources; + caUnit = onCluster.systemd.services.hyperhive-k8s-ca-trust; + serverCa = onCluster.services.hyperhive.deploy.bao.serverCaFile; + in + credentials != null + && lib.length sources == 1 + && (lib.head sources).configMap.name == "hyperhive-ca-trust" + && + map (i: [ + i.key + i.path + ]) (lib.head sources).configMap.items == [ + [ + "bao-server-ca.pem" + "notify-router-bao-server-ca" + ] + ] + && !(lib.any (v: v ? secret) volumes) + && lib.any (v: v ? secret) (podSpec "swarm-controller").volumes + && lib.hasInfix "--from-file=bao-server-ca.pem=${serverCa}" caUnit.script + && lib.hasInfix "--from-file=trust-bundle.pem=" caUnit.script + && lib.elem "multi-user.target" caUnit.wantedBy + # A change to either file publishes again with no manual step, and the + # host with the router on its container has no path unit. + && + lib.sort lib.lessThan onCluster.systemd.paths.hyperhive-k8s-ca-trust.pathConfig.PathChanged + == lib.sort lib.lessThan [ + serverCa + "${onCluster.services.hyperhive.deploy.hive-controller.tls.stateDir}/trust-bundle.pem" + ] + && !(caUnit.serviceConfig ? RemainAfterExit) + && !(withNode.systemd.paths ? hyperhive-k8s-ca-trust); + } + { + name = "the router's runtime \"k8s\" needs the node"; + ok = + lib.any (a: lib.hasInfix "runtime = \"k8s\" needs the" a.message) runtimeRefusals + && lib.all (a: a.assertion) onCluster.assertions; + } ]; in runGroup "k8s" cases