Watch
0
0
Fork
You've already forked hyperhive
0

k8s: the controller's listener is a ClusterIP service the host dials by name

The controller's api port was a hostPort on the node, which Pod Security baseline and restricted forbid. It is a ClusterIP Service now, behind a NetworkPolicy that admits only the node. The host's resolver (the hive's dnsmasq) forwards cluster.local to CoreDNS, and the gateway dials the Service by name through nginx's resolver. tcp.hostAddress goes.
This commit is contained in:
atlas 2026-11-23 17:20:22 +01:00 • committed by maia
commit 3cf89f25f1
5 changed files with 355 additions and 103 deletions

View file

@ -40,12 +40,33 @@ let
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);
in
{
options.services.hyperhive.deploy.k8s = {
@ -93,6 +114,29 @@ in
'';
};
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.
'';
};
cniInterfaces = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [
@ -194,6 +238,7 @@ in
"--service-cidr=${cfg.serviceCidr}"
"--data-dir=${dataDir}"
"--cluster-domain=${clusterDomain}"
"--cluster-dns=${clusterDns}"
];
# k3s's own images come first: with no registry the node pulls nothing,
# not even CoreDNS.
@ -204,5 +249,13 @@ in
};
networking.firewall.trustedInterfaces = cfg.cniInterfaces;
# 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}"
];
};
}

View file

