Watch
0
0
Fork
You've already forked hyperhive
0
hyperhive/nix/host-modules/k8s/render.nix
atlas d2acf3080a 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.
2026-11-27 21:29:36 +01:00

390 lines
13 KiB
Nix

# 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 "<n>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 \"<n>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