From e587fd44cdd721951b9ee49215631597eec8e45f Mon Sep 17 00:00:00 2001 From: atlas Date: Thu, 19 Nov 2026 10:08:27 +0100 Subject: [PATCH] k8s: render the in-cluster services' manifests from their units services.hyperhive.k8s.enable renders a Deployment (swarm-controller, swarm-notify-router) or CronJob (swarm-ci-metrics) per service this host deploys into system.build.k8sManifests. The renderer reads each evaluated unit: its environment, LoadCredential ids, state and runtime directories, ExecStart and timer. Files the unit names are mounted at the same paths, so the environment carries over as it is. Secrets are referenced by name only. No unit changes. checks: k8s-manifests-all-local (kubeconform -strict, offline schemas) and module-eval-k8s; the allLocal fixture turns the rendering on. --- docs/4-implementation/k8s/manifests.md | 114 ++++++++ nix/checks.nix | 62 ++++ nix/host-modules/default.nix | 1 + nix/host-modules/k8s/default.nix | 52 ++++ nix/host-modules/k8s/render.nix | 390 +++++++++++++++++++++++++ nix/module-eval/k8s.nix | 152 ++++++++++ nix/module-eval/shared.nix | 2 + 7 files changed, 773 insertions(+) create mode 100644 docs/4-implementation/k8s/manifests.md create mode 100644 nix/host-modules/k8s/default.nix create mode 100644 nix/host-modules/k8s/render.nix create mode 100644 nix/module-eval/k8s.nix diff --git a/docs/4-implementation/k8s/manifests.md b/docs/4-implementation/k8s/manifests.md new file mode 100644 index 000000000..740fbd4b3 --- /dev/null +++ b/docs/4-implementation/k8s/manifests.md @@ -0,0 +1,114 @@ +# Service manifests + +`services.hyperhive.k8s` renders Kubernetes manifests for the swarm services +that run in the cluster. `nix/host-modules/k8s/render.nix` builds them from +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. Rendering changes no unit, and +nothing in this module applies the manifests to a cluster. + +## Options + +- `services.hyperhive.k8s.enable` (default `false`): render the manifests. +- `services.hyperhive.k8s.namespace` (default `hyperhive`): the namespace of + every rendered object. + +## What gets rendered + +A service gets manifests on the host whose configuration deploys it: + +| service | workload | other objects | +| --------------------- | ---------- | -------------------------------------------------------------------------------- | +| `swarm-controller` | Deployment | PersistentVolumeClaim `swarm-controller-state`, ConfigMap `swarm-controller-etc` | +| `swarm-notify-router` | Deployment | none | +| `swarm-ci-metrics` | CronJob | PersistentVolumeClaim `swarm-ci-metrics-state` | + +`namespace.yaml` holds the Namespace. NATS with its auth responder, +`swarm-review-classifier`, `swarm-claude-login` and `swarm-stt` have no +manifests yet: their images don't exist yet. + +## One source: the unit + +The renderer reads the service's evaluated unit, not a copy of its settings: + +- **Environment:** the unit's `environment`, including what other modules + merge into it, minus `PATH`. A systemd `%d` becomes the credential + directory it stands for. The renderer fails if the unit's `path` holds + anything beyond the NixOS default tools, because the image doesn't carry + them. +- **Files:** the pod mounts each file the unit names at the same path, + so the environment carries over unchanged: + - credentials at `/run/credentials/.service/`, from the Secret + `-credentials`, one key per `LoadCredential` id; + - trust bundles (any `…/trust-bundle.pem` the environment names), from the + ConfigMap `hyperhive-ca-trust`, key `trust-bundle.pem`; + - `RuntimeDirectory` as an `emptyDir`, and `StateDirectory` on the + service's PersistentVolumeClaim, with `RUNTIME_DIRECTORY` and + `STATE_DIRECTORY` set the way systemd sets them; + - `/etc` files the unit reads, from the service's own ConfigMap. + + The renderer fails evaluation if an environment value names an absolute + path the pod doesn't mount, or a credential the unit doesn't load. A new + path in a unit then shows up as an error here, not as a pod that can't + find a file. + +- **Command:** `ExecStart` must be the service's own binary. Its arguments + become the container's `args`. +- **Schedule:** the CronJob runs every `OnUnitInactiveSec` minutes of the + unit's timer, never overlapping, with `TimeoutStartSec` as its deadline. + +A change to a unit's environment therefore changes its manifest in the same +commit. + +## Secrets + +The YAML lands in the world-readable nix store, so it holds no credential. +It names the Secret `-credentials` and the credential ids as keys. +It never names the host path the unit loads a credential from, and never its +contents. The `hyperhive-ca-trust` ConfigMap is only referenced as well, +because the hive CA exists only at runtime. Nothing here creates either +object. + +## Pods + +- **Image:** `mkServiceImage` from [Service images](images.md), built from the + same `deploy..package` the unit runs. Store paths the environment + names (the controller's branding assets, for example) go into the image + too. Where the environment names none, the image is the flake's + `image-`. The manifest carries the image name and tag but doesn't + depend on the image: building the manifests builds no daemon. + `imagePullPolicy` is `Never`, because the node imports the image tarball. +- **Security:** the `serviceUser` uid and gid from [Service images](images.md), + with `fsGroup` its gid so the pod reads its credentials (mode `0440`), + read-only root filesystem with an `emptyDir` on `/tmp`, no privilege + escalation, every capability dropped, the runtime's default seccomp profile, + and no service account token. +- **Probes:** a service with an opt-in health listener gets its variable set to + `0.0.0.0:8080`, with liveness on `/healthz` and readiness on `/readyz` + (see [Readiness checks](../swarm/readiness.md)). `swarm-controller` serves + `/readyz` on its unix socket only, so it has no probes yet. +- **Shutdown:** `terminationGracePeriodSeconds` is 15, the 10-second drain a + daemon allows itself after SIGTERM (`DRAIN` in + `swarm-secret-client/src/shutdown.rs`) plus headroom. +- **Rollout:** each Deployment has one replica and the `Recreate` strategy, + because each service runs once per swarm. + +## Not covered yet + +- The pods reach the swarm's host-run services (store, queue, identity + provider) by the same names as the units do. Those names don't resolve to + the host from inside a cluster yet. +- `OTEL_EXPORTER_OTLP_ENDPOINT` keeps the unit's value. For + `swarm-notify-router` that's its container's local log and metrics + forwarder, which a pod doesn't have. +- `swarm-controller`'s socket lives in an `emptyDir`, so only the pod can + reach it. + +## Validation + +The flake check `k8s-manifests-all-local` renders the manifests for the +single-host swarm fixture and runs `kubeconform -strict` over them, offline, +against JSON schemas for Kubernetes 1.35 pinned by hash. A deliberately +malformed Deployment in the same check must fail, so a validator that loads no +schema can't pass. `module-eval-k8s` checks that each workload carries its +unit's environment and that no credential source path reaches the YAML. diff --git a/nix/checks.nix b/nix/checks.nix index 3c2c7e32f..2f73ee5d6 100644 --- a/nix/checks.nix +++ b/nix/checks.nix @@ -32,6 +32,63 @@ in echo ${pkgs.lib.escapeShellArg moduleEvalShared.allLocal.systemd.services.nginx.serviceConfig.ExecStart} > $out ''; + # The single-host swarm fixture's k8s manifests (../host-modules/k8s), + # validated offline by `kubeconform -strict` against the schemas below. + # The invalid Deployment must fail, which shows the schemas load and an + # unknown field is refused. + k8s-manifests-all-local = + let + # Standalone strict JSON schemas for Kubernetes 1.35, one per kind the + # renderer emits, named the way `-schema-location` below looks them up. + schemaRev = "11639286f15b208b6c7f1f93bc2c1a70f42cfbcb"; + schemas = pkgs.linkFarm "k8s-1.35-schemas" ( + pkgs.lib.mapAttrsToList + (file: hash: { + name = "${file}.json"; + path = pkgs.fetchurl { + url = "https://raw.githubusercontent.com/yannh/kubernetes-json-schema/${schemaRev}/v1.35.0-standalone-strict/${file}.json"; + inherit hash; + }; + }) + { + deployment-apps-v1 = "sha256-Rtx8xL7CyaYkAEkeK4BXY1r7+mg4mZxRj3vqXGIamJs="; + cronjob-batch-v1 = "sha256-324f6Z2U41lEAnt7xDFwOfIvSc/0DE6x3AtU8C/PiUA="; + persistentvolumeclaim-v1 = "sha256-YTaHGsAzfxGkjaUjGigHQHxzhpZ+NDLzRBQbkC9qU4w="; + configmap-v1 = "sha256-4Ord69Z3wIqgkrLaImTYasT8NO7RErn6wpRbPwDB6bE="; + namespace-v1 = "sha256-Mk+uZ3uY0abVQ0DbDDNNBT6P+6/Os/czJuQd4mENWEM="; + } + ); + invalid = pkgs.writeText "invalid-deployment.yaml" '' + apiVersion: apps/v1 + kind: Deployment + metadata: + name: invalid + spec: + replicaCount: 1 + selector: + matchLabels: + app: invalid + template: + metadata: + labels: + app: invalid + spec: + containers: + - name: invalid + image: invalid + ''; + validate = "kubeconform -strict -summary -schema-location '${schemas}/{{ .ResourceKind }}{{ .KindSuffix }}.json'"; + in + pkgs.runCommand "k8s-manifests-all-local" { nativeBuildInputs = [ pkgs.kubeconform ]; } '' + ${validate} ${moduleEvalShared.allLocal.system.build.k8sManifests}/ + test -e ${moduleEvalShared.allLocal.system.build.k8sManifests}/swarm-controller/deployment.yaml + if ${validate} ${invalid}; then + echo "kubeconform accepted a Deployment with an unknown field" >&2 + exit 1 + fi + touch $out + ''; + # The only checks here that cover **nix**. Every other one is a Rust # derivation, so a `.nix`-only diff moves no hash and the whole set is # cache hits — green without evaluating what changed. See @@ -63,6 +120,11 @@ in inherit (pkgs) lib; shared = moduleEvalShared; }; + module-eval-k8s = import ./module-eval/k8s.nix { + inherit pkgs self nixosSystem; + inherit (pkgs) lib; + shared = moduleEvalShared; + }; module-eval-nats-authelia = import ./module-eval/nats-authelia.nix { inherit pkgs self nixosSystem; inherit (pkgs) lib; diff --git a/nix/host-modules/default.nix b/nix/host-modules/default.nix index 7dfa9682f..3efc8e519 100644 --- a/nix/host-modules/default.nix +++ b/nix/host-modules/default.nix @@ -13,6 +13,7 @@ { imports = [ ./hyperhive.nix + ./k8s ./deploy.nix ./local-defaults.nix ./hive-c0re diff --git a/nix/host-modules/k8s/default.nix b/nix/host-modules/k8s/default.nix new file mode 100644 index 000000000..b75ea4156 --- /dev/null +++ b/nix/host-modules/k8s/default.nix @@ -0,0 +1,52 @@ +# 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. +{ + pkgs, + lib, + config, + ... +}: +let + cfg = config.services.hyperhive.k8s; + + yaml = pkgs.formats.yaml { }; + + # The manifests name store paths that live in the images, not on the host, + # so the YAML carries no string context: building it builds no image and + # no daemon. + withoutContext = v: builtins.fromJSON (builtins.unsafeDiscardStringContext (builtins.toJSON v)); +in +{ + options.services.hyperhive.k8s = { + enable = lib.mkOption { + type = lib.types.bool; + default = false; + description = '' + Render Kubernetes manifests for the in-cluster swarm services this + host deploys (swarm-controller, swarm-notify-router and + swarm-ci-metrics) into `system.build.k8sManifests`, one YAML file per + object. 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. + ''; + }; + + namespace = lib.mkOption { + type = lib.types.str; + default = "hyperhive"; + description = "The Kubernetes namespace the rendered objects live in."; + }; + }; + + config = lib.mkIf cfg.enable { + system.build.k8sManifests = pkgs.linkFarm "hyperhive-k8s-manifests" ( + lib.mapAttrsToList (path: object: { + name = "${path}.yaml"; + path = yaml.generate "${baseNameOf path}.yaml" (withoutContext object); + }) (import ./render.nix { inherit lib pkgs config; }) + ); + }; +} diff --git a/nix/host-modules/k8s/render.nix b/nix/host-modules/k8s/render.nix new file mode 100644 index 000000000..652a30717 --- /dev/null +++ b/nix/host-modules/k8s/render.nix @@ -0,0 +1,390 @@ +# 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 them out as YAML. +# +# 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 +# unit names it by, so the environment carries over as it is and a change to a +# unit shows up in its manifest. +# +# Secrets are referenced by name and credential id only. The output lands in +# the world-readable nix store, so it never holds a credential's host path or +# contents. +{ + lib, + pkgs, + config, +}: +let + hyperhiveCfg = config.services.hyperhive; + deployCfg = hyperhiveCfg.deploy; + k8sCfg = hyperhiveCfg.k8s; + + # `serviceUser` is the user every image runs its daemon as. Mounted files are + # group-owned by its group through `fsGroup`. + inherit (import ../../images { inherit pkgs lib; }) mkServiceImage serviceUser; + + # `DRAIN` in swarm-secret-client/src/shutdown.rs: how long a daemon keeps + # finishing in-flight work after SIGTERM before it exits on its own. The + # kubelet's SIGKILL comes after the grace period, so the grace period is + # longer. + drainSeconds = 10; + terminationGracePeriodSeconds = drainSeconds + 5; + + healthPort = 8080; + + # What NixOS puts on every unit's `path`. + nixosDefaultPath = [ + "coreutils" + "findutils" + "gnugrep" + "gnused" + "systemd" + ]; + + # The swarm services that run in the cluster. `unit` is the evaluated + # systemd unit the host runs today; nothing reads it unless `enable` holds. + # `healthEnv` names the variable that binds the daemon's /healthz and + # /readyz listener; the controller serves /readyz on its unix socket only, + # which the kubelet cannot probe. + services = { + swarm-controller = { + inherit (deployCfg.swarm-controller) enable package; + unit = config.systemd.services.swarm-controller; + kind = "Deployment"; + healthEnv = null; + etcFiles = [ "hyperhive/swarm-controller.json" ]; + }; + swarm-notify-router = { + inherit (deployCfg.notify-router) enable package; + unit = config.containers.swarm-notify-router.config.systemd.services.swarm-notify-router; + kind = "Deployment"; + healthEnv = "SWARM_NOTIFY_ROUTER_HEALTH_ADDR"; + etcFiles = [ ]; + }; + swarm-ci-metrics = { + inherit (deployCfg.ci-metrics) enable package; + unit = config.systemd.services.swarm-ci-metrics; + timer = config.systemd.timers.swarm-ci-metrics; + kind = "CronJob"; + healthEnv = null; + etcFiles = [ ]; + }; + }; + + fail = name: msg: throw "services.hyperhive.k8s: ${name}: ${msg}"; + + labelsFor = name: { + "app.kubernetes.io/name" = name; + "app.kubernetes.io/part-of" = "hyperhive"; + }; + + metaFor = name: { + inherit name; + inherit (k8sCfg) namespace; + labels = labelsFor name; + }; + + # systemd duration "min", the only form these units use. + minutesOf = + name: what: value: + let + m = builtins.match "([0-9]+)min" value; + in + if m == null then + fail name "${what} is \"${value}\"; only \"min\" translates" + else + lib.toInt (lib.head m); + + workload = + name: svc: + let + inherit (svc) unit; + sc = unit.serviceConfig; + + credDir = "/run/credentials/${name}.service"; + # `LoadCredential` entries are `id:source` on the host and a bare `id` + # inside a container. Only the id is rendered. + credIds = map (e: lib.head (lib.splitString ":" e)) (lib.toList (sc.LoadCredential or [ ])); + + runtimeDir = if sc ? RuntimeDirectory then "/run/${sc.RuntimeDirectory}" else null; + stateDir = if sc ? StateDirectory then "/var/lib/${sc.StateDirectory}" else null; + + # PATH holds only NixOS's default tools (checked below), which the image + # does not carry. `%d` is systemd's specifier for the credential + # directory. + unitEnv = lib.mapAttrs (_: v: builtins.replaceStrings [ "%d" ] [ credDir ] (toString v)) ( + lib.filterAttrs (n: v: v != null && n != "PATH") unit.environment + ); + + # Trust bundles (../lib/hive-ca-trust.nix, ../hive-tls.nix): system roots + # plus the hive CA, assembled at runtime, so the cluster holds the one + # bundle as a ConfigMap and each path the unit names mounts it. + caFiles = lib.unique ( + lib.filter (v: lib.hasPrefix "/" v && baseNameOf v == "trust-bundle.pem") (lib.attrValues unitEnv) + ); + + env = + unitEnv + // lib.optionalAttrs (runtimeDir != null) { RUNTIME_DIRECTORY = runtimeDir; } + // lib.optionalAttrs (stateDir != null) { STATE_DIRECTORY = stateDir; } + // lib.optionalAttrs (svc.healthEnv != null) { + ${svc.healthEnv} = "0.0.0.0:${toString healthPort}"; + }; + + mountRoots = [ + credDir + "/nix/store" + ] + ++ caFiles + ++ lib.optional (runtimeDir != null) runtimeDir + ++ lib.optional (stateDir != null) stateDir + ++ map (f: "/etc/${f}") svc.etcFiles; + under = root: v: v == root || lib.hasPrefix "${root}/" v; + unmounted = lib.filterAttrs (_: v: lib.hasPrefix "/" v && !(lib.any (r: under r v) mountRoots)) env; + missingCreds = lib.filterAttrs ( + _: v: under credDir v && !(lib.elem (lib.removePrefix "${credDir}/" v) credIds) + ) env; + + # Store paths the environment names go into the image by way of a file + # that lists them, so the pod finds every path the unit finds. + storeValues = lib.filter (v: lib.hasInfix "/nix/store/" v) (lib.attrValues env); + image = mkServiceImage { + inherit name; + inherit (svc) package; + extraContents = lib.optional (storeValues != [ ]) ( + pkgs.writeTextDir "share/hyperhive/${name}.env-refs" (lib.concatLines storeValues) + ); + }; + + execWords = lib.filter (w: w != "") (lib.splitString " " (toString sc.ExecStart)); + entrypoint = "${svc.package}/bin/${name}"; + + volumes = + lib.optional (credIds != [ ]) { + name = "credentials"; + secret = { + secretName = "${name}-credentials"; + # 0440: the pod's group reads them, as `LoadCredential` lets the + # unit's user read them. + defaultMode = 288; + items = map (id: { + key = id; + path = id; + }) credIds; + }; + } + ++ lib.optional (caFiles != [ ]) { + name = "ca-trust"; + configMap.name = "hyperhive-ca-trust"; + } + ++ lib.optional (runtimeDir != null) { + name = "runtime"; + emptyDir = { }; + } + ++ lib.optional (stateDir != null) { + name = "state"; + persistentVolumeClaim.claimName = "${name}-state"; + } + ++ lib.optional (svc.etcFiles != [ ]) { + name = "etc"; + configMap.name = "${name}-etc"; + } + ++ [ + { + name = "tmp"; + emptyDir = { }; + } + ]; + + etcKey = f: builtins.replaceStrings [ "/" ] [ "_" ] f; + + volumeMounts = + lib.optional (credIds != [ ]) { + name = "credentials"; + mountPath = credDir; + readOnly = true; + } + ++ map (f: { + name = "ca-trust"; + mountPath = f; + subPath = "trust-bundle.pem"; + readOnly = true; + }) caFiles + ++ lib.optional (runtimeDir != null) { + name = "runtime"; + mountPath = runtimeDir; + } + ++ lib.optional (stateDir != null) { + name = "state"; + mountPath = stateDir; + } + ++ map (f: { + name = "etc"; + mountPath = "/etc/${f}"; + subPath = etcKey f; + readOnly = true; + }) svc.etcFiles + ++ [ + { + name = "tmp"; + mountPath = "/tmp"; + } + ]; + + container = { + inherit name volumeMounts; + image = "${image.imageName}:${image.imageTag}"; + # The node imports the image tarball; there is no registry to pull from. + imagePullPolicy = "Never"; + env = lib.mapAttrsToList (n: v: { + name = n; + value = v; + }) env; + securityContext = { + allowPrivilegeEscalation = false; + readOnlyRootFilesystem = true; + runAsNonRoot = true; + capabilities.drop = [ "ALL" ]; + }; + } + // lib.optionalAttrs (lib.tail execWords != [ ]) { args = lib.tail execWords; } + // lib.optionalAttrs (svc.healthEnv != null) { + ports = [ + { + name = "health"; + containerPort = healthPort; + } + ]; + livenessProbe = { + httpGet = { + path = "/healthz"; + port = "health"; + }; + periodSeconds = 10; + }; + readinessProbe = { + httpGet = { + path = "/readyz"; + port = "health"; + }; + periodSeconds = 10; + }; + }; + + podSpec = { + inherit terminationGracePeriodSeconds volumes; + containers = [ container ]; + automountServiceAccountToken = false; + enableServiceLinks = false; + securityContext = { + runAsUser = serviceUser.uid; + runAsGroup = serviceUser.gid; + fsGroup = serviceUser.gid; + seccompProfile.type = "RuntimeDefault"; + }; + }; + + podTemplate = restartPolicy: { + metadata.labels = labelsFor name; + spec = podSpec // { + inherit restartPolicy; + }; + }; + + main = + if svc.kind == "Deployment" then + { + apiVersion = "apps/v1"; + kind = "Deployment"; + metadata = metaFor name; + spec = { + replicas = 1; + # One instance per swarm, as one unit per swarm runs today: the + # old pod is gone before the new one starts. + strategy.type = "Recreate"; + selector.matchLabels = labelsFor name; + template = podTemplate "Always"; + }; + } + else + let + every = minutesOf name "the timer's OnUnitInactiveSec" svc.timer.timerConfig.OnUnitInactiveSec; + in + { + apiVersion = "batch/v1"; + kind = "CronJob"; + metadata = metaFor name; + spec = { + schedule = "*/${toString every} * * * *"; + # The timer counts from the end of the last run, so runs never + # overlap. + concurrencyPolicy = "Forbid"; + jobTemplate.spec = { + # A failed oneshot waits for the next timer run. + backoffLimit = 0; + activeDeadlineSeconds = 60 * minutesOf name "TimeoutStartSec" sc.TimeoutStartSec; + template = podTemplate "Never"; + }; + }; + }; + + objects = { + "${name}/${lib.toLower svc.kind}" = main; + } + // lib.optionalAttrs (stateDir != null) { + "${name}/persistentvolumeclaim" = { + apiVersion = "v1"; + kind = "PersistentVolumeClaim"; + metadata = metaFor "${name}-state"; + spec = { + accessModes = [ "ReadWriteOnce" ]; + resources.requests.storage = "1Gi"; + }; + }; + } + // lib.optionalAttrs (svc.etcFiles != [ ]) { + "${name}/configmap" = { + apiVersion = "v1"; + kind = "ConfigMap"; + metadata = metaFor "${name}-etc"; + data = lib.listToAttrs ( + map ( + f: + let + e = config.environment.etc.${f}; + in + lib.nameValuePair (etcKey f) ( + if e.text != null then e.text else fail name "/etc/${f} has no `text` to put in a ConfigMap" + ) + ) svc.etcFiles + ); + }; + }; + in + if !(lib.all (p: lib.elem (lib.getName p) nixosDefaultPath) unit.path) then + fail name "the unit puts packages on PATH, which the image does not carry" + else if svc.healthEnv != null && unitEnv ? ${svc.healthEnv} then + fail name "the unit already sets ${svc.healthEnv}" + else if lib.head execWords != entrypoint then + fail name "ExecStart is not ${entrypoint} with plain arguments" + else if lib.any (w: lib.hasInfix "\"" w || lib.hasInfix "'" w) execWords then + fail name "ExecStart has quoted arguments, which the split on spaces would break" + else if unmounted != { } then + fail name "the pod mounts nothing at the path ${lib.concatStringsSep ", " (lib.attrNames unmounted)} names" + else if missingCreds != { } then + fail name "${lib.concatStringsSep ", " (lib.attrNames missingCreds)} names a credential the unit does not load" + else + objects; +in +{ + "namespace" = { + apiVersion = "v1"; + kind = "Namespace"; + metadata = { + name = k8sCfg.namespace; + labels."app.kubernetes.io/part-of" = "hyperhive"; + }; + }; +} +// lib.concatMapAttrs (name: svc: lib.optionalAttrs svc.enable (workload name svc)) services diff --git a/nix/module-eval/k8s.nix b/nix/module-eval/k8s.nix new file mode 100644 index 000000000..848135936 --- /dev/null +++ b/nix/module-eval/k8s.nix @@ -0,0 +1,152 @@ +# `checks.module-eval-k8s` — see ./lib.nix for the shared rationale. The k8s +# manifests ../host-modules/k8s/render.nix builds from the single-host swarm's +# units: each workload carries its unit's environment, no credential source +# reaches the world-readable YAML, and the CronJob follows the timer. +# +# Every fixture is a shared one, so this cluster evaluates no host of its own. +{ + pkgs, + lib, + self, + nixosSystem, + shared, +}: +let + inherit + (import ./lib.nix { + inherit + pkgs + lib + self + nixosSystem + ; + }) + runGroup + ; + + allLocal = shared.allLocal; + + render = + config: + import ../host-modules/k8s/render.nix { + inherit lib pkgs config; + }; + objects = render allLocal; + + units = { + swarm-controller = allLocal.systemd.services.swarm-controller; + swarm-notify-router = + allLocal.containers.swarm-notify-router.config.systemd.services.swarm-notify-router; + swarm-ci-metrics = allLocal.systemd.services.swarm-ci-metrics; + }; + + podSpec = + name: + let + o = objects."${name}/deployment" or objects."${name}/cronjob"; + in + if o.kind == "CronJob" then o.spec.jobTemplate.spec.template.spec else o.spec.template.spec; + container = name: lib.head (podSpec name).containers; + envOf = name: lib.listToAttrs (map (e: lib.nameValuePair e.name e.value) (container name).env); + + # The unit's environment as the pod should see it: no PATH, and `%d` + # spelled out as the credential directory. + unitEnv = + name: + lib.mapAttrs ( + _: v: builtins.replaceStrings [ "%d" ] [ "/run/credentials/${name}.service" ] (toString v) + ) (removeAttrs units.${name}.environment [ "PATH" ]); + + # What the pod adds on top of the unit's own environment. + added = { + swarm-controller = { + RUNTIME_DIRECTORY = "/run/swarm-controller"; + STATE_DIRECTORY = "/var/lib/swarm-controller"; + }; + swarm-notify-router.SWARM_NOTIFY_ROUTER_HEALTH_ADDR = "0.0.0.0:8080"; + swarm-ci-metrics.STATE_DIRECTORY = "/var/lib/swarm-ci-metrics"; + }; + + # Host paths the credentials are loaded from: the host units' own + # `LoadCredential=id:source`, and the router container's nspawn flags. + credentialSources = + lib.concatMap + ( + e: + let + parts = lib.splitString ":" e; + in + lib.optional (lib.length parts > 1) (lib.last parts) + ) + ( + units.swarm-controller.serviceConfig.LoadCredential + ++ units.swarm-ci-metrics.serviceConfig.LoadCredential + ) + ++ map (f: lib.last (lib.splitString ":" f)) allLocal.containers.swarm-notify-router.extraFlags; + credentialIds = lib.concatMap ( + u: map (e: lib.head (lib.splitString ":" e)) u.serviceConfig.LoadCredential + ) (lib.attrValues units); + rendered = builtins.unsafeDiscardStringContext (builtins.toJSON objects); + + ciTimer = allLocal.systemd.timers.swarm-ci-metrics.timerConfig; + cron = objects."swarm-ci-metrics/cronjob".spec; + + # The same host with one more variable on the poller's unit, naming a path + # the pod does not mount. + withStrayPath = lib.recursiveUpdate allLocal { + systemd.services.swarm-ci-metrics.environment.SWARM_CI_METRICS_STRAY = "/etc/stray.json"; + }; + renders = + config: (builtins.tryEval (builtins.deepSeq (builtins.toJSON (render config)) true)).success; + + cases = [ + { + # Each service's own credential path is the control: the comparison + # reads a non-empty environment. + name = "each workload carries its unit's environment, plus only its directories and health listener"; + ok = + lib.all (name: envOf name == unitEnv name // added.${name}) (lib.attrNames units) + && + (envOf "swarm-controller").BAO_CLIENT_CERT + == "/run/credentials/swarm-controller.service/bao-client.pem" + && (envOf "swarm-notify-router") ? SWARM_NOTIFY_ROUTER_NATS_URL; + } + { + # The ids are the control: they are in the same text, so the search + # finds what is there. + name = "the manifests name each credential by id and never the host path it is loaded from"; + ok = + lib.length credentialSources >= 7 + && !(lib.any (s: lib.hasInfix s rendered) credentialSources) + && lib.all (id: lib.hasInfix "\"${id}\"" rendered) credentialIds + && !(lib.any (o: o.kind == "Secret") (lib.attrValues objects)) + && + (lib.head (podSpec "swarm-controller").volumes).secret.secretName == "swarm-controller-credentials"; + } + { + name = "the poller's CronJob runs on its timer's interval and deadline, never overlapping"; + ok = + ciTimer.OnUnitInactiveSec == "5min" + && cron.schedule == "*/5 * * * *" + && cron.concurrencyPolicy == "Forbid" + && cron.jobTemplate.spec.activeDeadlineSeconds == 1800; + } + { + name = "the router's probes reach the listener its variable binds, and every pod outlasts the drain"; + ok = + let + c = container "swarm-notify-router"; + in + (lib.head c.ports).containerPort == 8080 + && c.readinessProbe.httpGet.path == "/readyz" + && c.livenessProbe.httpGet.path == "/healthz" + && lib.all (name: (podSpec name).terminationGracePeriodSeconds > 10) (lib.attrNames units); + } + { + # The unchanged host is the control that the render itself succeeds. + name = "a unit variable naming a path the pod does not mount fails the render"; + ok = renders allLocal && !(renders withStrayPath); + } + ]; +in +runGroup "k8s" cases diff --git a/nix/module-eval/shared.nix b/nix/module-eval/shared.nix index 1e414a17a..4e28228aa 100644 --- a/nix/module-eval/shared.nix +++ b/nix/module-eval/shared.nix @@ -45,8 +45,10 @@ in bareWithController = hiveWithController { }; + # With the k8s manifests rendered too, which changes no unit. allLocal = hiveWithController { deploy.singleHostSwarm = true; + k8s.enable = true; deploy.victorialogs.authPackage = marker "logs"; deploy.victorialogs.grafanaAuthPackage = marker "logs-grafana"; deploy.victoriametrics.authPackage = marker "metrics";