# 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`, 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 # unit names it by, so the environment carries over as it is and a change to a # unit shows up in its manifest. The one change is the store login: a service # the store has a jwt role for (`deploy.bao.k8sPrincipals`) runs under a # ServiceAccount of its name, with a projected token for the store's audience # in place of its client certificate and key. # # 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. A credential that is a public CA file comes from the CA ConfigMap, # not a Secret. { lib, pkgs, config, }: let hyperhiveCfg = config.services.hyperhive; deployCfg = hyperhiveCfg.deploy; 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`. 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. `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; unit = config.systemd.services.swarm-controller; kind = "Deployment"; healthEnv = null; etcFiles = [ "hyperhive/swarm-controller.json" ]; publicCredentials = { }; switch = null; }; swarm-notify-router = { inherit (deployCfg.notify-router) enable package; 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; unit = config.systemd.services.swarm-ci-metrics; timer = config.systemd.timers.swarm-ci-metrics; kind = "CronJob"; healthEnv = null; etcFiles = [ ]; publicCredentials = { }; switch = null; }; }; # Where a pod pushes telemetry: the hive collector, by the name the node's # CoreDNS answers with the bridge address (./host-services.nix). A unit's own # endpoint is a loopback forwarder or a gateway route that needs a token, and # a pod has neither. `otlpEndpointVars` are the variables a unit may name its # endpoint in; the first is the standard one and is always set. otelCfg = hyperhiveCfg.otel; collectorEndpoint = "http://${otelCfg.collector.host}:${toString hyperhiveCfg.swarm.hiveOtel.collectorPort}"; otlpEndpointVars = [ "OTEL_EXPORTER_OTLP_ENDPOINT" "SWARM_CI_METRICS_OTLP_ENDPOINT" ]; podOtlpEnv = unitEnv: lib.optionalAttrs otelCfg.collector.enable ( lib.genAttrs (lib.filter ( n: n == "OTEL_EXPORTER_OTLP_ENDPOINT" || unitEnv ? ${n} ) otlpEndpointVars) (_: collectorEndpoint) ); 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. unitCredIds = 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 ); # A service the store knows by a jwt role as well as by its certificate # logs in with its pod's ServiceAccount token: the pod holds no client # certificate. It reaches the store on the listener that asks for none # (`deploy.bao.podListenerPort`), by the name every reader dials. baoLogin = lib.elem name baoDeployCfg.k8sPrincipals && unitEnv ? BAO_CLIENT_CERT; baoClientCredIds = map ( var: let v = unitEnv.${var} or ""; in if under credDir v then lib.removePrefix "${credDir}/" v else fail name "${var} is not a credential of the unit, which the pod's login drops" ) [ "BAO_CLIENT_CERT" "BAO_CLIENT_KEY" ]; credIds = if baoLogin then lib.subtractLists baoClientCredIds unitCredIds else unitCredIds; baoEnv = { BAO_ADDR = "https://${hyperhiveCfg.swarm.bao.domain}:${toString baoDeployCfg.podListenerPort}"; BAO_AUTH = "jwt"; BAO_JWT_FILE = podAuth.tokenFile; BAO_JWT_ROLE = name; BAO_JWT_MOUNT = podAuth.mount; }; # 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 == trustBundleKey) (lib.attrValues unitEnv) ); env = ( if baoLogin then removeAttrs unitEnv [ "BAO_CLIENT_CERT" "BAO_CLIENT_KEY" ] // baoEnv else unitEnv ) // podOtlpEnv 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 baoLogin podAuth.tokenDir ++ 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}"; # The credentials that are public CA files come from the CA ConfigMap, the # rest from the service's Secret. A volume holding both is a projected # one, which merges them into the one directory the unit's credentials # are in. publicIds = lib.filter (id: svc.publicCredentials ? ${id}) credIds; secretIds = lib.subtractLists publicIds credIds; # 0440: the pod's group reads them, as `LoadCredential` lets the unit's # user read them. credentialsMode = 288; credentialItems = map (id: { key = id; path = id; }); credentialsVolume = if publicIds == [ ] then { name = "credentials"; secret = { secretName = "${name}-credentials"; defaultMode = credentialsMode; items = credentialItems credIds; }; } else { name = "credentials"; projected = { defaultMode = credentialsMode; sources = lib.optional (secretIds != [ ]) { secret = { name = "${name}-credentials"; items = credentialItems secretIds; }; } ++ [ { configMap = { name = caConfigMap; items = map (id: { key = svc.publicCredentials.${id}; path = id; }) publicIds; }; } ]; }; }; volumes = lib.optional (credIds != [ ]) credentialsVolume ++ lib.optional baoLogin { name = "bao-token"; projected = { # 0440, as the credentials: the pod's group reads the token. defaultMode = 288; sources = [ { serviceAccountToken = { audience = podAuth.audience; # The shortest the API server grants. The kubelet refreshes # the file before it expires, and a login reads it afresh. expirationSeconds = 600; path = "token"; }; } ]; }; } ++ lib.optional (caFiles != [ ]) { name = "ca-trust"; configMap.name = caConfigMap; } ++ 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; } ++ lib.optional baoLogin { name = "bao-token"; mountPath = podAuth.tokenDir; readOnly = true; } ++ map (f: { name = "ca-trust"; mountPath = f; subPath = trustBundleKey; 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 ]; # The API token is never mounted; a pod that logs in to the store gets # a token of its own, projected for the store's audience. automountServiceAccountToken = false; enableServiceLinks = false; securityContext = { runAsUser = serviceUser.uid; runAsGroup = serviceUser.gid; fsGroup = serviceUser.gid; seccompProfile.type = "RuntimeDefault"; }; } // lib.optionalAttrs baoLogin { serviceAccountName = name; }; 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 baoLogin { # Named after the service: the store's jwt role binds this account. "${name}/serviceaccount" = { apiVersion = "v1"; kind = "ServiceAccount"; metadata = metaFor name; automountServiceAccountToken = false; }; } // 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 { inherit objects image; }; enabled = lib.mapAttrs workload (lib.filterAttrs (_: svc: svc.enable) services); in { objects = { "namespace" = { apiVersion = "v1"; kind = "Namespace"; metadata = { name = k8sCfg.namespace; labels."app.kubernetes.io/part-of" = "hyperhive"; }; }; } // lib.concatMapAttrs (_: w: w.objects) enabled; # 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; }