Watch
0
0
Fork
You've already forked hyperhive
0

k8s: deploy.notify-router.runtime moves the router between its container and the cluster

This commit is contained in:
atlas 2026-11-21 15:16:32 +01:00 • committed by maia
commit 30567ad28f
4 changed files with 671 additions and 187 deletions

View file

@ -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;

View file

@ -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 {

View file

@ -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;
}

View file

@ -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;
})
]
);
}