Watch
0
0
Fork
You've already forked hyperhive
0
hyperhive/nix/host-modules/k8s/node.nix
atlas 9f62e71dae run grafana as a pod in the cluster
The Deployment swarm-grafana replaces the swarm-grafana container: one
replica on a static local volume that is the container's data directory,
an init container that fetches the OIDC client secret and creates the
administrator password, the datasources' bearer and the encryption key in
the secret store, and a sidecar that keeps the controller's Viewer token.
The datasources reach the stores through the gateway with that bearer, and
Grafana's /metrics asks for the stores' kind of credential, which the vhost
sends. The five host units, the journal forwarder, its client glue and the
unix-socket directory go with the container.
2026-11-28 10:01:39 +01:00

580 lines
22 KiB
Nix

# The k3s cluster this host runs, as its main node, for the swarm services that
# run in the cluster, the Kubernetes counterpart of `deploy.singleHostSwarm`'s
# all-local swarm, and the agent a host that sets `deploy.k8s.join` runs
# instead. docs/4-implementation/k8s/node.md has the design.
#
# The main node holds the images of the services ./render.nix renders and
# shares them with the nodes that join through k3s's embedded registry mirror
# of the images' registry host. Every swarm service this host enables runs on it,
# so enabling one turns the node on, and a host that turns the node off while it
# enables one fails at evaluation (./runtime.nix applies the manifests).
{
config,
lib,
pkgs,
...
}:
let
cfg = config.services.hyperhive.deploy.k8s;
networkCfg = config.services.hyperhive.network;
# IPv4 CIDR arithmetic on nix's 64-bit integers.
ipToInt =
ip:
builtins.foldl' (acc: x: acc * 256 + x) 0 (
map lib.strings.toIntBase10 (lib.strings.splitString "." ip)
);
pow2 = n: if n == 0 then 1 else 2 * (pow2 (n - 1));
parseCidr =
cidr:
let
parts = lib.strings.splitString "/" cidr;
in
{
base = ipToInt (lib.head parts);
len = lib.strings.toIntBase10 (lib.last parts);
};
# Two ranges overlap when they agree on the leading bits of the shorter one.
overlap =
a: b:
let
pa = parseCidr a;
pb = parseCidr b;
keep = 4294967296 - pow2 (32 - lib.min pa.len pb.len);
in
builtins.bitAnd pa.base keep == builtins.bitAnd pb.base keep;
# The first address of a range, and the dotted form of an integer.
networkOf =
cidr:
let
p = parseCidr cidr;
in
builtins.bitAnd p.base (4294967296 - pow2 (32 - p.len));
intToIp =
n:
lib.concatMapStringsSep "." (d: toString (lib.mod (n / d) 256)) [
16777216
65536
256
1
];
cidrType = lib.types.strMatching "([0-9]{1,3}\\.){3}[0-9]{1,3}/[0-9]{1,2}";
# k3s's own defaults, named so the flags below and the ServiceAccount
# issuer and key paths read from one place.
dataDir = "/var/lib/rancher/k3s";
clusterDomain = "cluster.local";
# k3s's default for `--cluster-dns` is the tenth address of the service
# range (`GetIndexedIP(svcCIDR, 10)` in k3s' `pkg/cli/server/server.go`). It
# 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;
inherit (import ../../images { inherit pkgs lib; }) registryHost;
joinToken = import ../lib/k8s-join-token.nix;
# Mirrors the images' registry host between the nodes, which is how a node
# that holds no copy of an image gets one from a peer that does. The upstream
# `.invalid` host never resolves, so a name no peer holds fails to pull. Only
# this host is mirrored: `"*"` would also route the node's pulls of public
# images through its peers.
# https://docs.k3s.io/installation/registry-mirror
registriesYaml = ''
mirrors:
${registryHost}:
'';
# flannel's WireGuard backend names its device `flannel-wg` and binds
# `ListenPort` (`createWGDev` and `RegisterNetwork` in flannel v0.28's
# `pkg/backend/wireguard/wireguard.go`, the version k3s 1.35 vendors), whose
# default, 51820, is the port of a host's own `wg0` in the semi-spread
# example. k3s writes the backend's config itself and has no option for the
# port, so the node hands it a net-conf through `--flannel-conf`
# (`pkg/executor/embed/embed.go`: a given file is used as is). The fields are
# the ones k3s's own template fills (`flannelConf` and `wireguardNativeBackend`
# in `pkg/agent/flannel/setup.go`) for an IPv4-only cluster, so there is no
# IPv6 port or `flannel-wg-v6`.
flannelWgPort = 51830;
flannelWgIface = "flannel-wg";
flannelNetConf = pkgs.writeText "flannel-net-conf.json" (
builtins.toJSON {
Network = cfg.podCidr;
EnableIPv4 = true;
EnableIPv6 = false;
IPv6Network = "::/0";
Backend = {
Type = "wireguard";
PersistentKeepaliveInterval = 25;
ListenPort = flannelWgPort;
};
}
);
# flannel binds the tunnel to the interface of the default route and names
# that interface's address as the peers' endpoint (`LookupExtInterface` in
# k3s' `pkg/agent/flannel/flannel.go`) unless the node has an external IP and
# the server runs `--flannel-external-ip`, which makes the endpoint that IP
# (the `public-ip-overwrite` annotation, `pkg/subnet/kube/kube.go` in
# flannel). A node with an `address` advertises it, so the tunnel runs on
# the address the firewall admits whatever the default route is.
flannelFlags = [
"--flannel-conf=${flannelNetConf}"
]
++ lib.optional (cfg.address != null) "--node-external-ip=${cfg.address}";
# What the nodes of a cluster reach each other on, and the firewall rules
# that admit those ports from the nodes' addresses and from no others. The
# `extraCommands` run before the firewall's final refusal.
nodePorts = [
{
proto = "tcp";
port = 6443;
}
{
proto = "tcp";
port = 10250;
}
{
proto = "udp";
port = flannelWgPort;
}
{
proto = "tcp";
port = 5001;
}
];
admitNodes =
addresses:
lib.concatMapStrings (
address:
lib.concatMapStrings (p: ''
iptables -A nixos-fw -s ${address} -p ${p.proto} --dport ${toString p.port} -j nixos-fw-accept
'') nodePorts
) addresses;
# The swarm services that run in the cluster, by the name of their
# `deploy.<name>.enable` option.
swarmServices = [
"notify-router"
"stt"
"ci-metrics"
"review-classifier"
"claude-login"
"nats"
"swarm-controller"
"victorialogs"
"victoriametrics"
"grafana"
];
enabledServices = lib.filter (name: deployCfg.${name}.enable) swarmServices;
# The services whose data the module keeps in the cluster. Each puts its state
# label on this node.
stateful = lib.filterAttrs (_: svc: svc.enable) {
inherit (deployCfg)
nats
ci-metrics
victorialogs
victoriametrics
grafana
;
};
in
{
options.services.hyperhive.deploy.k8s = {
enable = lib.mkOption {
type = lib.types.bool;
default = false;
defaultText = lib.literalMD "`true` where the host enables a swarm service that runs in the cluster, else `false`";
description = ''
Run a k3s server on this host, the cluster's main node, with the images of the
swarm services that run in the cluster loaded into it, and render
their manifests (`services.hyperhive.k8s.enable`).
Defaults on where this host enables any swarm service that runs in the
cluster: `deploy.notify-router`, `stt`, `ci-metrics`, `review-classifier`,
`claude-login`, `nats` and `swarm-controller`, which
`services.hyperhive.deploy.singleHostSwarm` and `allSwarmServices` turn
on. Setting it to `false` on such a host fails the evaluation. 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-wg`), so the node
reaches its pods.
'';
};
podCidr = lib.mkOption {
type = cidrType;
default = "10.200.0.0/16";
description = ''
IPv4 range k3s hands pod addresses out of (`--cluster-cidr`). It must
overlap neither the hive bridge's subnet
({option}`services.hyperhive.network.bridgeIp`) nor
{option}`services.hyperhive.deploy.k8s.serviceCidr`, nor any network
the host routes to. k3s's own default, `10.42.0.0/16`, contains the
hive bridge's default subnet. A host that joins sets the same value as
the main node: its flannel reads the range from this option.
'';
};
serviceCidr = lib.mkOption {
type = cidrType;
default = "10.201.0.0/16";
description = ''
IPv4 range k3s hands service cluster IPs out of (`--service-cidr`);
the cluster DNS address is the tenth address of it. The same
constraints as {option}`services.hyperhive.deploy.k8s.podCidr` apply.
'';
};
clusterDomain = lib.mkOption {
type = lib.types.str;
readOnly = true;
internal = true;
default = clusterDomain;
description = ''
The cluster's DNS domain (`--cluster-domain`). A Service is
`<name>.<namespace>.svc.<this>`.
'';
};
clusterDns = lib.mkOption {
type = lib.types.str;
readOnly = true;
internal = true;
default = clusterDns;
description = ''
The address of the cluster's DNS service (`--cluster-dns`): the tenth
address of {option}`services.hyperhive.deploy.k8s.serviceCidr`. The
host's resolver forwards the cluster's domain to it.
'';
};
flannelWgPort = lib.mkOption {
type = lib.types.port;
readOnly = true;
internal = true;
default = flannelWgPort;
description = ''
The UDP port flannel's WireGuard tunnel listens on. The firewall admits
it from the nodes' addresses.
'';
};
cniInterfaces = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [
"cni0"
flannelWgIface
];
readOnly = true;
internal = true;
description = ''
The pod network's interfaces. The firewall trusts them, and a
listener meant for pods only is opened on these and no other.
'';
};
serviceAccountIssuer = lib.mkOption {
type = lib.types.str;
readOnly = true;
internal = true;
default = "https://kubernetes.default.svc.${clusterDomain}";
description = ''
The `iss` claim of the ServiceAccount tokens the cluster issues, the
issuer k3s gives its API server for the cluster domain it runs with.
'';
};
serviceAccountKeyFiles = lib.mkOption {
type = lib.types.listOf lib.types.str;
readOnly = true;
internal = true;
default = [
"${dataDir}/server/tls/service.key"
"${dataDir}/server/tls/service.current.key"
];
description = ''
The files k3s keeps its ServiceAccount keys in: the key that verifies
tokens and the one that signs them, which differ after a rotation.
'';
};
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 enabled services whose data the cluster keeps";
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`, `ci-metrics`, `victorialogs`, `victoriametrics` and `grafana`, each when enabled. 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 is disabled
stays and does nothing, and `kubectl label node <name> <label>-`
removes one.
'';
};
address = lib.mkOption {
type = lib.types.nullOr lib.types.str;
default = null;
example = "192.168.1.10";
description = ''
The address the other nodes of the cluster reach this node on. Set, it
is the node's IP (`--node-ip`) and its external IP
(`--node-external-ip`), so the node's registered address and flannel's
tunnel endpoint are it, and a server also lists it in its API
certificate (`--tls-san`). Null leaves k3s to pick the address of the
default route for the node and for the tunnel.
'';
};
nodeAddresses = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [ ];
example = [
"192.168.1.11"
"192.168.1.12"
];
description = ''
The IPv4 addresses of the nodes that may join this cluster. The
firewall admits the cluster's node-to-node ports (TCP 6443 for the API
and the image mirror, TCP 10250 for the kubelet, UDP ${toString flannelWgPort} for flannel's
WireGuard tunnel, TCP 5001 for the mirror's peers) from these addresses
and from no others. The tunnel authenticates its peers as well: a host
that holds no key the cluster lists gets no frame onto the pod
network, whatever address it sends from. Empty opens none of them. The firewall's
iptables backend is required: the rules are not written for nftables.
'';
};
join = lib.mkOption {
type = lib.types.nullOr (
lib.types.submodule {
options.server = lib.mkOption {
type = lib.types.str;
example = "192.168.1.10";
description = ''
The address of the cluster's main node, the host that sets
{option}`services.hyperhive.deploy.k8s.enable`.
'';
};
}
);
default = null;
description = ''
Make this host a k3s agent of the cluster the main node at `server`
runs, instead of a node of its own. It runs the cluster's pods and none
of the server's manifests or units. It holds no state label or entry
label, so a pod that keeps data on a node's disk does not run here.
The join token comes from the swarm secret store: the main node's
`k3s-join-token-publish` unit writes it, and this host's
`k3s-join-token` unit reads it under the hive's store identity
({option}`services.hyperhive.deploy.hive-controller.tls.baoHiveIdentityCertFile`)
before k3s starts. Set {option}`services.hyperhive.deploy.k8s.address`
to the address the main node reaches this host on, and list it in the
main node's {option}`services.hyperhive.deploy.k8s.nodeAddresses`.
'';
};
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.mkMerge [
{
services.hyperhive.deploy.k8s.enable = lib.mkDefault (enabledServices != [ ] && cfg.join == null);
assertions = [
{
assertion = cfg.enable || cfg.join != null || enabledServices == [ ];
message = ''
services.hyperhive.deploy.k8s.enable is false, and this host enables
swarm services that run only in the cluster: ${
lib.concatMapStringsSep ", " (n: "deploy.${n}.enable") enabledServices
}.
Set services.hyperhive.deploy.k8s.enable to true (it is the default
where one is enabled) or disable those services on this host.
'';
}
];
}
(lib.mkIf cfg.enable {
assertions = [
{
assertion = cfg.join == null;
message = ''
services.hyperhive.deploy.k8s.enable runs this host as the cluster's
main node and services.hyperhive.deploy.k8s.join as a node of another
host's cluster: set one.
'';
}
{
assertion = config.services.hyperhive.k8s.enable;
message = ''
services.hyperhive.deploy.k8s.enable loads the images
services.hyperhive.k8s.enable renders into the node, so it needs
services.hyperhive.k8s.enable to be true.
'';
}
{
assertion =
!networkCfg.enable
|| !(lib.any (overlap networkCfg.networkCidr) [
cfg.podCidr
cfg.serviceCidr
]);
message = ''
services.hyperhive.deploy.k8s.podCidr (${cfg.podCidr}) and
services.hyperhive.deploy.k8s.serviceCidr (${cfg.serviceCidr}) must
not overlap the hive bridge's subnet (${networkCfg.networkCidr}, from
services.hyperhive.network.bridgeIp and bridgePrefixLength): the
bridge and the cluster would route the same addresses.
'';
}
{
assertion = !(overlap cfg.podCidr cfg.serviceCidr);
message = ''
services.hyperhive.deploy.k8s.podCidr (${cfg.podCidr}) and
services.hyperhive.deploy.k8s.serviceCidr (${cfg.serviceCidr}) must
not overlap each other.
'';
}
];
services.hyperhive.k8s.enable = lib.mkDefault true;
services.k3s = {
enable = true;
role = "server";
disable = [
"traefik"
"metrics-server"
];
nodeLabel = lib.mapAttrsToList (k: v: "${k}=${v}") cfg.nodeLabels;
nodeIP = cfg.address;
extraFlags = [
"--secrets-encryption"
"--embedded-registry"
"--cluster-cidr=${cfg.podCidr}"
"--service-cidr=${cfg.serviceCidr}"
"--data-dir=${dataDir}"
"--cluster-domain=${clusterDomain}"
"--cluster-dns=${clusterDns}"
"--flannel-backend=wireguard-native"
"--flannel-external-ip"
]
++ flannelFlags
++ lib.optional (cfg.address != null) "--tls-san=${cfg.address}";
# k3s's own images come first: the mirror holds only the hyperhive
# images, so the node pulls nothing else, not even CoreDNS.
images = [
config.services.k3s.package.airgap-images
]
++ (config.system.build.k8sImages or [ ]);
};
networking.firewall.trustedInterfaces = cfg.cniInterfaces;
networking.firewall.extraCommands = admitNodes cfg.nodeAddresses;
environment.etc."rancher/k3s/registries.yaml".text = registriesYaml;
# The host's resolver (the hive's dnsmasq, which the host's own
# `/etc/resolv.conf` names) hands the cluster's domain to CoreDNS, so a
# Service is reachable from the host by its name. The bridge's agents ask
# the same resolver and get the same answers.
services.dnsmasq.settings.server = lib.mkIf config.services.hyperhive.gateway.dns.enable [
"/${clusterDomain}/${clusterDns}"
];
})
# NetworkManager manages every interface it finds unless told not to, and
# rewrites the routes and addresses of the ones the cluster creates: `cni0`
# (the bridge CNI), `flannel-wg` and the other `flannel*` devices, and the
# host end of each pod's veth pair (`veth*`). The same applies on a joining
# node, which runs the same CNI. A host without NetworkManager is left alone.
(lib.mkIf ((cfg.enable || cfg.join != null) && config.networking.networkmanager.enable) {
networking.networkmanager.unmanaged = [
"interface-name:cni0"
"interface-name:flannel*"
"interface-name:veth*"
];
})
# An agent of another host's cluster. The server's manifests and units are
# not here: the pods it runs come from the main node's API.
(lib.mkIf (cfg.join != null && !cfg.enable) {
assertions = [
{
assertion =
deployCfg.hive-controller.tls.baoHiveIdentityCertFile != null
&& deployCfg.hive-controller.tls.baoHiveIdentityKeyFile != null;
message = ''
services.hyperhive.deploy.k8s.join reads the join token from the
swarm secret store under the hive's identity, so
services.hyperhive.deploy.hive-controller.tls.baoHiveIdentityCertFile
and baoHiveIdentityKeyFile must name it.
'';
}
{
assertion = !config.networking.nftables.enable;
message = ''
services.hyperhive.deploy.k8s.join admits the cluster's ports with
iptables rules, which networking.nftables.enable replaces.
'';
}
];
services.k3s = {
enable = true;
role = "agent";
serverAddr = "https://${cfg.join.server}:6443";
tokenFile = joinToken.file;
nodeIP = cfg.address;
# `--flannel-backend` is a server flag: an agent takes the backend from
# the server's config (`controlConfig.FlannelBackend` in k3s'
# `pkg/agent/config/config.go`). The net-conf is read from the node's own
# file, so the agent names it too, with the pod range the server runs.
extraFlags = flannelFlags;
# k3s's own images first, for the reason the server's are: a node with
# no route to a public registry pulls nothing else.
images = [ config.services.k3s.package.airgap-images ];
};
networking.firewall.trustedInterfaces = cfg.cniInterfaces;
networking.firewall.extraCommands = admitNodes (
lib.unique ([ cfg.join.server ] ++ cfg.nodeAddresses)
);
environment.etc."rancher/k3s/registries.yaml".text = registriesYaml;
})
];
}