# 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"; hiveClientCaKey = "hive-client-ca.pem"; servicesRootKey = "swarm-services-root.pem"; controllerCfg = deployCfg.swarm-controller; controllerOnCluster = controllerCfg.enable && controllerCfg.runtime == "k8s"; controllerTcp = hyperhiveCfg.swarm.controller.tcp; natsCfg = deployCfg.nats; servicesRootPath = "${deployCfg.hive-controller.tls.stateDir}/${servicesRootKey}"; caSources = { ${trustBundleKey} = if caTrust.useSelfSigned then caTrust.caHostPath else null; ${baoServerCaKey} = baoDeployCfg.serverCaFile; # What the controller's pod needs of the hive: the root its listener # trusts the gateway's client leaf by, and the authority it writes into # each hive's store role. Both are public. ${servicesRootKey} = if controllerOnCluster && controllerTcp.enable then servicesRootPath else null; ${hiveClientCaKey} = if controllerOnCluster then controllerCfg.hiveClientCaFile else null; }; # `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 controller's listener leaf: its pod issues the leaf itself, from the # store, with its ServiceAccount token, as the host's # `swarm-controller-tls.service` does with its certificate # (../lib/swarm-controller-tls-issue.nix is the one script). An init # container writes it before the daemon starts and a second container renews # it, both into an emptyDir only the pod holds. tlsIssue = import ../lib/swarm-controller-tls-issue.nix { inherit lib config; }; leafTools = [ baoDeployCfg.package pkgs.jq pkgs.openssl pkgs.coreutils pkgs.gnugrep ]; leafIssueBin = "swarm-controller-tls-issue"; leafRenewBin = "swarm-controller-tls-renew"; leafImagePackage = let issue = pkgs.writeShellScriptBin leafIssueBin '' export PATH=${lib.makeBinPath leafTools} ${tlsIssue.script { login = "bao write -field=token auth/${podAuth.mount}/login role=swarm-controller jwt=@${podAuth.tokenFile}"; credential = "ServiceAccount token"; group = null; createDir = false; }} ''; # The host's timer runs the same check daily: the script leaves a leaf # that is within the first half of its window alone. A failed run (the # store sealed or unreachable) is tried again sooner. renew = pkgs.writeShellScriptBin leafRenewBin '' export PATH=${lib.makeBinPath [ pkgs.coreutils ]} while true; do if ${issue}/bin/${leafIssueBin}; then sleep 86400 else sleep 600 fi done ''; in pkgs.symlinkJoin { name = "swarm-controller-tls"; paths = [ issue renew ]; }; # 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. `publicCredentials` maps the ids of the credentials that # hold a public CA file to their key in the CA ConfigMap, and `publicFiles` # the paths the unit names that hold one to theirs. `listener`, where a # service has one, is the TCP port a Service publishes in the cluster and the # directory the pod's init container writes the leaf to. # `ephemeralState` gives a service an `emptyDir` in place of a claim for its # state directory: what it keeps there is re-derived at start. A pod starts on # whatever volume it gets. # `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 or units # that run the service when it is `"host"`. `otlp` is where the pod pushes # its telemetry: `"hive"` is the hive collector. A swarm-tier producer is # `"own"` and keeps the route its unit names, because the hive collector # stamps the `hive` label on what it forwards and a swarm-level series must # not carry one (../swarm-otel.nix, the swarm tier's own pipeline). # `daemon` is the unit's binary and systemd name where the service's own name # differs, `baoRole` the store role the daemon logs in with, and `pod`, where # a pod holds more than the daemon, a function of the daemon's container # (its environment, mounts and security context) giving the rest: further # containers, init containers, volumes, host aliases, pod settings, objects and # and images. An `otlp` of `"none"` is a daemon that pushes no telemetry of its # own. # `egress`, where a service has it, names the host services (`hostPorts`) its # pod may reach: it gets a NetworkPolicy that allows those and cluster DNS and # admits no ingress. `hostUsers = false` runs the pod in a user namespace of # its own, so its ids map to unprivileged ones on the node. services = { swarm-controller = { inherit (controllerCfg) enable package unit; kind = "Deployment"; healthEnv = "SWARM_CONTROLLER_HEALTH_ADDR"; etcFiles = [ "hyperhive/swarm-controller.json" ]; publicCredentials = { "bao-ca.pem" = baoServerCaKey; "hive-client-ca.pem" = hiveClientCaKey; }; publicFiles = lib.optionalAttrs controllerTcp.enable { ${servicesRootPath} = servicesRootKey; }; # The TCP listener, behind a Service the gateway on the host dials by # name. listener = lib.optionalAttrs controllerTcp.enable { port = controllerTcp.port; tlsDir = controllerCfg.tcp.tlsDir; }; # The unit pushes to the swarm collector's route and mints its own bearer # (../glue-controller-env.nix, `otel_http_client.rs`). otlp = "own"; ephemeralState = true; switch = { inherit (controllerCfg) runtime; hostUnit = "swarm-controller.service"; }; }; # The queue and its auth-callout responder are one pod: the responder is the # daemon below, and the server (with its exporter) is `pod`'s. swarm-nats = { inherit (natsCfg) enable; inherit (natsCfg) pod; package = natsCfg.authPackage; daemon = "swarm-nats-auth"; baoRole = "swarm-nats-auth"; unit = natsCfg.unit; kind = "Deployment"; healthEnv = "SWARM_NATS_AUTH_HEALTH_ADDR"; etcFiles = [ ]; publicCredentials."bao-ca.pem" = baoServerCaKey; otlp = "none"; switch = { inherit (natsCfg) runtime; hostUnit = "container@swarm-nats.service"; }; }; 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; otlp = "hive"; switch = { inherit (deployCfg.notify-router) runtime; hostUnit = "container@swarm-notify-router.service"; }; }; swarm-stt = { inherit (deployCfg.stt) enable package; unit = deployCfg.stt.unit; kind = "Deployment"; healthEnv = "SWARM_STT_HEALTH_ADDR"; etcFiles = [ ]; publicCredentials.stt-bao-server-ca = baoServerCaKey; # The audio it decodes comes from strangers. It reaches the store, the # identity provider and the queue it logs in to and answers on, and # pushes telemetry to the hive collector. egress = [ "store" "identity" "queue" "collector" ]; otlp = "hive"; ephemeralState = true; # Stands in for the unit's `PrivateUsers`: the decoder reads audio that # strangers sent. hostUsers = false; switch = { inherit (deployCfg.stt) runtime; hostUnit = "container@swarm-stt.service"; }; }; swarm-review-classifier = { inherit (deployCfg.review-classifier) enable package; unit = deployCfg.review-classifier.unit; kind = "Deployment"; healthEnv = "SWARM_REVIEW_CLASSIFIER_HEALTH_ADDR"; etcFiles = [ ]; publicCredentials.review-classifier-bao-server-ca = baoServerCaKey; otlp = "hive"; switch = { inherit (deployCfg.review-classifier) runtime; hostUnit = "container@swarm-review-classifier.service"; }; }; swarm-claude-login = { inherit (deployCfg.claude-login) enable package; unit = deployCfg.claude-login.unit; kind = "Deployment"; healthEnv = "SWARM_CLAUDE_LOGIN_HEALTH_ADDR"; etcFiles = [ ]; publicCredentials.claude-login-bao-server-ca = baoServerCaKey; otlp = "hive"; switch = { inherit (deployCfg.claude-login) runtime; hostUnit = "container@swarm-claude-login.service"; }; }; swarm-ci-metrics = { inherit (deployCfg.ci-metrics) enable package; unit = deployCfg.ci-metrics.unit; timer = deployCfg.ci-metrics.timer; kind = "CronJob"; healthEnv = null; etcFiles = [ ]; publicCredentials."bao-ca.pem" = baoServerCaKey; otlp = "own"; # The timer and the service both: the prune unit holds back either, and a # service started by hand cannot run beside the CronJob. switch = { inherit (deployCfg.ci-metrics) runtime; hostUnit = [ "swarm-ci-metrics.timer" "swarm-ci-metrics.service" ]; }; }; }; # Where a pod pushes telemetry. A `"hive"` service pushes to 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. An `"own"` service # keeps its unit's endpoint, a swarm route it logs in to by itself. # `otlpEndpointVars` are the variables a unit may name its endpoint in; the # first is the standard one and is always set for a `"hive"` service. otelCfg = hyperhiveCfg.otel; collectorEndpoint = "http://${otelCfg.collector.host}:${toString hyperhiveCfg.swarm.hiveOtel.collectorPort}"; otlpEndpointVars = [ "OTEL_EXPORTER_OTLP_ENDPOINT" "SWARM_CI_METRICS_OTLP_ENDPOINT" ]; podOtlpEnv = svc: unitEnv: lib.optionalAttrs (svc.otlp == "hive" && 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}"; # A unit's `ExecStart` as argv, split as systemd splits it: on spaces, with # single quotes grouping a word (`lib.escapeShellArg` writes them) and `$$` # standing for `$`. A pod's arguments are not expanded by a shell. splitExec = name: line: let quotes = w: lib.length (lib.splitString "'" w) - 1; step = st: w: let text = if st.open == null then w else "${st.open} ${w}"; in if lib.mod (quotes text) 2 == 1 then st // { open = text; } else { open = null; words = st.words ++ [ text ]; }; split = lib.foldl' step { open = null; words = [ ]; } (lib.filter (w: w != "") (lib.splitString " " line)); unquote = w: if lib.hasInfix "'\\''" w then fail name "ExecStart has an argument with a single quote in it" else builtins.replaceStrings [ "'" "$$" ] [ "" "$" ] w; in if split.open != null then fail name "ExecStart has an unterminated quote" else map unquote split.words; labelsFor = name: { "app.kubernetes.io/name" = name; "app.kubernetes.io/part-of" = "hyperhive"; }; metaFor = name: { inherit name; inherit (k8sCfg) namespace; labels = labelsFor name; }; # The host services a pod's `egress` names, each the TCP port it is reached # on at the bridge's address (./host-services.nix). The node trusts the pod # network's interfaces, so a NetworkPolicy is the only thing that limits # which of the host's ports a pod reaches. The identity provider is the # gateway's vhost: `swarm.authelia.url` names no port. hostPorts = { store = baoDeployCfg.podListenerPort; identity = 443; queue = hyperhiveCfg.swarm.nats.port; collector = hyperhiveCfg.swarm.hiveOtel.collectorPort; }; # What the policy of a pod that reaches `reaches` allows: the cluster's DNS, # those host ports, and the pods of the queue's load balancer where the queue # runs in the cluster, because the `hostPort` they bind is forwarded to them # before the policy sees the packet. The policy selects every pod of the # service for ingress too and allows none, so only the node's own traffic # (the kubelet's probes, which the policy engine always admits) reaches it. networkPolicyOf = name: reaches: let tcp = port: { protocol = "TCP"; inherit port; }; queueOnCluster = natsCfg.enable && natsCfg.runtime == "k8s"; in { apiVersion = "networking.k8s.io/v1"; kind = "NetworkPolicy"; metadata = metaFor name; spec = { podSelector.matchLabels = labelsFor name; policyTypes = [ "Ingress" "Egress" ]; egress = [ { to = [ { namespaceSelector.matchLabels."kubernetes.io/metadata.name" = "kube-system"; podSelector.matchLabels.k8s-app = "kube-dns"; } ]; ports = [ { protocol = "UDP"; port = 53; } (tcp 53) ]; } { to = [ { ipBlock.cidr = "${hyperhiveCfg.network.bridgeIp}/32"; } ]; ports = map (r: tcp hostPorts.${r}) reaches; } ] ++ lib.optional (queueOnCluster && lib.elem "queue" reaches) { to = [ { namespaceSelector.matchLabels."kubernetes.io/metadata.name" = "kube-system"; podSelector.matchLabels = { "svccontroller.k3s.cattle.io/svcname" = "swarm-nats"; "svccontroller.k3s.cattle.io/svcnamespace" = k8sCfg.namespace; }; } ]; ports = [ (tcp hostPorts.queue) ]; }; }; }; # The listener's Service, and the policy that lets only the node reach it. The # cluster's policy engine (kube-router) admits traffic whose source is a local # address of the node to any pod (`--src-type LOCAL`, the rule it labels "from # local node"), and a policy that selects the pod for ingress and allows # nothing refuses every other source. The gateway on the host dials the # Service's name, so its connection reaches the pod from the node; a pod of # the cluster does not. listenerObjects = name: listener: { "${name}/service" = { apiVersion = "v1"; kind = "Service"; metadata = metaFor name; spec = { type = "ClusterIP"; selector = labelsFor name; ports = [ { name = "api"; protocol = "TCP"; port = listener.port; targetPort = "api"; } ]; }; }; "${name}/networkpolicy" = { apiVersion = "networking.k8s.io/v1"; kind = "NetworkPolicy"; metadata = metaFor name; spec = { podSelector.matchLabels = labelsFor name; policyTypes = [ "Ingress" ]; }; }; }; # 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); # A unit's memory setting `what` as a Kubernetes quantity. systemd's K, M, G # and T are powers of 1024, as Kubernetes' Ki, Mi, Gi and Ti are. `infinity` # is `null`, which a limit reads as no limit and a request refuses. memoryOf = what: name: value: let v = toString value; m = builtins.match "([0-9]+)([KMGT]?)" v; in if v == "infinity" then null else if m == null then fail name "${what} is \"${v}\"; only a byte count, optionally with the suffix K, M, G or T, translates" else lib.head m + { "" = ""; K = "Ki"; M = "Mi"; G = "Gi"; T = "Ti"; } .${lib.last m}; memoryLimitOf = memoryOf "MemoryMax"; # A unit's `MemoryMin`, else its `MemoryLow`, as a container's memory # request: the memory systemd keeps for the unit. A unit that sets neither # reserves none, which is `0`. memoryRequestOf = name: sc: let what = if sc ? MemoryMin then "MemoryMin" else "MemoryLow"; v = memoryOf what name sc.${what}; in if !(sc ? MemoryMin || sc ? MemoryLow) then "0" else if v == null then fail name "${what} is \"infinity\"; only a byte count, optionally with the suffix K, M, G or T, translates" else v; # A unit's `CPUQuota`, a percent of one core, as a container's cpu limit in # millicores. cpuLimitOf = name: value: let v = toString value; m = builtins.match "([0-9]+)%" v; in if m == null then fail name "CPUQuota is \"${v}\"; only \"%\" translates" else "${toString (lib.toInt (lib.head m) * 10)}m"; workload = name: svc: let inherit (svc) unit; sc = unit.serviceConfig; listener = svc.listener or { }; publicFiles = svc.publicFiles or { }; daemon = svc.daemon or name; baoRole = svc.baoRole or name; credDir = "/run/credentials/${daemon}.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; ephemeral = svc.ephemeralState or false; # 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 baoRole 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 = baoRole; 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 svc 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 ++ lib.attrNames publicFiles ++ lib.optional (listener != { }) listener.tlsDir ++ 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; bin = daemon; extraContents = lib.optional (storeValues != [ ]) ( pkgs.writeTextDir "share/hyperhive/${name}.env-refs" (lib.concatLines storeValues) ); }; execWords = splitExec name (toString sc.ExecStart); entrypoint = "${svc.package}/bin/${daemon}"; # 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 == [ ] && publicFiles == { })) { name = "ca-trust"; configMap.name = caConfigMap; } ++ lib.optional (listener != { }) { name = "tls"; # In memory: the leaf's key never reaches the node's disk. emptyDir.medium = "Memory"; } ++ lib.optional (runtimeDir != null) { name = "runtime"; emptyDir = { }; } ++ lib.optional (stateDir != null) ( { name = "state"; } // ( if ephemeral then { emptyDir = { }; } else { persistentVolumeClaim.claimName = "${name}-state"; } ) ) ++ lib.optional (svc.etcFiles != [ ]) { name = "etc"; configMap.name = "${name}-etc"; } ++ [ { name = "tmp"; emptyDir = { }; } ]; etcKey = f: builtins.replaceStrings [ "/" ] [ "_" ] f; tlsMount = { name = "tls"; mountPath = listener.tlsDir; }; 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 ++ map (path: { name = "ca-trust"; mountPath = path; subPath = publicFiles.${path}; readOnly = true; }) (lib.attrNames publicFiles) ++ lib.optional (listener != { }) tlsMount ++ 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"; } ]; # The unit's memory and CPU ceilings are the container's limits. They are # caps, not reservations, so the requests are explicit: Kubernetes sets # an unset request to the limit, and the pod would reserve the whole cap # on the node. The memory request is what the unit asks systemd to keep # (`MemoryMin`, else `MemoryLow`), and the cpu request is `0`, since # `CPUQuota` reserves nothing. The pod is then Burstable. The unit's other # resource settings have no pod field and stay on the host: `TasksMax` # has no counterpart (the node's kubelet sets the pids limit), and the pod # keeps the one security shape every pod has, in place of the sandbox # settings (`MemoryDenyWriteExecute`, `SystemCallFilter`, `PrivateUsers`, # ...). limits = lib.optionalAttrs (sc ? MemoryMax && memoryLimitOf name sc.MemoryMax != null) { memory = memoryLimitOf name sc.MemoryMax; } // lib.optionalAttrs (sc ? CPUQuota) { cpu = cpuLimitOf name sc.CPUQuota; }; requests = { memory = memoryRequestOf name sc; cpu = "0"; }; # The listener's Service targets this port by its name. ports = lib.optional (svc.healthEnv != null) { name = "health"; containerPort = healthPort; } ++ lib.optional (listener != { }) { name = "api"; containerPort = listener.port; }; 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 (limits != { } || sc ? MemoryMin || sc ? MemoryLow) { resources = { inherit requests; } // lib.optionalAttrs (limits != { }) { inherit limits; }; } // lib.optionalAttrs (lib.tail execWords != [ ]) { args = lib.tail execWords; } // lib.optionalAttrs (ports != [ ]) { inherit ports; } // lib.optionalAttrs (svc.healthEnv != null) { livenessProbe = { httpGet = { path = "/healthz"; port = "health"; }; periodSeconds = 10; }; readinessProbe = { httpGet = { path = "/readyz"; port = "health"; }; periodSeconds = 10; }; }; # The listener's leaf: issued before the daemon starts, renewed beside it. # Both log in as the pod's account, so they hold the token volume the # daemon's login uses, and the store's CA from the credentials volume. leafImage = mkServiceImage { name = "${name}-tls"; package = leafImagePackage; bin = leafIssueBin; }; # What the service adds to the daemon's pod. extra = { containers = [ ]; initContainers = [ ]; volumes = [ ]; hostAliases = [ ]; podSpec = { }; objects = { }; images = [ ]; } // lib.optionalAttrs (svc ? pod) ( svc.pod { inherit env volumeMounts metaFor; inherit (container) securityContext; } ); leafContainer = { name = "tls-issue"; image = "${leafImage.imageName}:${leafImage.imageTag}"; imagePullPolicy = "Never"; env = lib.mapAttrsToList (n: v: { name = n; value = v; }) ( lib.filterAttrs ( n: _: lib.elem n [ "BAO_ADDR" "BAO_CACERT" ] ) env // { HOME = "/tmp"; } ); volumeMounts = lib.filter ( m: lib.elem m.name [ "credentials" "bao-token" "tls" "tmp" ] ) volumeMounts; inherit (container) securityContext; }; podSpec = { inherit terminationGracePeriodSeconds; volumes = volumes ++ extra.volumes; containers = [ container ] ++ lib.optional (listener != { }) ( leafContainer // { name = "tls-renew"; command = [ "/bin/${leafRenewBin}" ]; } ) ++ extra.containers; # 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; } // lib.optionalAttrs (svc ? hostUsers && !svc.hostUsers) { hostUsers = false; } // lib.optionalAttrs (listener != { } || extra.initContainers != [ ]) { initContainers = lib.optional (listener != { }) leafContainer ++ extra.initContainers; } // lib.optionalAttrs (extra.hostAliases != [ ]) { inherit (extra) hostAliases; } // extra.podSpec; # What the `-etc` ConfigMap holds. A file mounted from it by `subPath` # never sees a later change, so the pod template carries a hash of the # content: a changed file changes the template, and the Deployment rolls. etcData = 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 ); podTemplate = restartPolicy: { metadata = { labels = labelsFor name; } // lib.optionalAttrs (svc.etcFiles != [ ]) { annotations."checksum/etc" = builtins.hashString "sha256" (builtins.toJSON etcData); }; 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; } // extra.objects // lib.optionalAttrs (svc ? egress) { "${name}/networkpolicy" = networkPolicyOf name svc.egress; } // lib.optionalAttrs (listener != { }) (listenerObjects name listener) // 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 && !ephemeral) { "${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 = etcData; }; }; 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.otlp == "own" && !(lib.any (n: unitEnv ? ${n}) otlpEndpointVars) then fail name "the unit names no OTLP endpoint of its own, which the pod would push to" else if svc.healthEnv != null && unitEnv ? ${svc.healthEnv} then fail name "the unit already sets ${svc.healthEnv}" else if svc ? egress && !(lib.all (r: hostPorts ? ${r}) svc.egress) then fail name "egress names a host service the renderer has no port for (${lib.concatStringsSep ", " (lib.attrNames hostPorts)})" else if svc ? egress && listener != { } then fail name "has an egress policy and a listener, which would share one NetworkPolicy" else if lib.head execWords != entrypoint then fail name "ExecStart is not ${entrypoint} with plain arguments" else if lib.any (w: lib.hasInfix "\"" w) execWords then fail name "ExecStart has double-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; # What the pod's other containers run. extraImages = lib.optional (listener != { }) leafImage ++ extra.images; }; 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.unique (lib.concatMap (w: [ w.image ] ++ w.extraImages) (lib.attrValues 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 ); # The services whose pods run in a user namespace. Cheap to read, like `switches`. userNamespaces = lib.attrNames ( lib.filterAttrs (_: svc: svc.enable && svc ? hostUsers && !svc.hostUsers) services ); services = lib.mapAttrs (_: w: { inherit (w) objects; }) enabled; inherit caConfigMap caSources; }