Watch
0
0
Fork
You've already forked hyperhive
0

pin queue and poller state to per-service node labels instead of the hostname

This commit is contained in:
atlas 2026-11-25 21:48:02 +01:00 • committed by maia
commit ff2bdea78d
7 changed files with 348 additions and 40 deletions

View file

@ -0,0 +1,36 @@
# The node labels that pin pods to a node, and the selectors that find them.
# ./node.nix puts the labels on the node; the renderer and the queue's module
# select on them. docs/4-implementation/k8s/node.md has the scheme.
rec {
# The node that holds the data a service keeps in the cluster. One label per
# service, so moving one service's data moves one label.
stateLabel = service: "hyperhive.darkest.space/state-${service}";
# The node the hosts' DNS points at: the pods that hosts dial run there.
entryLabel = "hyperhive.darkest.space/entry";
# k3s's own (docs.k3s.io/networking/networking-services, "Controlling servicelb
# node selection"): once any node carries it, the service load balancer binds
# a published port on the labelled nodes only.
loadBalancerLabel = "svccontroller.k3s.cattle.io/enablelb";
# A pod's `nodeSelector` for a service's state label.
stateSelector = service: {
${stateLabel service} = "true";
};
# A static local volume's `nodeAffinity` for the same label.
stateAffinity = service: {
required.nodeSelectorTerms = [
{
matchExpressions = [
{
key = stateLabel service;
operator = "In";
values = [ "true" ];
}
];
}
];
};
}

View file

@ -67,6 +67,15 @@ let
# is passed explicitly below, so the address the host's resolver forwards
# to and the one CoreDNS gets agree by construction.
clusterDns = intToIp (networkOf cfg.serviceCidr + 10);
labels = import ./labels.nix;
deployCfg = config.services.hyperhive.deploy;
# The services whose data the module keeps in the cluster: those with a
# `runtime` that is `k8s`. Each puts its state label on this node.
stateful = lib.filterAttrs (_: svc: svc.enable && svc.runtime == "k8s") {
inherit (deployCfg) nats ci-metrics;
};
in
{
options.services.hyperhive.deploy.k8s = {
@ -176,6 +185,37 @@ in
'';
};
nodeLabels = lib.mkOption {
type = lib.types.attrsOf lib.types.str;
readOnly = true;
default =
lib.genAttrs [
labels.entryLabel
labels.loadBalancerLabel
] (_: "true")
// lib.mapAttrs' (name: _: lib.nameValuePair (labels.stateLabel name) "true") stateful;
defaultText = lib.literalMD "computed from the services whose `runtime` is `k8s`";
description = ''
The labels this node carries, which the module sets with
`services.k3s.nodeLabel`. The pods and volumes that need a node select
on them, so a node that joins the cluster and has none of them takes
none of those pods.
- `hyperhive.darkest.space/state-<service>` for each service whose data the
cluster keeps: `nats` and `ci-metrics`, each when its `runtime` is
`k8s`. A volume's `nodeAffinity` and the pod's `nodeSelector` name it.
- `hyperhive.darkest.space/entry`: the node the hosts' DNS points at.
- `svccontroller.k3s.cattle.io/enablelb`: with it on any node, the
service load balancer binds a published port on the labelled nodes
only, so a joined node does not publish the queue's port.
k3s puts these on the node's object at every start, registered or not.
It never takes one off: a label left from a service that has moved
back to `host` stays and does nothing, and `kubectl label node <name>
<label>-` removes one.
'';
};
manifestDir = lib.mkOption {
type = lib.types.str;
readOnly = true;
@ -232,6 +272,7 @@ in
"traefik"
"metrics-server"
];
nodeLabel = lib.mapAttrsToList (k: v: "${k}=${v}") cfg.nodeLabels;
extraFlags = [
"--secrets-encryption"
"--cluster-cidr=${cfg.podCidr}"

View file

@ -46,6 +46,7 @@ let
controllerOnCluster = controllerCfg.enable && controllerCfg.runtime == "k8s";
controllerTcp = hyperhiveCfg.swarm.controller.tcp;
natsCfg = deployCfg.nats;
labels = import ./labels.nix;
servicesRootPath = "${deployCfg.hive-controller.tls.stateDir}/${servicesRootKey}";
caSources = {
${trustBundleKey} = if caTrust.useSelfSigned then caTrust.caHostPath else null;
@ -275,6 +276,13 @@ let
healthEnv = null;
etcFiles = [ ];
publicCredentials."bao-ca.pem" = baoServerCaKey;
# A static local volume on the unit's own state directory, in place of the
# default class: it binds only on the node with the service's state label
# (./labels.nix).
localState = {
service = "ci-metrics";
hostDir = deployCfg.ci-metrics.hostStateDir;
};
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.
@ -551,6 +559,8 @@ let
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;
localState = svc.localState or null;
stateClaim = if localState != null then "${name}-store" else "${name}-state";
# PATH holds only NixOS's default tools (checked below), which the image
# does not carry. `%d` is systemd's specifier for the credential
@ -732,9 +742,7 @@ let
{
name = "state";
}
// (
if ephemeral then { emptyDir = { }; } else { persistentVolumeClaim.claimName = "${name}-state"; }
)
// (if ephemeral then { emptyDir = { }; } else { persistentVolumeClaim.claimName = stateClaim; })
)
++ lib.optional (svc.etcFiles != [ ]) {
name = "etc";
@ -957,6 +965,9 @@ let
}
// lib.optionalAttrs baoLogin { serviceAccountName = name; }
// lib.optionalAttrs (svc ? hostUsers && !svc.hostUsers) { hostUsers = false; }
// lib.optionalAttrs (localState != null) {
nodeSelector = labels.stateSelector localState.service;
}
// lib.optionalAttrs (listener != { } || extra.initContainers != [ ]) {
initContainers = lib.optional (listener != { }) leafContainer ++ extra.initContainers;
}
@ -1048,10 +1059,30 @@ let
"${name}/persistentvolumeclaim" = {
apiVersion = "v1";
kind = "PersistentVolumeClaim";
metadata = metaFor "${name}-state";
metadata = metaFor stateClaim;
spec = {
accessModes = [ "ReadWriteOnce" ];
resources.requests.storage = "1Gi";
}
// lib.optionalAttrs (localState != null) {
storageClassName = stateClaim;
volumeName = stateClaim;
};
};
}
// lib.optionalAttrs (stateDir != null && !ephemeral && localState != null) {
"${name}/persistentvolume" = {
apiVersion = "v1";
kind = "PersistentVolume";
# Cluster-scoped: no namespace.
metadata = removeAttrs (metaFor stateClaim) [ "namespace" ];
spec = {
capacity.storage = "1Gi";
accessModes = [ "ReadWriteOnce" ];
persistentVolumeReclaimPolicy = "Retain";
storageClassName = stateClaim;
local.path = localState.hostDir;
nodeAffinity = labels.stateAffinity localState.service;
};
};
}

