let a second machine join the main node's k3s and run pods from images only the main node holds
This commit is contained in:
parent
aab13d065f
commit
7819ed2dbd
20 changed files with 1106 additions and 96 deletions
|
|
@ -60,6 +60,7 @@ jobs:
|
|||
- k8s-runtime-switch
|
||||
- k8s-controller-switch
|
||||
- k8s-nats-switch
|
||||
- k8s-join
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
if: inputs.test == '' || inputs.test == matrix.test
|
||||
|
|
|
|||
|
|
@ -26,7 +26,7 @@ the container environment).
|
|||
## The image set
|
||||
|
||||
Each of these is a flake package named `image-<daemon>`, and the image name is
|
||||
`hyperhive/<daemon>`:
|
||||
`registry.hyperhive.invalid/<daemon>` ([the registry host](#the-registry-host)):
|
||||
|
||||
- `swarm-controller`
|
||||
- `swarm-nats-auth`
|
||||
|
|
@ -55,6 +55,41 @@ nix eval --raw .#image-swarm-logs-auth.imageName
|
|||
nix eval --raw .#image-swarm-logs-auth.imageTag
|
||||
```
|
||||
|
||||
## The registry host
|
||||
|
||||
Every image name starts with `registry.hyperhive.invalid`, which
|
||||
`mkServiceImage` takes from `registryHost` in `nix/images/default.nix`.
|
||||
RFC 6761 reserves `.invalid`, and it never resolves, so the name has no
|
||||
registry behind it. Containerd expands a name with no host, such as
|
||||
`hyperhive/<daemon>`, to `docker.io/hyperhive/<daemon>`, and a node that holds
|
||||
no copy would ask Docker Hub for it. With this host the pull fails instead.
|
||||
|
||||
## Where a node gets an image
|
||||
|
||||
The main node imports the tarballs into containerd before k3s starts, and
|
||||
k3s's embedded registry mirror (`--embedded-registry`, on the main node) shares
|
||||
what a node holds with the others. `/etc/rancher/k3s/registries.yaml` on every
|
||||
node enables the mirror for the one host:
|
||||
|
||||
```yaml
|
||||
mirrors:
|
||||
registry.hyperhive.invalid:
|
||||
```
|
||||
|
||||
k3s documents the flag, the file and the rule that applies here: a node shares
|
||||
images it imported from a tarball when their tag names a registry the file
|
||||
enables for mirroring, and the upstream registry doesn't have to exist
|
||||
(<https://docs.k3s.io/installation/registry-mirror>). The file names only this
|
||||
host and not `"*"`, so the node's pulls of public images stay direct.
|
||||
|
||||
A pod that lands on a node without its image, a node that joined, pulls the
|
||||
image from a peer that holds it (`imagePullPolicy: IfNotPresent`). If no peer
|
||||
holds it, for instance because the main node is down and the node never had
|
||||
the image, the pull fails with the host's name in the error, and the pod
|
||||
retries once a peer has the image. Images a node holds stay: k3s doesn't
|
||||
prune imported tarball images. The mirror doesn't share a `latest` tag, and
|
||||
the tags here are content hashes.
|
||||
|
||||
## Loading an image
|
||||
|
||||
`nix build` produces a `.tar.gz` that `podman load`, `skopeo` and the k3s image
|
||||
|
|
|
|||
|
|
@ -94,7 +94,8 @@ credential directory.
|
|||
too. Where the environment names none, the image is the flake's
|
||||
`image-<service>`. The manifest carries the image name and tag but doesn't
|
||||
depend on the image: building the manifests builds no daemon.
|
||||
`imagePullPolicy` is `Never`, because the node imports the image tarball.
|
||||
`imagePullPolicy` is `IfNotPresent`: the node imports the image tarball, and a
|
||||
node that joined pulls it from a peer ([Service images](images.md#where-a-node-gets-an-image)).
|
||||
- **Security:** the `serviceUser` uid and gid from [Service images](images.md),
|
||||
with `fsGroup` its gid so the pod reads its credentials (mode `0440`),
|
||||
read-only root filesystem with an `emptyDir` on `/tmp`, no privilege
|
||||
|
|
|
|||
|
|
@ -1,10 +1,12 @@
|
|||
# The cluster node
|
||||
|
||||
`services.hyperhive.deploy.k8s.enable` (default `false`) makes the host run a
|
||||
single-node k3s server for the swarm services that run in the cluster. It's
|
||||
the Kubernetes counterpart of `services.hyperhive.deploy.singleHostSwarm`: set
|
||||
it on the host that runs the swarm's services, and the cluster comes up with the
|
||||
service images loaded and no service's objects applied.
|
||||
k3s server for the swarm services that run in the cluster. It's the Kubernetes
|
||||
counterpart of `services.hyperhive.deploy.singleHostSwarm`: set it on the host
|
||||
that runs the swarm's services, and the cluster comes up with the service
|
||||
images loaded and no service's objects applied. Other machines can
|
||||
[join it](#joining-nodes) and run the services' pods; hyperhive runs no
|
||||
cluster of its own beyond that one main node, and it replicates no service.
|
||||
|
||||
## What the host gets
|
||||
|
||||
|
|
@ -14,8 +16,9 @@ service images loaded and no service's objects applied.
|
|||
pods have cluster DNS and PersistentVolumeClaims.
|
||||
- **Images:** the node holds k3s's own images and the image of each service
|
||||
that [renders manifests](manifests.md) on this host, in containerd before k3s
|
||||
starts. No registry exists, and the pods name their images with
|
||||
`imagePullPolicy: Never`.
|
||||
starts. No registry service exists. A pod names its image with
|
||||
`imagePullPolicy: IfNotPresent`, and a node that joined and lacks the image
|
||||
gets it from a peer ([Service images](images.md#where-a-node-gets-an-image)).
|
||||
- **Manifests:** `services.hyperhive.k8s.enable` is on, so the host builds
|
||||
`system.build.k8sManifests` and `system.build.k8sImages`. Setting it to
|
||||
`false` explicitly fails the evaluation.
|
||||
|
|
@ -27,7 +30,9 @@ service images loaded and no service's objects applied.
|
|||
same addresses. k3s's own default pod range, `10.42.0.0/16`, contains the
|
||||
bridge's default subnet.
|
||||
- **Firewall:** the pod network's interfaces, `cni0` and `flannel.1`, are
|
||||
trusted, so the node reaches its pods.
|
||||
trusted, so the node reaches its pods. The node-to-node ports are open to
|
||||
the addresses in `deploy.k8s.nodeAddresses` only, which is empty by default
|
||||
([Joining nodes](#joining-nodes)).
|
||||
- **NetworkPolicy:** k3s's own controller (kube-router, iptables) enforces
|
||||
NetworkPolicy objects; the node doesn't turn it off. A pod no policy selects
|
||||
reaches whatever it can route to. [The manifests](manifests.md#pods) say which
|
||||
|
|
@ -85,6 +90,86 @@ Moving a service's data to another node is manual: copy the directory, put the
|
|||
label on the new node, take it off the old one. Moving it with a command
|
||||
belongs to a later version.
|
||||
|
||||
## Joining nodes
|
||||
|
||||
The main node is the k3s server. A machine that joins is a k3s agent: it runs
|
||||
pods, and none of the server's manifests, units or labels. It doesn't need the
|
||||
swarm's services on it. The pods the main node renders run on it unless they
|
||||
keep data on a disk ([Node labels](#node-labels)), and a pod that has moved
|
||||
there pulls its image from a peer.
|
||||
|
||||
On the main node, set the addresses:
|
||||
|
||||
- `deploy.k8s.address`: the address the other nodes reach this one on. Set,
|
||||
it's the node's IP (`--node-ip`) and the API certificate lists it
|
||||
(`--tls-san`). Unset, k3s picks the default route's address, as it did before
|
||||
the option existed.
|
||||
- `deploy.k8s.nodeAddresses`: the addresses of the nodes that may join. The
|
||||
firewall admits these ports from them and from no other source: TCP 6443
|
||||
(the API, and the image mirror), TCP 10250 (the kubelet), UDP 8472 (flannel's
|
||||
VXLAN tunnel) and TCP 5001 (the mirror's peers). It writes iptables rules
|
||||
and refuses a host with `networking.nftables.enable`. With the list empty,
|
||||
no port is open.
|
||||
|
||||
On a NixOS host with a hive, set `deploy.k8s.join.server` to the main node's
|
||||
address (and `deploy.k8s.address` to this host's own, listed in the main node's
|
||||
`nodeAddresses`). The host runs `k3s agent` against
|
||||
`https://<server>:6443` with the token the store holds, and the same image
|
||||
mirror. It needs the store identity of its hive
|
||||
(`deploy.hive-controller.tls.baoHiveIdentityCertFile` and its key), as the
|
||||
hive's other units do, and refuses to evaluate without it. The module refuses a
|
||||
host that sets both `join` and `deploy.k8s.enable`.
|
||||
|
||||
### The join token
|
||||
|
||||
k3s keeps the token agents join with in
|
||||
`/var/lib/rancher/k3s/server/agent-token`. The main node's unit
|
||||
`k3s-join-token-publish` writes it to `secret/swarm/services/k8s/agent-token`
|
||||
in the secret store, under the identity of the hive that runs the main node, at
|
||||
each start of k3s, and writes it only when the stored value differs. A joining host's unit
|
||||
`k3s-join-token` reads that leaf under its own hive's identity and writes
|
||||
`/run/k3s-join/token` (tmpfs, root, `0400`) before k3s starts, so no step is
|
||||
manual. Every hive's identity reads the leaf and only the main node's hive
|
||||
writes it. The token is a join credential, not a cluster admin one, but it lets
|
||||
a machine that holds it become a node, so the nodes' firewall rules are the
|
||||
second check.
|
||||
|
||||
If the store is down or still locked when the host starts, the unit retries every 30
|
||||
seconds for a day, and k3s restarts every 5 seconds until the file exists.
|
||||
|
||||
### Joining a machine that isn't a hyperhive host
|
||||
|
||||
Nothing in the module reaches a machine it doesn't configure, so an admin does
|
||||
this by hand:
|
||||
|
||||
1. List the machine's address in the main node's `deploy.k8s.nodeAddresses`
|
||||
and activate.
|
||||
2. Read the token from the store, with an identity that may read
|
||||
`secret/swarm/services/k8s/agent-token` (the operator's, or the root
|
||||
token), and put it on the machine in a file only root reads:
|
||||
|
||||
```bash
|
||||
bao kv get -field=value secret/swarm/services/k8s/agent-token
|
||||
```
|
||||
|
||||
3. Write `/etc/rancher/k3s/registries.yaml` on the machine. It's the file the
|
||||
main node has, so the machine gets images from its peers:
|
||||
|
||||
```yaml
|
||||
mirrors:
|
||||
registry.hyperhive.invalid:
|
||||
```
|
||||
|
||||
4. Start k3s as an agent:
|
||||
|
||||
```bash
|
||||
k3s agent --server https://<main node>:6443 --token-file <token file> --node-ip <the machine's address>
|
||||
```
|
||||
|
||||
The machine's firewall has to admit the same four ports from the main node and
|
||||
the other nodes. The machine has no network route to the images' host, so a
|
||||
pod's image comes from a peer or fails ([Service images](images.md#where-a-node-gets-an-image)).
|
||||
|
||||
## Reaching host-run services
|
||||
|
||||
A pod reaches a service that runs on the host by the service's swarm name. The
|
||||
|
|
@ -213,4 +298,8 @@ ConfigMap. The VM test `k8s-node` boots a node through the module and runs a
|
|||
pod against it. The VM test `k8s-bao-login` runs the node and the secret store
|
||||
together: a pod under a service's ServiceAccount logs in and reads a value, a
|
||||
pod under another account gets no token, and a client on the hive bridge can't
|
||||
connect to the pods' port.
|
||||
connect to the pods' port. The VM test `k8s-join` boots a second machine that
|
||||
joins the main node through `deploy.k8s.join` with the token from the main
|
||||
node's store, runs a pod there from an image only the main node imported, and
|
||||
checks that the queue stays on the main node and that an image no node holds
|
||||
fails to pull instead of reaching a public registry.
|
||||
|
|
|
|||
|
|
@ -41,6 +41,7 @@ the rest of the cell says how.
|
|||
| `swarm/agents/<agent>/proxy-credential` | `swarm-controller`: 32 random bytes, at start and every 5 minutes for every agent that holds a store identity | the hive (`hive-c0re`) and the agent, which fetches it | ❌ never replaced: written only while the path holds nothing | ✅ `hive-c0re` re-reads it every 30 seconds |
|
||||
| `ssh-agents/sign/swarm-agent` (a signing call, nothing is stored) | the store's SSH CA mount (`ssh-agents`), when the agent's `hive-agent-ssh-cert` unit asks it to sign, which the operator's per-agent `ssh` switch allows the public key the unit generated in its own `/run`; the CA key is generated inside the store by `swarm-bao-agent-ssh-policy` | the agent, which keeps the key and the signed certificate in `/run` only; a target machine trusts the CA's public key by value | ✅ the certificate lasts 60 minutes; the CA is never replaced, and a target that holds a different CA key refuses every certificate | ✅ the agent signs again every 20 minutes |
|
||||
| `swarm/hives/<hive>/squid-selfcheck` | `swarm-controller`, in the same pass as the agents' credentials | the hive: `hive-c0re` and `squid-selfcheck-credential` (root) | ❌ never replaced: written only while the path holds nothing | ✅ `hive-c0re` every 30 seconds, the root unit every 10 minutes |
|
||||
| `swarm/services/k8s/agent-token` | `k3s-join-token-publish`, on the cluster's main node, as that node's hive: k3s's `agent-token`, written again whenever the file differs | a node that joins: `k3s-join-token`, as that node's hive, before k3s starts | ✅ at each start of the main node's k3s | ✅ at each start of the joining node's k3s |
|
||||
| `swarm/hives/<hive>/oidc/client` | authelia, first boot, straight into the store | the hive | ❌ minted once, straight into the store; minted again only when the store holds none | ✅ re-read when authelia refuses it |
|
||||
| `swarm/services/<clientId>/oidc/client` | authelia | that service | must be stated | must be stated |
|
||||
| `swarm/services/ci-runner/registration-token` | `swarm-controller`, from the forge, at start and every 5 minutes | `swarm-bao-ci-runner` on the runner's host | ❌ the forge keeps one token until an admin resets it; the controller then writes the new one within 5 minutes | ✅ every 10 minutes; restarts the runner on a change |
|
||||
|
|
@ -160,6 +161,7 @@ pieces fit, and the reasoning behind them, is in [`credentials.md`](../../2-hand
|
|||
| the secret store's own contents | openbao, on first `bao operator init` — **an operator action, not a unit** | inside the `swarm-bao` container, at its own `/var/lib/openbao`, kept across rebuilds by `ephemeral = false`. ⚠️ **Not a host path**: `nixos-container destroy swarm-bao` takes the raft data with it, so back up the container's tree, not `/var/lib/`. Only the store's TLS material (`/var/lib/swarm-bao-tls`) and its PKCS11 token (`/var/lib/swarm-bao-token`) are host-level | n/a — there is one store; a hive elsewhere is a _client_ of it and holds none of this |
|
||||
| the secret store's unseal material | the HSM/TPM under `deploy.bao.seal = "pkcs11"`; openbao itself under `"shamir"` | in the token; or held by whoever ran `bao operator init`, which is what `"shamir"` means and why it's stated rather than inferred | n/a — only the host running the store seals anything |
|
||||
| a cluster pod's store login token (a ServiceAccount token) | the cluster's API server, which signs it for the pod's account and the audience `bao`. The kubelet projects it into the pod and rewrites it before it expires | `/var/run/secrets/hyperhive/bao/token` in the pod. The store accepts it at its `jwt-k8s` mount, for the role of that account only, against the public halves of the node's signing keys, which `swarm-bao-k8s-jwt-policy` derives from the key files. A node whose signing keys changed needs that unit restarted, and tokens signed with the old key fail to log in meanwhile | Nothing to place: the pods and the store run on the cluster's one host |
|
||||
| the k3s join token | `k3s-join-token-publish` on the main node writes `swarm/services/k8s/agent-token` from the file k3s keeps | `/run/k3s-join/token` (tmpfs, root, `0400`) on a node with `deploy.k8s.join`, which `k3s-join-token` fills from the store under that host's own hive identity and k3s reads as its token | A different token than the server's: the node fails to register and k3s retries. The server's file wins: the main node's unit rewrites the leaf at its next k3s start, and the joining node's next k3s start reads it. A node that isn't a NixOS host gets the token from an admin, who reads the leaf (`docs/4-implementation/k8s/node.md`) |
|
||||
|
||||
### Hive-level — one of each per hive
|
||||
|
||||
|
|
|
|||
|
|
@ -398,7 +398,7 @@ in
|
|||
test "$(jq -c '.config.Entrypoint' "$config")" = '["/bin/hello"]'
|
||||
test "$(jq -r '.config.User' "$config")" = '${toString serviceUser.uid}:${toString serviceUser.gid}'
|
||||
jq -e '.config.Env | index("SSL_CERT_FILE=/etc/ssl/certs/ca-bundle.crt")' "$config" >/dev/null
|
||||
test "${image.imageName}" = hyperhive/smoke
|
||||
test "${image.imageName}" = registry.hyperhive.invalid/smoke
|
||||
|
||||
for layer in $(jq -r '.[0].Layers[]' manifest.json); do
|
||||
tar -tf "$layer"
|
||||
|
|
|
|||
|
|
@ -24,6 +24,7 @@ in
|
|||
{
|
||||
imports = [
|
||||
./host-services.nix
|
||||
./join.nix
|
||||
./node.nix
|
||||
./pod-logs.nix
|
||||
./runtime.nix
|
||||
|
|
|
|||
142
nix/host-modules/k8s/join.nix
Normal file
142
nix/host-modules/k8s/join.nix
Normal file
|
|
@ -0,0 +1,142 @@
|
|||
# The join token, through the swarm secret store: the main node's k3s server
|
||||
# writes it, and a host that sets `deploy.k8s.join` reads it before its k3s
|
||||
# agent starts. Both log in as the hive, the way `squid-selfcheck-credential`
|
||||
# does (../hive-squid-credential.nix). The leaf and the file are
|
||||
# ../lib/k8s-join-token.nix; ../swarm-bao.nix grants the read and, to the
|
||||
# store host's own hive, the write. docs/4-implementation/k8s/node.md has the
|
||||
# design.
|
||||
{
|
||||
pkgs,
|
||||
lib,
|
||||
config,
|
||||
...
|
||||
}:
|
||||
let
|
||||
hyperhiveCfg = config.services.hyperhive;
|
||||
cfg = hyperhiveCfg.deploy.k8s;
|
||||
hiveController = hyperhiveCfg.deploy.hive-controller;
|
||||
tls = hiveController.tls;
|
||||
baoCfg = hyperhiveCfg.swarm.bao;
|
||||
baoDeploy = hyperhiveCfg.deploy.bao;
|
||||
|
||||
token = import ../lib/k8s-join-token.nix;
|
||||
|
||||
haveIdentity = tls.baoHiveIdentityCertFile != null && tls.baoHiveIdentityKeyFile != null;
|
||||
|
||||
# The file k3s's server keeps the token agents join with in.
|
||||
serverTokenFile = "/var/lib/rancher/k3s/server/agent-token";
|
||||
|
||||
# Where the store runs on this host, the first login waits for its container.
|
||||
# No `wants`: a pull would start the container mid-switch on the old closure.
|
||||
storeContainer = lib.optional baoDeploy.enable "container@${baoCfg.machine}.service";
|
||||
|
||||
storeRetry = import ../lib/store-retry.nix { };
|
||||
|
||||
common = {
|
||||
path = [
|
||||
baoDeploy.package
|
||||
pkgs.coreutils
|
||||
pkgs.gnugrep
|
||||
];
|
||||
environment = {
|
||||
BAO_ADDR = "https://${baoCfg.domain}:${toString baoCfg.port}";
|
||||
BAO_CLIENT_CERT = tls.baoHiveIdentityCertFile;
|
||||
BAO_CLIENT_KEY = tls.baoHiveIdentityKeyFile;
|
||||
}
|
||||
// lib.optionalAttrs (baoDeploy.serverCaFile != null) {
|
||||
BAO_CACERT = baoDeploy.serverCaFile;
|
||||
};
|
||||
# ./lib/store-retry.nix: the login fails for as long as the store is
|
||||
# sealed or down.
|
||||
inherit (storeRetry) startLimitBurst startLimitIntervalSec;
|
||||
wants = [ "network-online.target" ];
|
||||
after = [ "network-online.target" ] ++ storeContainer;
|
||||
};
|
||||
in
|
||||
{
|
||||
config = lib.mkMerge [
|
||||
# The main node: the token k3s generated, in the store.
|
||||
(lib.mkIf (cfg.enable && haveIdentity) {
|
||||
systemd.services.k3s-join-token-publish = common // {
|
||||
description = "Write the k3s join token to the swarm secret store";
|
||||
wantedBy = [ "k3s.service" ];
|
||||
after = common.after ++ [ "k3s.service" ];
|
||||
wants = common.wants ++ [ "k3s.service" ];
|
||||
serviceConfig = storeRetry.serviceConfig // {
|
||||
Type = "oneshot";
|
||||
UMask = "0077";
|
||||
SyslogIdentifier = "k3s-join-token-publish";
|
||||
TimeoutStartSec = "5min";
|
||||
};
|
||||
script = ''
|
||||
set -euo pipefail
|
||||
${import ../lib/store-seeded-secret.nix { }}
|
||||
|
||||
# k3s writes the file as it starts.
|
||||
for _ in $(seq 120); do
|
||||
[ -s ${serverTokenFile} ] && break
|
||||
sleep 2
|
||||
done
|
||||
if [ ! -s ${serverTokenFile} ]; then
|
||||
echo "k3s has not written ${serverTokenFile}." >&2
|
||||
exit 1
|
||||
fi
|
||||
value="$(< ${serverTokenFile})"
|
||||
|
||||
store_init
|
||||
store_login
|
||||
if [ "$STORE_UP" != 1 ]; then
|
||||
echo "could not log in to the swarm secret store; the join token is not published." >&2
|
||||
exit 1
|
||||
fi
|
||||
if current="$(store_bao kv get -field=value ${lib.escapeShellArg "secret/${token.leaf}"} 2>"$STORE_ERR")" \
|
||||
&& [ "$current" = "$value" ]; then
|
||||
exit 0
|
||||
fi
|
||||
printf '%s' "$value" |
|
||||
store_bao kv put ${lib.escapeShellArg "secret/${token.leaf}"} value=- >/dev/null
|
||||
echo "published the k3s join token at ${token.leaf}."
|
||||
'';
|
||||
};
|
||||
|
||||
})
|
||||
|
||||
# A node that joins: the token, in a file before k3s starts.
|
||||
(lib.mkIf (cfg.join != null && haveIdentity) {
|
||||
systemd.services.k3s-join-token = common // {
|
||||
description = "Read the k3s join token from the swarm secret store";
|
||||
wantedBy = [ "k3s.service" ];
|
||||
before = [ "k3s.service" ];
|
||||
serviceConfig = storeRetry.serviceConfig // {
|
||||
Type = "oneshot";
|
||||
UMask = "0077";
|
||||
SyslogIdentifier = "k3s-join-token";
|
||||
TimeoutStartSec = "5min";
|
||||
};
|
||||
script = ''
|
||||
set -euo pipefail
|
||||
${import ../lib/store-seeded-secret.nix { }}
|
||||
${import ../lib/atomic-write-secret.nix { }}
|
||||
${import ../lib/refresh-consumer.nix { }}
|
||||
|
||||
install -d -m 0700 ${builtins.dirOf token.file}
|
||||
store_init
|
||||
store_login
|
||||
if [ "$STORE_UP" != 1 ]; then
|
||||
echo "could not log in to the swarm secret store; ${token.file} stays as it is." >&2
|
||||
exit 1
|
||||
fi
|
||||
if ! value="$(store_read ${lib.escapeShellArg "secret/${token.leaf}"})" || [ -z "$value" ]; then
|
||||
cat "$STORE_ERR" >&2
|
||||
echo "the swarm secret store holds no k3s join token at ${token.leaf} yet; ${token.file} stays as it is." >&2
|
||||
exit 1
|
||||
fi
|
||||
# Written only when the value changed, so the file keeps its mtime.
|
||||
if secret_differs ${token.file} "$value"; then
|
||||
atomic_write_secret 0400 root:root ${token.file} "$value"
|
||||
fi
|
||||
'';
|
||||
};
|
||||
})
|
||||
];
|
||||
}
|
||||
|
|
@ -1,13 +1,16 @@
|
|||
# The single-node k3s cluster this host runs for the swarm services that run
|
||||
# in the cluster, the Kubernetes counterpart of `deploy.singleHostSwarm`'s
|
||||
# all-local swarm. docs/4-implementation/k8s/node.md has the design.
|
||||
# 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 node holds the images of the services ./render.nix renders and has no
|
||||
# registry. No service's objects are applied until its `runtime` is `k8s`
|
||||
# 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. No service's objects are applied until its `runtime` is `k8s`
|
||||
# (./runtime.nix): until then its host unit runs.
|
||||
{
|
||||
config,
|
||||
lib,
|
||||
pkgs,
|
||||
...
|
||||
}:
|
||||
let
|
||||
|
|
@ -71,6 +74,50 @@ let
|
|||
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}:
|
||||
'';
|
||||
|
||||
# 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 = 8472;
|
||||
}
|
||||
{
|
||||
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 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") {
|
||||
|
|
@ -83,7 +130,7 @@ in
|
|||
type = lib.types.bool;
|
||||
default = false;
|
||||
description = ''
|
||||
Run a single-node k3s server on this host, with the images of the
|
||||
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`). Set it on the host
|
||||
that runs the swarm's services, which is the one
|
||||
|
|
@ -216,6 +263,66 @@ in
|
|||
'';
|
||||
};
|
||||
|
||||
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`), so flannel's tunnel endpoint and the
|
||||
node's registered address 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.
|
||||
'';
|
||||
};
|
||||
|
||||
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 8472 for flannel's
|
||||
VXLAN tunnel, TCP 5001 for the mirror's peers) from these addresses
|
||||
and from no others. 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;
|
||||
|
|
@ -228,8 +335,17 @@ in
|
|||
};
|
||||
};
|
||||
|
||||
config = lib.mkIf cfg.enable {
|
||||
config = lib.mkMerge [
|
||||
(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 = ''
|
||||
|
|
@ -273,16 +389,19 @@ in
|
|||
"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}"
|
||||
];
|
||||
# k3s's own images come first: with no registry the node pulls nothing,
|
||||
# not even CoreDNS.
|
||||
]
|
||||
++ 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
|
||||
]
|
||||
|
|
@ -290,6 +409,8 @@ in
|
|||
};
|
||||
|
||||
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
|
||||
|
|
@ -298,5 +419,48 @@ in
|
|||
services.dnsmasq.settings.server = lib.mkIf config.services.hyperhive.gateway.dns.enable [
|
||||
"/${clusterDomain}/${clusterDns}"
|
||||
];
|
||||
})
|
||||
|
||||
# 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;
|
||||
# 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;
|
||||
})
|
||||
];
|
||||
}
|
||||
|
|
|
|||
|
|
@ -841,8 +841,9 @@ let
|
|||
container = {
|
||||
inherit name volumeMounts;
|
||||
image = "${image.imageName}:${image.imageTag}";
|
||||
# The node imports the image tarball; there is no registry to pull from.
|
||||
imagePullPolicy = "Never";
|
||||
# A node without the image pulls it from a peer that holds it
|
||||
# (the mirror in ./node.nix); the name's host resolves nowhere else.
|
||||
imagePullPolicy = "IfNotPresent";
|
||||
env = lib.mapAttrsToList (n: v: {
|
||||
name = n;
|
||||
value = v;
|
||||
|
|
@ -907,7 +908,7 @@ let
|
|||
leafContainer = {
|
||||
name = "tls-issue";
|
||||
image = "${leafImage.imageName}:${leafImage.imageTag}";
|
||||
imagePullPolicy = "Never";
|
||||
imagePullPolicy = "IfNotPresent";
|
||||
env =
|
||||
lib.mapAttrsToList
|
||||
(n: v: {
|
||||
|
|
@ -1143,8 +1144,8 @@ in
|
|||
}
|
||||
// lib.concatMapAttrs (_: w: w.objects) enabled;
|
||||
|
||||
# The image each enabled service's pod runs: what a node has to hold,
|
||||
# since there is no registry to pull from.
|
||||
# The image each enabled service's pod runs: what the main node imports,
|
||||
# for the others to pull from it.
|
||||
images = lib.unique (lib.concatMap (w: [ w.image ] ++ w.extraImages) (lib.attrValues enabled));
|
||||
|
||||
# What ./runtime.nix moves services with. `switches` holds the services that
|
||||
|
|
|
|||
11
nix/host-modules/lib/k8s-join-token.nix
Normal file
11
nix/host-modules/lib/k8s-join-token.nix
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
# What the k3s server and a node that joins it agree on about the join token:
|
||||
# the leaf of the swarm secret store the server's unit writes it to
|
||||
# (../k8s/join.nix) and the file the joining node's unit lands it in, which k3s
|
||||
# reads as its token. ../swarm-bao.nix grants the hives' identities a read of
|
||||
# the leaf.
|
||||
{
|
||||
# Under KV v2's `secret/` mount, as `bao kv` takes it.
|
||||
leaf = "swarm/services/k8s/agent-token";
|
||||
# On the node that joins. A tmpfs, so the token is fetched again at boot.
|
||||
file = "/run/k3s-join/token";
|
||||
}
|
||||
|
|
@ -45,6 +45,7 @@ let
|
|||
# about the pods' login.
|
||||
k8sNode = deployCfg.k8s;
|
||||
podAuth = import ./lib/bao-pod-auth.nix;
|
||||
k8sJoinToken = import ./lib/k8s-join-token.nix;
|
||||
|
||||
shared = import ./lib/swarm-bao-shared.nix { inherit config lib pkgs; };
|
||||
inherit (shared)
|
||||
|
|
@ -920,7 +921,10 @@ let
|
|||
}) hyperhiveCfg.swarm.hives;
|
||||
|
||||
# What a hive's gateway-leaf identity may do: issue from its own role, read
|
||||
# two of its own cache facts, and read its own squid self-check credential.
|
||||
# two of its own cache facts, read its own squid self-check credential, and
|
||||
# read the k3s join token a node that joins fetches
|
||||
# (./k8s/join.nix); the hive of this host, which runs the cluster's main
|
||||
# node, also writes it.
|
||||
# The root unit on the hive host (`hive-priv-cache-facts`,
|
||||
# ./hive-priv-cache.nix) reads the facts under this identity: the key
|
||||
# hive-priv's downloads must be signed by, and the token it pulls with. The
|
||||
|
|
@ -941,6 +945,16 @@ let
|
|||
"pull-token"
|
||||
]
|
||||
+ readStanza "${credentialMountPath}/data/swarm/hives/${obj.hiveName}/squid-selfcheck"
|
||||
+ (
|
||||
if k8sNode.enable && obj.hiveName == deployCfg.hive-controller.hiveName then
|
||||
''
|
||||
path "${credentialMountPath}/data/${k8sJoinToken.leaf}" {
|
||||
capabilities = ["create", "read", "update"]
|
||||
}
|
||||
''
|
||||
else
|
||||
readStanza "${credentialMountPath}/data/${k8sJoinToken.leaf}"
|
||||
)
|
||||
# The archive credentials swarm-controller writes for the agents this hive
|
||||
# places: the backup unit (./hive-archive-backup.nix) lists them and reads each.
|
||||
+ readStanza "${credentialMountPath}/data/swarm/hives/${obj.hiveName}/archive/*"
|
||||
|
|
|
|||
|
|
@ -925,7 +925,7 @@ let
|
|||
fromInit = name: bin: extraEnv: from: extraMounts: {
|
||||
inherit name securityContext;
|
||||
image = ref init;
|
||||
imagePullPolicy = "Never";
|
||||
imagePullPolicy = "IfNotPresent";
|
||||
command = [ "/bin/${bin}" ];
|
||||
env = lib.mapAttrsToList (n: v: {
|
||||
name = n;
|
||||
|
|
@ -990,7 +990,7 @@ let
|
|||
{
|
||||
name = "nats";
|
||||
image = ref server;
|
||||
imagePullPolicy = "Never";
|
||||
imagePullPolicy = "IfNotPresent";
|
||||
args = lib.tail (lib.splitString " " natsSystem.systemd.services.nats.serviceConfig.ExecStart);
|
||||
# The port the client Service targets.
|
||||
ports = [
|
||||
|
|
@ -1029,7 +1029,7 @@ let
|
|||
{
|
||||
name = "exporter";
|
||||
image = ref exporter;
|
||||
imagePullPolicy = "Never";
|
||||
imagePullPolicy = "IfNotPresent";
|
||||
args = [
|
||||
"-addr"
|
||||
"0.0.0.0"
|
||||
|
|
|
|||
|
|
@ -6,6 +6,12 @@
|
|||
packages ? { },
|
||||
}:
|
||||
let
|
||||
# The registry host every image name carries. `.invalid` is reserved by RFC 6761
|
||||
# and never resolves, so a node that holds no copy of an image, and finds none
|
||||
# at a peer, fails to pull it instead of asking a public registry for a name
|
||||
# it does not own. ../host-modules/k8s/node.nix mirrors this host.
|
||||
registryHost = "registry.hyperhive.invalid";
|
||||
|
||||
# The conventional nonroot id. An OCI image has no `config.ids` to take it
|
||||
# from, so it is defined once here: the image's `User`, the smoke check and
|
||||
# a pod's `securityContext.runAsUser`/`runAsGroup` must all read this.
|
||||
|
|
@ -31,7 +37,7 @@ let
|
|||
env ? { },
|
||||
}:
|
||||
pkgs.dockerTools.buildLayeredImage {
|
||||
name = "hyperhive/${name}";
|
||||
name = "${registryHost}/${name}";
|
||||
contents = [
|
||||
package
|
||||
pkgs.cacert
|
||||
|
|
@ -55,7 +61,7 @@ let
|
|||
};
|
||||
in
|
||||
{
|
||||
inherit mkServiceImage serviceUser;
|
||||
inherit mkServiceImage registryHost serviceUser;
|
||||
|
||||
images = lib.genAttrs [
|
||||
"swarm-controller"
|
||||
|
|
|
|||
|
|
@ -1603,9 +1603,9 @@ let
|
|||
# One role, policy and login role per hive in the directory, each
|
||||
# naming only its own hive: the policy text in the unit is exactly the
|
||||
# `update` on its own role and `read` on its own two cache facts and its own
|
||||
# squid self-check credential, and each
|
||||
# squid self-check credential, and on the k3s join token every hive shares, and each
|
||||
# hive's block names neither the other's role nor its subject.
|
||||
name = "each hive's gateway-leaf identity may issue from its own role, read its own two cache facts, squid self-check credential and archive grants, and list those grants, and nothing else";
|
||||
name = "each hive's gateway-leaf identity may issue from its own role, read its own two cache facts, squid self-check credential and archive grants, list those grants, read the k3s join token, and nothing else";
|
||||
ok =
|
||||
let
|
||||
s = baoGrantTwoHives.systemd.services.swarm-bao-hive-leaf-policy.script;
|
||||
|
|
@ -1647,6 +1647,10 @@ let
|
|||
path = "secret/data/swarm/hives/h1/squid-selfcheck";
|
||||
caps = [ "read" ];
|
||||
}
|
||||
{
|
||||
path = "secret/data/swarm/services/k8s/agent-token";
|
||||
caps = [ "read" ];
|
||||
}
|
||||
{
|
||||
path = "secret/data/swarm/hives/h1/archive/*";
|
||||
caps = [ "read" ];
|
||||
|
|
@ -1671,6 +1675,10 @@ let
|
|||
path = "secret/data/swarm/hives/h2/squid-selfcheck";
|
||||
caps = [ "read" ];
|
||||
}
|
||||
{
|
||||
path = "secret/data/swarm/services/k8s/agent-token";
|
||||
caps = [ "read" ];
|
||||
}
|
||||
{
|
||||
path = "secret/data/swarm/hives/h2/archive/*";
|
||||
caps = [ "read" ];
|
||||
|
|
|
|||
|
|
@ -51,9 +51,46 @@ let
|
|||
deploy.claude-login.runtime = "k8s";
|
||||
deploy.swarm-controller.runtime = "k8s";
|
||||
deploy.nats.runtime = "k8s";
|
||||
deploy.k8s.address = "192.168.1.10";
|
||||
deploy.k8s.nodeAddresses = [
|
||||
"192.168.1.11"
|
||||
"192.168.1.12"
|
||||
];
|
||||
}
|
||||
);
|
||||
|
||||
# Two hives on a store host with the node: the policy of each differs by the
|
||||
# join token. Shares nothing of `onCluster`'s controller, which lists the
|
||||
# hives.
|
||||
twoHives = hive {
|
||||
deploy.bao.enable = true;
|
||||
deploy.k8s.enable = true;
|
||||
swarm.hives.h2.domain = "h2.t.local";
|
||||
};
|
||||
|
||||
# A host that joins that cluster: an agent with the store identity its join
|
||||
# token is read under. The only fixture without `deploy.k8s.enable`, which
|
||||
# is what it claims about.
|
||||
joined = hive {
|
||||
deploy.k8s.join.server = "192.168.1.10";
|
||||
deploy.k8s.address = "192.168.1.11";
|
||||
deploy.hive-controller.tls = {
|
||||
baoHiveIdentityCertFile = "/var/lib/hive-leaf/leaf.pem";
|
||||
baoHiveIdentityKeyFile = "/var/lib/hive-leaf/leaf-key.pem";
|
||||
};
|
||||
};
|
||||
joinedUnit = joined.systemd.services.k3s-join-token;
|
||||
|
||||
# Every image the cluster's pods name, and where the pull policy is.
|
||||
registryPrefix = "registry.hyperhive.invalid/";
|
||||
clusterText =
|
||||
builtins.toJSON (render onCluster)
|
||||
+ builtins.toJSON onCluster.services.hyperhive.k8s.rendered.services;
|
||||
imageRefs = map (s: lib.head (lib.splitString "\"" s)) (
|
||||
lib.tail (lib.splitString "\"image\":\"" clusterText)
|
||||
);
|
||||
occurrences = needle: text: lib.length (lib.splitString needle text) - 1;
|
||||
|
||||
# A host that asks for the cluster with no node, and a controller in it with
|
||||
# no TCP listener.
|
||||
runtimeRefused = hive {
|
||||
|
|
@ -414,6 +451,7 @@ let
|
|||
"opentelemetry-collector"
|
||||
"swarm-bao-controller-policy"
|
||||
"swarm-bao-granter-role"
|
||||
"swarm-bao-hive-leaf-policy"
|
||||
"swarm-bao-services-issuer-policy"
|
||||
] (names allLocal.systemd.services)
|
||||
)
|
||||
|
|
@ -2295,6 +2333,129 @@ let
|
|||
&& lib.elem rule onCluster.systemd.tmpfiles.rules
|
||||
&& !(lib.elem rule withNode.systemd.tmpfiles.rules);
|
||||
}
|
||||
{
|
||||
# The registry host is spelled out here, so the module is not compared
|
||||
# with itself. `withNode` is the control for the flags that follow an
|
||||
# address: it sets none, and k3s keeps its own default.
|
||||
name = "the server serves the embedded registry and mirrors the images' host alone, and follows the node's address when it has one";
|
||||
ok =
|
||||
let
|
||||
registries = onCluster.environment.etc."rancher/k3s/registries.yaml".text;
|
||||
in
|
||||
registries == "mirrors:\n registry.hyperhive.invalid:\n"
|
||||
&& withNode.environment.etc."rancher/k3s/registries.yaml".text == registries
|
||||
&& !(lib.hasInfix "*" registries)
|
||||
&& lib.elem "--embedded-registry" onCluster.services.k3s.extraFlags
|
||||
&& lib.elem "--embedded-registry" withNode.services.k3s.extraFlags
|
||||
&& onCluster.services.k3s.nodeIP == "192.168.1.10"
|
||||
&& lib.elem "--tls-san=192.168.1.10" onCluster.services.k3s.extraFlags
|
||||
&& withNode.services.k3s.nodeIP == null
|
||||
&& !(lib.any (lib.hasPrefix "--tls-san") withNode.services.k3s.extraFlags);
|
||||
}
|
||||
{
|
||||
# `withNode` lists no node: the control that the ports are not open
|
||||
# for everyone, and the `-s` on every rule that they are for the nodes.
|
||||
name = "the nodes' ports are open to the listed node addresses and to no other source";
|
||||
ok =
|
||||
let
|
||||
rules = onCluster.networking.firewall.extraCommands;
|
||||
rule =
|
||||
address: proto: port:
|
||||
"iptables -A nixos-fw -s ${address} -p ${proto} --dport ${port} -j nixos-fw-accept\n";
|
||||
forNodes = address: [
|
||||
(rule address "tcp" "6443")
|
||||
(rule address "tcp" "10250")
|
||||
(rule address "udp" "8472")
|
||||
(rule address "tcp" "5001")
|
||||
];
|
||||
nodeLines = lib.filter (l: lib.hasInfix "--dport" l && lib.hasInfix "nixos-fw -s" l) (
|
||||
lib.splitString "\n" rules
|
||||
);
|
||||
in
|
||||
lib.all (r: lib.hasInfix r rules) (forNodes "192.168.1.11" ++ forNodes "192.168.1.12")
|
||||
&& lib.length nodeLines == 8
|
||||
&& !(lib.hasInfix "--dport 6443" withNode.networking.firewall.extraCommands)
|
||||
&& !(lib.elem 6443 onCluster.networking.firewall.allowedTCPPorts)
|
||||
&& !(lib.elem 8472 onCluster.networking.firewall.allowedUDPPorts);
|
||||
}
|
||||
{
|
||||
# The main node is the control for each absence.
|
||||
name = "a host that joins runs a k3s agent with the token the store gave it, none of the server's units or labels, and the same mirror";
|
||||
ok =
|
||||
joined.services.k3s.enable
|
||||
&& joined.services.k3s.role == "agent"
|
||||
&& joined.services.k3s.serverAddr == "https://192.168.1.10:6443"
|
||||
&& joined.services.k3s.tokenFile == "/run/k3s-join/token"
|
||||
&& joined.services.k3s.agentTokenFile == null
|
||||
&& joined.services.k3s.nodeIP == "192.168.1.11"
|
||||
&& joined.services.k3s.nodeLabel == [ ]
|
||||
&& joined.services.k3s.manifests == { }
|
||||
&& !(lib.elem "--embedded-registry" joined.services.k3s.extraFlags)
|
||||
&&
|
||||
joined.environment.etc."rancher/k3s/registries.yaml".text
|
||||
== onCluster.environment.etc."rancher/k3s/registries.yaml".text
|
||||
&& lib.hasInfix "iptables -A nixos-fw -s 192.168.1.10 -p tcp --dport 6443 -j nixos-fw-accept" joined.networking.firewall.extraCommands
|
||||
&& joinedUnit.before == [ "k3s.service" ]
|
||||
&& joinedUnit.wantedBy == [ "k3s.service" ]
|
||||
&& lib.hasInfix "secret/swarm/services/k8s/agent-token" joinedUnit.script
|
||||
&& lib.hasInfix "/run/k3s-join/token" joinedUnit.script
|
||||
&& !(joined.systemd.services ? k3s-join-token-publish)
|
||||
&& withNode.systemd.services ? k3s-join-token-publish
|
||||
&& !(withNode.systemd.services ? k3s-join-token)
|
||||
&& withNode.services.k3s.role == "server"
|
||||
&& withNode.services.k3s.nodeLabel != [ ]
|
||||
&& !(joined.systemd.services ? swarm-notify-router-k8s-prune)
|
||||
&& withNode.systemd.services ? swarm-notify-router-k8s-prune;
|
||||
}
|
||||
{
|
||||
name = "a host that is both the main node and a joined node is refused, and so is a join with no store identity";
|
||||
ok =
|
||||
let
|
||||
both = hive {
|
||||
deploy.k8s.enable = true;
|
||||
deploy.k8s.join.server = "192.168.1.10";
|
||||
};
|
||||
noIdentity = hive { deploy.k8s.join.server = "192.168.1.10"; };
|
||||
messages = c: map (a: a.message) (lib.filter (a: !a.assertion) c.assertions);
|
||||
mentions = needle: c: lib.any (lib.hasInfix needle) (messages c);
|
||||
in
|
||||
mentions "k8s.join as a node of another" both
|
||||
&& mentions "baoHiveIdentityCertFile" noIdentity
|
||||
&& !(mentions "k8s.join as a node of another" joined)
|
||||
&& !(mentions "baoHiveIdentityCertFile" joined);
|
||||
}
|
||||
{
|
||||
# The main hive writes and h2 only reads. A count, not a match: the
|
||||
# same path is in both policies, so a stanza in the wrong one still
|
||||
# leaves the other in the text.
|
||||
name = "every hive's identity may read the join token, and the main node's hive alone may write it";
|
||||
ok =
|
||||
let
|
||||
script = twoHives.systemd.services.swarm-bao-hive-leaf-policy.script;
|
||||
path = "path \"secret/data/swarm/services/k8s/agent-token\" {\n capabilities = ";
|
||||
in
|
||||
occurrences "${path}[\"create\", \"read\", \"update\"]" script == 1
|
||||
&& occurrences "${path}[\"read\"]" script == 1
|
||||
&&
|
||||
occurrences "agent-token\" {\n capabilities = [\"create\"" allLocal.systemd.services.swarm-bao-hive-leaf-policy.script
|
||||
== 0
|
||||
&&
|
||||
occurrences "agent-token\" {\n capabilities = [\"read\"]" allLocal.systemd.services.swarm-bao-hive-leaf-policy.script
|
||||
== 1;
|
||||
}
|
||||
{
|
||||
# Presence controls: the lists are not empty, and the queue's three images
|
||||
# and a leaf's are among them.
|
||||
name = "every image the pods name carries the registry host that resolves nowhere, and none is pulled from a registry or never";
|
||||
ok =
|
||||
lib.length imageRefs >= 8
|
||||
&& lib.all (r: lib.hasPrefix registryPrefix r) imageRefs
|
||||
&& lib.any (r: lib.hasSuffix "-server" (lib.head (lib.splitString ":" r))) imageRefs
|
||||
&& lib.any (r: lib.hasInfix "-tls:" r) imageRefs
|
||||
&& occurrences "\"imagePullPolicy\":\"IfNotPresent\"" clusterText >= 8
|
||||
&& !(lib.hasInfix "\"imagePullPolicy\":\"Never\"" clusterText)
|
||||
&& !(lib.hasInfix "docker.io" clusterText);
|
||||
}
|
||||
];
|
||||
in
|
||||
runGroup "k8s" cases
|
||||
|
|
|
|||
|
|
@ -142,6 +142,7 @@ let
|
|||
k8s-runtime-switch
|
||||
k8s-controller-switch
|
||||
k8s-nats-switch
|
||||
k8s-join
|
||||
;
|
||||
};
|
||||
in
|
||||
|
|
|
|||
|
|
@ -22,5 +22,6 @@
|
|||
k8s-runtime-switch = import ./vm-tests/k8s-runtime-switch.nix { inherit pkgs self; };
|
||||
k8s-controller-switch = import ./vm-tests/k8s-controller-switch.nix { inherit pkgs self; };
|
||||
k8s-nats-switch = import ./vm-tests/k8s-nats-switch.nix { inherit pkgs self; };
|
||||
k8s-join = import ./vm-tests/k8s-join.nix { inherit pkgs self; };
|
||||
semi-spread = import ./vm-tests/semi-spread.nix { inherit pkgs self; };
|
||||
}
|
||||
|
|
|
|||
371
nix/vm-tests/k8s-join.nix
Normal file
371
nix/vm-tests/k8s-join.nix
Normal file
|
|
@ -0,0 +1,371 @@
|
|||
# `vmTests.<system>.k8s-join`: a second machine joins the main node's k3s
|
||||
# through `services.hyperhive.deploy.k8s.join`, with the join token the main
|
||||
# node wrote to its secret store. The main node runs the store and the cluster
|
||||
# node (`deploy.k8s.enable`) and imports an image that the second machine does
|
||||
# not hold. The script asserts that:
|
||||
#
|
||||
# - the main node's `k3s-join-token-publish` writes k3s's agent token to the
|
||||
# store under the hive's identity, and the joining machine's
|
||||
# `k3s-join-token` reads the same token under its own hive's identity;
|
||||
# - the joining machine goes Ready, carries no `state-*`, `entry` or
|
||||
# `enablelb` label, and the main node carries them;
|
||||
# - the node-to-node ports are open on the main node from the joining
|
||||
# machine's address only;
|
||||
# - a pod with the `state-ci-metrics` selector, the one the poller's pod
|
||||
# carries, runs on the main node, and a pod forced onto the joining machine
|
||||
# pulls its image from the main node through the embedded registry mirror
|
||||
# and runs: the machine had none, and the image's host resolves nowhere;
|
||||
# - a pod whose image no node holds fails to pull, with the images' registry
|
||||
# host in the error and no request to docker.io.
|
||||
#
|
||||
# Both nodes' store identities are leaves the script signs with the store's
|
||||
# CA: the module mints the hive's own and leaves the other hives' for an
|
||||
# operator to copy, which is what the script plays.
|
||||
{ pkgs, self }:
|
||||
let
|
||||
inherit (pkgs) lib;
|
||||
images = import ../images {
|
||||
inherit pkgs lib;
|
||||
};
|
||||
labels = import ../host-modules/k8s/labels.nix;
|
||||
|
||||
mainIp = "192.168.1.10";
|
||||
joinIp = "192.168.1.11";
|
||||
bridgeIp = "10.42.0.1";
|
||||
baoName = "bao.t.local";
|
||||
baoPort = 8200;
|
||||
leafDir = "/var/lib/test-leaf";
|
||||
pkiDir = "/var/lib/swarm-bao-pki";
|
||||
|
||||
# A daemon-shaped image, built the way the swarm's are, that only the main
|
||||
# node imports.
|
||||
probeImage = images.mkServiceImage {
|
||||
name = "k8s-join-probe";
|
||||
package = pkgs.coreutils;
|
||||
bin = "sleep";
|
||||
};
|
||||
probeRef = "${probeImage.imageName}:${probeImage.imageTag}";
|
||||
missingRef = "${images.registryHost}/nobody-has-this:v1";
|
||||
|
||||
pod = name: image: selector: {
|
||||
apiVersion = "v1";
|
||||
kind = "Pod";
|
||||
metadata = { inherit name; };
|
||||
spec = {
|
||||
nodeSelector = selector;
|
||||
restartPolicy = "Never";
|
||||
containers = [
|
||||
{
|
||||
name = "probe";
|
||||
inherit image;
|
||||
imagePullPolicy = "IfNotPresent";
|
||||
args = [ "3600" ];
|
||||
}
|
||||
];
|
||||
};
|
||||
};
|
||||
|
||||
identity = hive: {
|
||||
baoHiveIdentityCertFile = "${leafDir}/${hive}.pem";
|
||||
baoHiveIdentityKeyFile = "${leafDir}/${hive}-key.pem";
|
||||
};
|
||||
|
||||
swarm = {
|
||||
swarm.domain = "t.local";
|
||||
swarm.bao.domain = baoName;
|
||||
swarm.bao.port = baoPort;
|
||||
swarm.hives.h1.domain = "h1.t.local";
|
||||
swarm.hives.h2.domain = "h2.t.local";
|
||||
};
|
||||
in
|
||||
pkgs.testers.runNixOSTest {
|
||||
name = "k8s-join";
|
||||
|
||||
# The store takes a few minutes to open its raft storage, and a second node
|
||||
# joins and pulls after it. Under the 1 h job bound with room for the build.
|
||||
globalTimeout = 2700;
|
||||
|
||||
nodes.main =
|
||||
{ config, lib, ... }:
|
||||
{
|
||||
imports = [ self.nixosModules.default ];
|
||||
|
||||
services.hyperhive = lib.recursiveUpdate swarm {
|
||||
deploy.k8s = {
|
||||
enable = true;
|
||||
address = mainIp;
|
||||
nodeAddresses = [ joinIp ];
|
||||
};
|
||||
network.enable = true;
|
||||
network.bridgeIp = bridgeIp;
|
||||
deploy.bao.enable = true;
|
||||
deploy.bao.seal = "shamir";
|
||||
deploy.bao.bootstrapTokenFile = "/var/lib/swarm-bao-bootstrap/grant.token";
|
||||
# The joining machine reaches the store on the main node's address.
|
||||
deploy.bao.extraListenAddresses = [ mainIp ];
|
||||
# The poller's data is on this node's disk, so the module labels the
|
||||
# node with its state label.
|
||||
deploy.ci-metrics.enable = true;
|
||||
deploy.ci-metrics.runtime = "k8s";
|
||||
deploy.hive-controller.hiveName = "h1";
|
||||
deploy.hive-controller.tls = identity "h1";
|
||||
};
|
||||
system.stateVersion = "25.11";
|
||||
|
||||
# The store's name resolves to its loopback listener for this host.
|
||||
services.nginx.enable = lib.mkForce false;
|
||||
networking.hosts."127.0.0.1" = [ baoName ];
|
||||
networking.firewall.allowedTCPPorts = [ baoPort ];
|
||||
|
||||
services.k3s.images = [ probeImage ];
|
||||
environment.systemPackages = [
|
||||
pkgs.kubectl
|
||||
pkgs.jq
|
||||
pkgs.openssl
|
||||
];
|
||||
environment.variables.KUBECONFIG = "/etc/rancher/k3s/k3s.yaml";
|
||||
environment.etc = {
|
||||
"k8s-join/probe-ref".text = probeRef;
|
||||
"k8s-join/pod-on-joiner.json".text = builtins.toJSON (
|
||||
pod "on-joiner" probeRef { "kubernetes.io/hostname" = "joiner"; }
|
||||
);
|
||||
"k8s-join/pod-stateful.json".text = builtins.toJSON (
|
||||
pod "stateful" probeRef (labels.stateSelector "ci-metrics")
|
||||
);
|
||||
"k8s-join/pod-missing.json".text = builtins.toJSON (
|
||||
pod "missing" missingRef { "kubernetes.io/hostname" = "joiner"; }
|
||||
);
|
||||
};
|
||||
|
||||
networking.interfaces.eth1.ipv4.addresses = lib.mkForce [
|
||||
{
|
||||
address = mainIp;
|
||||
prefixLength = 24;
|
||||
}
|
||||
];
|
||||
|
||||
# The store's raft data is on a tmpfs, for the reason `full-setup` gives.
|
||||
fileSystems."/var/lib/nixos-containers/${config.services.hyperhive.swarm.bao.machine}/var/lib/private" =
|
||||
{
|
||||
device = "tmpfs";
|
||||
fsType = "tmpfs";
|
||||
options = [
|
||||
"mode=0700"
|
||||
"size=1G"
|
||||
];
|
||||
};
|
||||
|
||||
virtualisation = {
|
||||
memorySize = 6144;
|
||||
cores = 4;
|
||||
diskSize = 8192;
|
||||
};
|
||||
};
|
||||
|
||||
nodes.joiner =
|
||||
{ lib, ... }:
|
||||
{
|
||||
imports = [ self.nixosModules.default ];
|
||||
|
||||
services.hyperhive = lib.recursiveUpdate swarm {
|
||||
deploy.k8s = {
|
||||
join.server = mainIp;
|
||||
address = joinIp;
|
||||
};
|
||||
deploy.hive-controller.hiveName = "h2";
|
||||
deploy.hive-controller.tls = identity "h2";
|
||||
deploy.bao.serverCaFile = "${leafDir}/ca.pem";
|
||||
};
|
||||
system.stateVersion = "25.11";
|
||||
|
||||
networking.hosts."${mainIp}" = [ baoName ];
|
||||
networking.interfaces.eth1.ipv4.addresses = lib.mkForce [
|
||||
{
|
||||
address = joinIp;
|
||||
prefixLength = 24;
|
||||
}
|
||||
];
|
||||
|
||||
environment.systemPackages = [ pkgs.jq ];
|
||||
|
||||
virtualisation = {
|
||||
memorySize = 3072;
|
||||
cores = 2;
|
||||
diskSize = 8192;
|
||||
};
|
||||
};
|
||||
|
||||
testScript = builtins.readFile ./lib/k3s.py + ''
|
||||
import hashlib
|
||||
|
||||
INIT = "/root/bao-init.json"
|
||||
LEAF_DIR = "${leafDir}"
|
||||
PKI = "${pkiDir}"
|
||||
TOKEN_LEAF = "swarm/services/k8s/agent-token"
|
||||
SERVER_TOKEN = "/var/lib/rancher/k3s/server/agent-token"
|
||||
JOIN_TOKEN = "/run/k3s-join/token"
|
||||
JOINER_IP = "${joinIp}"
|
||||
PROBE_REF = main.succeed("cat /etc/k8s-join/probe-ref").strip()
|
||||
MISSING_REF = "${missingRef}"
|
||||
HOST = "${images.registryHost}"
|
||||
STATE_LABEL = "${labels.stateLabel "ci-metrics"}"
|
||||
ENTRY_LABEL = "${labels.entryLabel}"
|
||||
LB_LABEL = "${labels.loadBalancerLabel}"
|
||||
|
||||
|
||||
def as_root(command: str) -> str:
|
||||
return main.succeed(f'BAO_TOKEN="$(jq -r .root_token {INIT})" {command}')
|
||||
|
||||
|
||||
def diagnose(units: list[str]) -> None:
|
||||
for unit in units:
|
||||
print(f"--- {unit}")
|
||||
print(main.execute(f"systemctl status {unit} --no-pager -l; journalctl -u {unit} --no-pager -n 40")[1])
|
||||
|
||||
|
||||
def settle(command: str, timeout: int, units: list[str]) -> None:
|
||||
try:
|
||||
main.wait_until_succeeds(command, timeout=timeout)
|
||||
except Exception:
|
||||
diagnose(units)
|
||||
raise
|
||||
|
||||
|
||||
def sign(cn: str, name: str) -> None:
|
||||
"""A client leaf for `cn` under the store's CA, at LEAF_DIR/<name>.pem."""
|
||||
main.succeed(
|
||||
f"cd {LEAF_DIR} && "
|
||||
f"openssl req -newkey rsa:2048 -nodes -keyout {name}-key.pem -out {name}.csr -subj /CN={cn} && "
|
||||
"printf 'basicConstraints=critical,CA:FALSE\\nkeyUsage=critical,digitalSignature,keyEncipherment\\n"
|
||||
"extendedKeyUsage=clientAuth\\n' > leaf.ext && "
|
||||
f"openssl x509 -req -in {name}.csr -CA {PKI}/ca.pem -CAkey {PKI}/ca-key.pem -CAcreateserial "
|
||||
f"-days 30 -sha256 -extfile leaf.ext -out {name}.pem && chmod 0600 {name}-key.pem"
|
||||
)
|
||||
|
||||
|
||||
def ship(name: str) -> None:
|
||||
"""Copies LEAF_DIR/<name> from the main node to the joining machine."""
|
||||
data = main.succeed(f"base64 -w0 {LEAF_DIR}/{name}").strip()
|
||||
joiner.succeed(f"install -d -m 0700 {LEAF_DIR} && echo {data} | base64 -d > {LEAF_DIR}/{name} && chmod 0600 {LEAF_DIR}/{name}")
|
||||
|
||||
|
||||
def digest(node: QemuMachine, path: str) -> str:
|
||||
return hashlib.sha256(node.succeed(f"cat {path}").strip().encode()).hexdigest()
|
||||
|
||||
|
||||
def node_labels(name: str) -> dict:
|
||||
return json.loads(kube(main, f"get node {name} -o json"))["metadata"]["labels"]
|
||||
|
||||
|
||||
def first_status(name: str) -> dict:
|
||||
return pod(main, name)["status"].get("containerStatuses", [{}])[0]
|
||||
|
||||
|
||||
with subtest("the main node is Ready and holds the probe image"):
|
||||
main.succeed(f"install -d -m 0755 {LEAF_DIR}")
|
||||
wait_node_ready(main, timeout=300)
|
||||
main.wait_until_succeeds(f"k3s ctr images ls -q | grep -qxF '{containerd_ref(PROBE_REF)}'", timeout=120)
|
||||
joiner.start()
|
||||
|
||||
with subtest("the store is initialised, unsealed and bootstrapped"):
|
||||
main.wait_until_succeeds('[ "$(bao status >/dev/null 2>&1; echo $?)" = 2 ]', timeout=900)
|
||||
main.succeed(f"umask 077 && bao operator init -key-shares=1 -key-threshold=1 -format=json > {INIT}")
|
||||
unseal_bao(main, INIT)
|
||||
main.succeed(
|
||||
"set -o pipefail; "
|
||||
f'export BAO_TOKEN="$(jq -r .root_token {INIT})"; '
|
||||
"bao policy write bao-bootstrap /etc/hyperhive/bao-bootstrap-policy.hcl; "
|
||||
"bao token create -policy=bao-bootstrap -ttl=24h -orphan -display-name=bao-bootstrap -field=token "
|
||||
"| install -D -m 0600 /dev/stdin /var/lib/swarm-bao-bootstrap/grant.token; "
|
||||
"unset BAO_TOKEN; "
|
||||
"systemctl restart swarm-bao-granter-role"
|
||||
)
|
||||
main.wait_until_succeeds(
|
||||
"journalctl -u swarm-bao-granter-role --no-pager | grep -F 'Uploaded policy: bao-granter'",
|
||||
timeout=300,
|
||||
)
|
||||
|
||||
with subtest("the granting units have written the hives' policies and cert-auth roles"):
|
||||
main.succeed("systemctl reset-failed 'swarm-bao-*-policy.service' swarm-bao-agent-pki.service || true")
|
||||
main.succeed("systemctl restart --no-block 'swarm-bao-*-policy.service' swarm-bao-agent-pki.service")
|
||||
settle('[ "$(systemctl is-active swarm-bao-agent-pki.service)" = active ]', 900, ["swarm-bao-agent-pki.service"])
|
||||
# Under the shamir seal the PKI unit leaves a restart of the store to the
|
||||
# operator when its listener's client CA changed.
|
||||
if main.execute("journalctl -u swarm-bao-agent-pki --no-pager | grep -F 'restart openbao.service'")[0] == 0:
|
||||
main.succeed("systemctl --machine=swarm-bao restart openbao.service")
|
||||
main.wait_until_succeeds('[ "$(bao status >/dev/null 2>&1; echo $?)" = 2 ]', timeout=900)
|
||||
unseal_bao(main, INIT)
|
||||
for hive in ["h1", "h2"]:
|
||||
settle(
|
||||
f"systemctl restart swarm-bao-hive-leaf-policy.service; "
|
||||
f'BAO_TOKEN="$(jq -r .root_token {INIT})" bao read auth/cert/certs/swarm-hive-leaf-{hive}',
|
||||
600,
|
||||
["swarm-bao-hive-leaf-policy.service"],
|
||||
)
|
||||
|
||||
with subtest("the main node publishes the token k3s keeps, under its hive's identity"):
|
||||
sign("swarm-bao-hive-leaf-h1", "h1")
|
||||
sign("swarm-bao-hive-leaf-h2", "h2")
|
||||
main.succeed("systemctl reset-failed k3s-join-token-publish.service || true; systemctl restart k3s-join-token-publish.service")
|
||||
stored = as_root(f"bao kv get -mount=secret -field=value {TOKEN_LEAF}").strip()
|
||||
assert hashlib.sha256(stored.encode()).hexdigest() == digest(main, SERVER_TOKEN), "the store's token is not k3s's"
|
||||
|
||||
with subtest("the joining machine reads the same token under its own identity, and k3s joins"):
|
||||
main.succeed(f"cp {PKI}/ca.pem {LEAF_DIR}/ca.pem")
|
||||
for name in ["ca.pem", "h2.pem", "h2-key.pem"]:
|
||||
ship(name)
|
||||
joiner.succeed("systemctl reset-failed k3s-join-token.service || true; systemctl restart k3s-join-token.service")
|
||||
assert digest(joiner, JOIN_TOKEN) == digest(main, SERVER_TOKEN), "the joining machine holds another token"
|
||||
assert joiner.succeed(f"stat -c %a {JOIN_TOKEN}").strip() == "400"
|
||||
joiner.succeed("systemctl restart k3s.service")
|
||||
main.wait_until_succeeds(
|
||||
"kubectl get node joiner -o jsonpath='{.status.conditions[?(@.type==\"Ready\")].status}' | grep -qx True",
|
||||
timeout=600,
|
||||
)
|
||||
|
||||
with subtest("the main node carries the pin labels and the joined node none"):
|
||||
main_labels = node_labels("main")
|
||||
joined_labels = node_labels("joiner")
|
||||
for label in [STATE_LABEL, ENTRY_LABEL, LB_LABEL]:
|
||||
assert main_labels.get(label) == "true", (label, main_labels)
|
||||
pinned = [k for k in joined_labels if k.startswith("hyperhive.darkest.space/") or k == LB_LABEL]
|
||||
assert pinned == [], pinned
|
||||
|
||||
with subtest("the node-to-node ports are open to the joining machine's address only"):
|
||||
rules = main.succeed("iptables -S nixos-fw").splitlines()
|
||||
for port, proto in [("6443", "tcp"), ("10250", "tcp"), ("8472", "udp"), ("5001", "tcp")]:
|
||||
matching = [r for r in rules if f"--dport {port} " in r and f"-p {proto} " in r]
|
||||
assert matching, (port, rules)
|
||||
assert all(f"-s {JOINER_IP}/32" in r for r in matching), (port, matching)
|
||||
|
||||
with subtest("a pod with the poller's state selector runs on the main node"):
|
||||
main.succeed("kubectl apply -f /etc/k8s-join/pod-stateful.json")
|
||||
wait_pod(main, "stateful", phase="Running", ready=True, timeout=180)
|
||||
assert pod(main, "stateful")["spec"]["nodeName"] == "main"
|
||||
|
||||
with subtest("a pod forced onto the joining machine pulls its image from the main node and runs"):
|
||||
containerd_name = containerd_ref(PROBE_REF)
|
||||
assert HOST in containerd_name, containerd_name
|
||||
main.succeed(f"k3s ctr images ls -q | grep -qxF '{containerd_name}'")
|
||||
assert joiner.execute(f"k3s ctr images ls -q | grep -qxF '{containerd_name}'")[0] != 0, "the machine held the image already"
|
||||
main.succeed("kubectl apply -f /etc/k8s-join/pod-on-joiner.json")
|
||||
wait_pod(main, "on-joiner", phase="Running", ready=True, timeout=300)
|
||||
assert pod(main, "on-joiner")["spec"]["nodeName"] == "joiner"
|
||||
joiner.succeed(f"k3s ctr images ls -q | grep -qxF '{containerd_name}'")
|
||||
events = kube(main, "get events --field-selector involvedObject.name=on-joiner -o json")
|
||||
assert any(e["reason"] == "Pulled" for e in json.loads(events)["items"]), events
|
||||
|
||||
with subtest("an image no node holds fails to pull, naming the images' host and not docker.io"):
|
||||
main.succeed("kubectl apply -f /etc/k8s-join/pod-missing.json")
|
||||
main.wait_until_succeeds(
|
||||
"kubectl get pod missing -o json | jq -e "
|
||||
"'.status.containerStatuses[0].state.waiting.reason | IN(\"ErrImagePull\", \"ImagePullBackOff\")'",
|
||||
timeout=300,
|
||||
)
|
||||
message = first_status("missing")["state"]["waiting"].get("message", "")
|
||||
events = kube(main, "get events --field-selector involvedObject.name=missing -o json")
|
||||
text = message + events
|
||||
assert HOST in text, text
|
||||
assert "docker.io" not in text, text
|
||||
'';
|
||||
}
|
||||
|
|
@ -29,6 +29,7 @@
|
|||
{ pkgs, self }:
|
||||
let
|
||||
inherit (pkgs) lib;
|
||||
inherit (import ../images { inherit pkgs lib; }) registryHost;
|
||||
|
||||
# What the node's configuration and the script agree on. The collector's name
|
||||
# is a literal of `services.hyperhive.otel.collector.host`.
|
||||
|
|
@ -173,7 +174,7 @@ pkgs.testers.runNixOSTest {
|
|||
with subtest("the node is Ready and holds every image the module loads"):
|
||||
wait_node_ready(machine, timeout=300)
|
||||
refs = image_refs(machine)
|
||||
assert refs == ["hyperhive/swarm-ci-metrics:" + refs[0].split(":", 1)[1]], refs
|
||||
assert refs == ["${registryHost}/swarm-ci-metrics:" + refs[0].split(":", 1)[1]], refs
|
||||
wait_images(machine)
|
||||
|
||||
with subtest("the cluster encrypts its secrets and runs CoreDNS but neither traefik nor metrics-server"):
|
||||
|
|
|
|||
Loading…
Reference in a new issue