@ -134,8 +134,8 @@ let
# /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 the pod publishes on the node
# (`hostAddress`) and the directory its init container writes the leaf to.
# 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.
@ -168,11 +168,10 @@ let
"hive-client-ca.pem" = hiveClientCaKey;
};
publicFiles = lib.optionalAttrs controllerTcp.enable { ${servicesRootPath} = servicesRootKey; };
# The TCP listener, as a `hostPort` on the node's address: the gateway
# on the host dials it there.
# The TCP listener, behind a Service the gateway on the host dials by
# name.
listener = lib.optionalAttrs controllerTcp.enable {
port = controllerTcp.port;
hostAddress = controllerCfg.tcp.hostAddress;
tlsDir = controllerCfg.tcp.tlsDir;
};
# The unit pushes to the swarm collector's route and mints its own bearer
@ -423,6 +422,42 @@ let
};
};
# 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 "<n>min", the only form these units use.
minutesOf =
name: what: value:
@ -776,8 +811,7 @@ let
cpu = "0";
};
# `hostPort` publishes the listener on the node's address. The cluster's
# portmap plugin forwards it to the pod, so it reaches this one node.
# The listener's Service targets this port by its name.
ports =
lib.optional (svc.healthEnv != null) {
name = "health";
@ -786,8 +820,6 @@ let
++ lib.optional (listener != { }) {
name = "api";
containerPort = listener.port;
hostPort = listener.port;
hostIP = listener.hostAddress;
};
container = {
@ -994,6 +1026,7 @@ let
// 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" = {
@ -1031,6 +1064,8 @@ let
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

View file

@ -145,7 +145,7 @@ in
exit 0
fi
${apiReady}
${kubectl} --namespace ${cfg.namespace} delete deployment,cronjob,serviceaccount,networkpolicy \
${kubectl} --namespace ${cfg.namespace} delete deployment,cronjob,serviceaccount,networkpolicy,service \
--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

View file

@ -17,7 +17,7 @@
#
# `deploy.swarm-controller.runtime = "k8s"` runs the daemon as a pod in this
# host's cluster instead (./k8s/render.nix renders it from the unit below). The
# unit is then disabled, and the gateway dials the pod's `hostPort`.
# unit is then disabled, and the gateway dials the pod's Service by name.
{
pkgs,
lib,
@ -635,7 +635,8 @@ in
The pod needs the TCP listener
({option}`services.hyperhive.swarm.controller.tcp.enable`): the host
cannot reach a unix socket inside a pod, so the gateway dials the
listener on {option}`tcp.hostAddress`. The pod's state directory is an
listener, which a Service in the cluster publishes at
{option}`tcp.serviceHost`. The pod's state directory is an
`emptyDir`: the operator grant record is in the queue's key-value
store, and what is left in the directory (the forge avatar markers, the
legacy webhook secret the store also holds) is made again at start. A
@ -790,23 +791,22 @@ in
With {option}`services.hyperhive.deploy.swarm-controller.runtime` set
to `k8s` this is the bind inside the pod, so it must stay `0.0.0.0`.
The node's address is {option}`hostAddress`.
'';
};
hostAddress = lib.mkOption {
serviceHost = lib.mkOption {
type = lib.types.str;
default = config.services.hyperhive.network.bridgeIp;
defaultText = lib.literalExpression "config.services.hyperhive.network.bridgeIp";
readOnly = true;
internal = true;
default = "swarm-controller.${config.services.hyperhive.k8s.namespace}.svc.${config.services.hyperhive.deploy.k8s.clusterDomain}";
defaultText = lib.literalExpression ''"swarm-controller.<namespace>.svc.<cluster domain>"'';
description = ''
With {option}`services.hyperhive.deploy.swarm-controller.runtime` set
to `k8s`: the node address the pod's `hostPort` binds and the gateway
dials. The default is the hive bridge's address, the one the pods
already reach the host's services on. The gateway verifies the
listener's certificate as
{option}`services.hyperhive.swarm.controller.tcp.domain`, not as
this address. A `hostPort` reaches one node: a cluster of several
nodes needs a Service instead.
to `k8s`: the name of the Service in front of the pod's listener,
which the gateway dials. The host's resolver answers it through the
cluster's DNS. The gateway verifies the listener's certificate as
{option}`services.hyperhive.swarm.controller.tcp.domain`, not as this
name.
'';
};
@ -939,8 +939,8 @@ in
users.groups.swarm-controller = { };
users.groups.${clientsGroup} = { };
# The pod's `hostPort` is on the hive bridge's address by default, and the
# cluster's pods reach the host's services through the bridge.
# The cluster's pods reach the host's services through the bridge, and the
# host's resolver (the hive's dnsmasq, on the bridge) answers the Service's name.
services.hyperhive.network.enable = lib.mkIf onK8s (lib.mkDefault true);
# Through the unit, not `users.users.nginx.extraGroups`: systemd resolves
@ -1028,8 +1028,16 @@ in
services.hyperhive.deploy.swarm-controller.tcp.listenAddress is
"${tcpHost.listenAddress}", and with runtime = "k8s" it is the bind
inside the pod, where any address but "0.0.0.0" leaves the listener
unbound and the pod NotReady. Leave it at "0.0.0.0"; the node's
address is services.hyperhive.deploy.swarm-controller.tcp.hostAddress.
unbound and the pod NotReady. Leave it at "0.0.0.0".
'';
}
{
assertion = !onK8s || config.services.hyperhive.gateway.dns.enable;
message = ''
services.hyperhive.deploy.swarm-controller.runtime = "k8s" needs
services.hyperhive.gateway.dns.enable: the gateway dials the pod's
Service by name, and the hive's resolver is what hands the cluster's
domain to its DNS. Set it, or leave the controller's runtime at "host".
'';
}
{

View file

@ -107,17 +107,20 @@ let
# `toString` below so an unset `domain` reaches the assertion that names it
# instead of failing evaluation first.
controllerTcp = swarmCfg.controller.tcp;
# In the cluster the listener is the pod's `hostPort` on the node's address.
# The name the certificate is verified as stays `tcp.domain`
# (`controllerDial`), so the address needs no certificate of its own.
controllerAddress =
if deployCfg.swarm-controller.runtime == "k8s" then
deployCfg.swarm-controller.tcp.hostAddress
else
toString controllerTcp.domain;
# In the cluster the listener is behind a Service, which the host's resolver
# answers through the cluster's DNS. The upstream is a variable, so nginx asks
# the resolver per request: a name in the `proxy_pass` is looked up when the
# configuration loads, which fails the load while the cluster is not up and
# keeps the address of a Service that has since been recreated. The name the
# certificate is verified as stays `tcp.domain` (`controllerDial`), so the
# Service needs no certificate name of its own.
controllerOnCluster = deployCfg.swarm-controller.runtime == "k8s";
controllerUpstream =
if controllerTcp.enable then
"https://${controllerAddress}:${toString controllerTcp.port}"
if controllerOnCluster then
"https://$swarm_controller_upstream"
else
"https://${toString controllerTcp.domain}:${toString controllerTcp.port}"
else
"http://unix:${deployCfg.swarm-controller.socketPath}:";
# `proxy_http_version` and `Connection` because `recommendedProxySettings`,
@ -125,6 +128,10 @@ let
# them nginx speaks HTTP/1.0 to the upstream, which ends the SSE streams'
# keep-alive.
controllerDial = lib.optionalString controllerTcp.enable ''
${lib.optionalString controllerOnCluster ''
resolver ${config.services.hyperhive.network.bridgeIp} valid=10s ipv6=off;
set $swarm_controller_upstream ${deployCfg.swarm-controller.tcp.serviceHost}:${toString controllerTcp.port};
''}
${gatewayCfg.lib.verifiedProxyToWithClientCert (toString controllerTcp.domain) {
certificate = deployCfg.swarm-controller.tcp.gatewayClientCertFile;
key = deployCfg.swarm-controller.tcp.gatewayClientKeyFile;