View file

@ -61,6 +61,10 @@ let
onK8s = cfg.runtime == "k8s";
# Where the host unit's `StateDirectory` is: `DynamicUser` keeps it under
# `/var/lib/private`, so the pod's volume is the directory the unit uses.
hostStateDir = "/var/lib/private/${unit}";
# `hostUnit`: a host service, so the bundle reads the host CA path and waits
# on `hive-tls-ca.service`. `enable`: `imports` is unconditional, so without
# it a host with the poller off gets the bundle unit and an `ExecStart`-less
@ -209,16 +213,28 @@ in
configuration must enable. A switch moves the poller: the service and
timer go and the CronJob is applied, or the CronJob is deleted and the
service and timer return, so one poller runs at any time. Its cursor is
in the service's state directory on the host, and in a volume of the
cluster in a pod; neither moves with the poller, so the first pass after
a switch pushes every run again, as the same points. The pod starts on
its empty volume with no gate.
in the service's state directory on the host, and the cluster's volume
for it is on that directory, so a switch moves the process and not the
cursor. The pod runs on the node with the
`hyperhive.darkest.space/state-ci-metrics` label, which the node
module sets, and starts with no gate.
The poller keeps pushing to the swarm collector's route of its own,
not to the hive collector the cluster's other pods push to.
'';
};
hostStateDir = lib.mkOption {
type = lib.types.str;
readOnly = true;
internal = true;
default = hostStateDir;
description = ''
The directory the poller's service keeps its cursor in on the host,
which the cluster's volume for it is on (./k8s/render.nix).
'';
};
unit = lib.mkOption {
type = lib.types.raw;
readOnly = true;
@ -287,6 +303,14 @@ in
# name, which the cluster resolves to the hive bridge.
(lib.mkIf (cfg.enable && onK8s) {
services.hyperhive.network.enable = lib.mkDefault true;
# The pod's local volume needs its directory to exist before the pod
# starts, which on a host that never ran the service nothing else makes.
# The parent is the one the service manager makes for a dynamic user.
systemd.tmpfiles.rules = [
"d /var/lib/private 0700 root root -"
"d ${hostStateDir} 0700 root root -"
];
})
];
}

View file

@ -25,6 +25,8 @@ let
machine = "swarm-nats";
labels = import ./k8s/labels.nix;
# The container's journal forwarder pushes to its own receiver on the swarm
# collector, the route `serviceProducers.swarm-nats` in
# ./swarm-otel-service.nix declares, by the collector's gateway name.
@ -958,10 +960,16 @@ let
}
];
podSpec = {
shareProcessNamespace = true;
# Only the node with the queue's state label runs the pod: the volume's
# affinity says the same, and a node without it shows as no match
# instead of a volume that cannot bind.
nodeSelector = labels.stateSelector "nats";
};
# The server and the responder dial the queue by its name, which the pod
# answers with its own loopback: the leaf carries the name and no IP.
podSpec.shareProcessNamespace = true;
hostAliases = [
{
ip = "127.0.0.1";
@ -1056,17 +1064,7 @@ let
persistentVolumeReclaimPolicy = "Retain";
storageClassName = stateClass;
local.path = hostStoreDir;
nodeAffinity.required.nodeSelectorTerms = [
{
matchExpressions = [
{
key = "kubernetes.io/hostname";
operator = "In";
values = [ (lib.toLower config.networking.hostName) ];
}
];
}
];
nodeAffinity = labels.stateAffinity "nats";
};
};

View file

@ -885,6 +885,7 @@ let
lib.sort lib.lessThan (map (o: o.kind) onCluster.services.k3s.manifests.swarm-ci-metrics.content)
== [
"CronJob"
"PersistentVolume"
"PersistentVolumeClaim"
"ServiceAccount"
];
@ -1845,27 +1846,28 @@ let
&& (volume "nats-data").persistentVolumeClaim.claimName == pvc.metadata.name
&& pvc.spec.accessModes == [ "ReadWriteOnce" ]
# The claim binds by name the static local volume on the container's
# store directory, on this node, and only that: its class is its own.
# The poller's claim is the control that a claim does not.
# store directory, and only that: its class is its own.
&& pvc.spec.volumeName == pv.metadata.name
&& pvc.spec.storageClassName == pv.spec.storageClassName
&& pv.spec.storageClassName != ""
&& !(objects."swarm-ci-metrics/persistentvolumeclaim".spec ? volumeName)
&& pv.spec.local.path == hostStore
&& pv.spec.persistentVolumeReclaimPolicy == "Retain"
&& !(pv.metadata ? namespace)
# It binds on the node with the queue's state label, and the pod runs
# only there.
&&
pv.spec.nodeAffinity.required.nodeSelectorTerms == [
{
matchExpressions = [
{
key = "kubernetes.io/hostname";
key = "hyperhive.darkest.space/state-nats";
operator = "In";
values = [ (lib.toLower allLocal.networking.hostName) ];
values = [ "true" ];
}
];
}
]
&& spec.nodeSelector == { "hyperhive.darkest.space/state-nats" = "true"; }
# A pod on a host that never ran the container gets the directory made;
# a host with the container needs no rule.
&& lib.any (lib.hasPrefix "d ${hostStore} ") onCluster.systemd.tmpfiles.rules
@ -1912,7 +1914,7 @@ let
}
&& !(objects ? "swarm-controller/persistentvolumeclaim")
&& !(objects ? "swarm-stt/persistentvolumeclaim")
&& (stateVolume "swarm-ci-metrics").persistentVolumeClaim.claimName == "swarm-ci-metrics-state"
&& (stateVolume "swarm-ci-metrics").persistentVolumeClaim.claimName == "swarm-ci-metrics-store"
&& objects ? "swarm-ci-metrics/persistentvolumeclaim"
&& !(lib.any (n: lib.hasInfix "state-gate" n) (map toString withNode.system.build.k8sImages))
&& objects ? "swarm-nats/persistentvolumeclaim";
@ -2220,6 +2222,79 @@ let
&& problems withCaps != [ ]
&& problems withoutSeccomp != [ ];
}
{
# Each fixture is the control for the other: the host with the services
# on the host has the entry labels only, the one with them in the
# cluster has those and a state label each. The host without the node
# labels nothing.
name = "the node labels itself as the entry node, and with a state label for each service whose data the cluster keeps";
ok =
let
entry = [
"hyperhive.darkest.space/entry=true"
"svccontroller.k3s.cattle.io/enablelb=true"
];
sorted = lib.sort lib.lessThan;
in
sorted onCluster.services.k3s.nodeLabel == sorted (
entry
++ [
"hyperhive.darkest.space/state-nats=true"
"hyperhive.darkest.space/state-ci-metrics=true"
]
)
&& sorted withNode.services.k3s.nodeLabel == sorted entry
&&
onCluster.services.hyperhive.deploy.k8s.nodeLabels == {
"hyperhive.darkest.space/entry" = "true";
"svccontroller.k3s.cattle.io/enablelb" = "true";
"hyperhive.darkest.space/state-nats" = "true";
"hyperhive.darkest.space/state-ci-metrics" = "true";
}
&& allLocal.services.k3s.nodeLabel == [ ];
}
{
# The queue's pod is the control for the poller's lookups, and the
# stateless pods for the absence of a selector. `nodeAffinity` is in the
# text the hostname is searched in.
name = "the poller's claim is a static local volume on the service's directory, and the volumes and pods of the queue and the poller name their state label, with no hostname in any object";
ok =
let
pv = objects."swarm-ci-metrics/persistentvolume";
pvc = objects."swarm-ci-metrics/persistentvolumeclaim";
spec = podSpec "swarm-ci-metrics";
state = lib.findFirst (v: v.name == "state") null spec.volumes;
text = builtins.toJSON objects + builtins.toJSON onCluster.services.hyperhive.k8s.rendered.services;
hostDir = "/var/lib/private/swarm-ci-metrics";
rule = "d ${hostDir} 0700 root root -";
in
pv.spec.nodeAffinity.required.nodeSelectorTerms == [
{
matchExpressions = [
{
key = "hyperhive.darkest.space/state-ci-metrics";
operator = "In";
values = [ "true" ];
}
];
}
]
&& spec.nodeSelector == { "hyperhive.darkest.space/state-ci-metrics" = "true"; }
&& pv.spec.local.path == hostDir
&& pv.spec.persistentVolumeReclaimPolicy == "Retain"
&& !(pv.metadata ? namespace)
&& pvc.spec.volumeName == pv.metadata.name
&& pvc.spec.storageClassName == pv.spec.storageClassName
&& pv.spec.storageClassName != ""
&& state.persistentVolumeClaim.claimName == pvc.metadata.name
&& !(podSpec "swarm-controller" ? nodeSelector)
&& !(podSpec "swarm-stt" ? nodeSelector)
&& (podSpec "swarm-nats").nodeSelector == { "hyperhive.darkest.space/state-nats" = "true"; }
&& lib.hasInfix "nodeAffinity" text
&& !(lib.hasInfix "kubernetes.io/hostname" text)
&& lib.elem rule onCluster.systemd.tmpfiles.rules
&& !(lib.elem rule withNode.systemd.tmpfiles.rules);
}
];
in
runGroup "k8s" cases

View file

@ -364,6 +364,11 @@ pkgs.testers.runNixOSTest {
NODE = "${nodeIp}"
BRIDGE = "${bridgeIp}"
CONTROL = ${toString controlPort}
STATE_LABEL = "hyperhive.darkest.space/state-nats"
ENTRY_LABELS = {
"hyperhive.darkest.space/entry": "true",
"svccontroller.k3s.cattle.io/enablelb": "true",
}
MANIFESTS = "/var/lib/rancher/k3s/server/manifests"
SERVICES_ROOT = "${tlsDir}/swarm-services-root.pem"
TOKEN = "${routerToken}"
@ -447,6 +452,10 @@ pkgs.testers.runNixOSTest {
return name
def node_labels() -> dict:
return json.loads(kube(machine, "get node -o json"))["items"][0]["metadata"]["labels"]
def switch(target: str) -> str:
"""Switches to `target`. Units of this host that fail for reasons of
their own make the exit status 4; the units the switch is about must
@ -609,6 +618,14 @@ pkgs.testers.runNixOSTest {
assert int(machine.succeed(f"find {HOST_STORE} -type f | wc -l")) > 0
assert machine.succeed(f"find {HOST_STORE} ! -uid {HOST_UID} | wc -l").strip() == "0"
# The node registers with the entry labels only. The switch is the upgrade of
# a node that registered before the queue was in the cluster: it gets the
# state label at the restart of k3s, and the volume and the pod select on it.
with subtest("the node registered with the entry labels and no state label while the queue runs in its container"):
labels = node_labels()
assert all(labels.get(k) == v for k, v in ENTRY_LABELS.items()), labels
assert STATE_LABEL not in labels, labels
with subtest("the switch to the cluster stops the container before it applies the pod"):
out = switch("/run/booted-system/specialisation/k8s")
assert HOST_UNIT in out and "stopping the following units" in out, out
@ -654,6 +671,38 @@ pkgs.testers.runNixOSTest {
print(limits)
assert int(limits.split()[3]) >= 800000, limits
with subtest("the switch gave the registered node the state label, and the volume and the pod select on it"):
labels = node_labels()
assert labels.get(STATE_LABEL) == "true", labels
assert all(labels.get(k) == v for k, v in ENTRY_LABELS.items()), labels
volume = json.loads(kube(machine, f"get pv {SERVICE}-store -o json"))
assert volume["status"]["phase"] == "Bound", volume["status"]
assert volume["spec"]["claimRef"]["name"] == f"{SERVICE}-store", volume["spec"]
assert volume["spec"]["nodeAffinity"]["required"]["nodeSelectorTerms"] == [
{"matchExpressions": [{"key": STATE_LABEL, "operator": "In", "values": ["true"]}]}
], volume["spec"]
assert pod(machine, pod_name)["spec"]["nodeSelector"] == {STATE_LABEL: "true"}, pod(machine, pod_name)["spec"]
assert "kubernetes.io/hostname" not in json.dumps(volume["spec"]), volume["spec"]
with subtest("a node without the state label cannot run the pod, and the pod starts when the label returns"):
node = machine.succeed("kubectl get node -o name").strip()
old_uid = pod(machine, pod_name)["metadata"]["uid"]
kube(machine, f"label {node} {STATE_LABEL}-")
assert STATE_LABEL not in node_labels()
kube(machine, f"delete pod {pod_name} --wait=true --timeout=120s", 150)
unscheduled = (
f"kubectl -n {NS} get pods --selector app.kubernetes.io/name={SERVICE} -o json "
"| jq -r '.items[].status.conditions[]? | select(.type == \"PodScheduled\" and .status == \"False\") | .message'"
)
machine.wait_until_succeeds(f"{unscheduled} | grep -q .", timeout=120)
message = machine.succeed(unscheduled)
assert "node affinity" in message, message
assert pods() != [] and counts()[0] == 0, (pods(), counts())
kube(machine, f"label {node} {STATE_LABEL}=true")
pod_name = wait_pod_ready(old_uid)
assert node_labels().get(STATE_LABEL) == "true"
assert counts() == (1, 1), counts()
with subtest("the exporter is a ClusterIP Service, and the pod's policy admits the client port from any source and nothing else"):
svc = json.loads(kube(machine, f"get service {METRICS_SERVICE} -o json"))
assert svc["spec"]["type"] == "ClusterIP", svc["spec"]
@ -801,6 +850,9 @@ pkgs.testers.runNixOSTest {
assert 0 < pruned <= started, (pruned, started)
requires = machine.succeed(f"systemctl show -p Requires --value {HOST_UNIT}")
assert f"{PRUNE}.service" in requires, requires
# k3s adds labels and never takes one off: the label stays and does
# nothing while the container runs.
assert node_labels().get(STATE_LABEL) == "true", node_labels()
# The volume is kept for the next switch.
assert json.loads(kube(machine, f"get pvc {SERVICE}-store -o json"))["metadata"]["uid"] == STATE_VOLUME
settle(QUEUE_UP, 600, [HOST_UNIT])