Watch
0
0
Fork
You've already forked hyperhive
0

k8s: the queue's pod mounts the host unit's store in place

This commit is contained in:
atlas 2026-11-23 02:58:52 +01:00 • committed by maia
commit 140ee7f38a
9 changed files with 267 additions and 155 deletions

View file

@ -54,6 +54,7 @@ in
deployment-apps-v1 = "sha256-Rtx8xL7CyaYkAEkeK4BXY1r7+mg4mZxRj3vqXGIamJs=";
cronjob-batch-v1 = "sha256-324f6Z2U41lEAnt7xDFwOfIvSc/0DE6x3AtU8C/PiUA=";
persistentvolumeclaim-v1 = "sha256-YTaHGsAzfxGkjaUjGigHQHxzhpZ+NDLzRBQbkC9qU4w=";
persistentvolume-v1 = "sha256-3f9zVyvwllzs+cFglJocQW9Pnoref0amSXZ1iaHieDw=";
configmap-v1 = "sha256-4Ord69Z3wIqgkrLaImTYasT8NO7RErn6wpRbPwDB6bE=";
namespace-v1 = "sha256-Mk+uZ3uY0abVQ0DbDDNNBT6P+6/Os/czJuQd4mENWEM=";
serviceaccount-v1 = "sha256-gZPWw1YUdcbT1cROH67bHfU5BTc9kEvBcBVpQybWWc8=";

View file

@ -85,6 +85,10 @@ let
in
{
imports = [
(lib.mkRemovedOptionModule [ "services" "hyperhive" "deploy" "nats" "k8s" "freshState" ] ''
The pod mounts the host unit's own store directory, so there is no empty
volume to start on and no state gate. Remove this definition.
'')
(lib.mkRemovedOptionModule [ "services" "hyperhive" "deploy" "stt" "k8s" "freshState" ] ''
The pod keeps its transcript cache in an emptyDir, so it starts on any
node with no state to migrate. Remove this definition.

View file

@ -20,7 +20,6 @@ let
deployCfg = config.services.hyperhive.deploy;
node = deployCfg.k8s;
controllerCfg = deployCfg.swarm-controller;
natsCfg = deployCfg.nats;
# The path of a unit's state directory in a pod, which ./render.nix mounts
# the claim at.
@ -31,11 +30,11 @@ let
controllerStateDir = "/var/lib/swarm-controller";
# `option` is the service's name under `services.hyperhive.deploy`. `state`
# is null for a service whose pod keeps nothing worth moving: no volume, an
# `emptyDir`, or a volume that starts empty with no gate.
# is null for a service with nothing to copy: no volume, an `emptyDir`, a
# volume that starts empty with no gate, or (the queue) the host unit's own
# directory, mounted into the pod.
#
# The claim is `<service>-state`, as ./render.nix and ../swarm-nats.nix name
# it.
# The claim is `<service>-state`, as ./render.nix names it.
stateTable = {
swarm-controller = {
option = "swarm-controller";
@ -52,11 +51,7 @@ let
};
swarm-nats = {
option = "nats";
state = {
mount = natsCfg.storeDir;
hostPath = "/var/lib/nixos-containers/swarm-nats${natsCfg.storeDir}";
excludes = [ ];
};
state = null;
};
swarm-notify-router = {
option = "notify-router";

View file

@ -169,8 +169,7 @@ let
# a pod holds more than the daemon, a function of the daemon's container
# (its environment, mounts and security context) giving the rest: further
# containers, init containers, volumes, host aliases, pod settings, objects and
# images, and `state`, the `volume` and mount `path` of a state volume the
# pod makes itself, which the state gate checks. An `otlp` of `"none"` is a daemon that pushes no telemetry of its
# and images. An `otlp` of `"none"` is a daemon that pushes no telemetry of its
# own.
services = {
swarm-controller = {
@ -213,7 +212,6 @@ let
etcFiles = [ ];
publicCredentials."bao-ca.pem" = baoServerCaKey;
otlp = "none";
fresh = freshOf "nats" natsCfg;
switch = {
inherit (natsCfg) runtime;
hostUnit = "container@swarm-nats.service";
@ -779,21 +777,15 @@ let
bin = leafIssueBin;
};
# The volume the state gate checks, and where it is mounted: that of a
# service with a `fresh` option, none for the rest. A pod that makes its
# own volume names it in `state`.
# service with a `fresh` option, none for the rest.
stateVolume =
if !(svc ? fresh) then
null
if svc ? fresh && stateDir != null then
{
volume = "state";
path = stateDir;
}
else
extra.state or (
if stateDir != null then
{
volume = "state";
path = stateDir;
}
else
null
);
null;
stateGate = lib.optionalAttrs (stateVolume != null) {
name = "state-gate";

View file

@ -237,6 +237,9 @@ let
# shell variable `renderConfig` reads its value into.
calloutSubstitutions = map (k: ''-e "s|${k.placeholder}|${"$"}${k.var}|g"'') calloutPublicKeys;
# Hands the store directory back to the server's user.
chownStore = nats: "${pkgs.coreutils}/bin/chown -R ${nats.user}:${nats.group} ${nats.dataDir}";
# Renders the server's config as it starts, so the settings it includes are
# always the running system's. Exits non-zero, and so stops the server
# starting, while any of the three public keys has not been fetched: the
@ -550,7 +553,14 @@ let
# plain override conflicts rather than wins.
systemd.services.nats.serviceConfig.ExecStart =
lib.mkForce "${pkgs.nats-server}/bin/nats-server -c ${runtimeWrapper}";
systemd.services.nats.serviceConfig.ExecStartPre = "+${renderConfig}";
# The store directory is also mounted into the pod at the same path (a
# local volume, `pod` below), whose process runs as another uid and
# leaves its files owned by it. `+` since the unit's own sandbox and user
# cannot chown them back.
systemd.services.nats.serviceConfig.ExecStartPre = [
"+${renderConfig}"
"+${chownStore container.config.services.nats}"
];
# The auth-callout responder: the half that lets the server
# above say *yes*. Without it the `auth_callout` block is a
@ -764,15 +774,19 @@ let
# configuration evaluated alone.
natsSystem = if onK8s then podSystem else config.containers.${machine}.config;
# The JetStream store's directory inside the container and in the pod, and the
# container's copy of it on the host.
dataDir = natsSystem.services.nats.settings.jetstream.store_dir;
hostStoreDir = "/var/lib/nixos-containers/${machine}${dataDir}";
# What the queue's pod holds besides the responder's container
# (../k8s/render.nix gives the responder's own): the server, its exporter and
# the init containers that make the server's files, from the units and
# settings the container runs on the host.
#
# The server starts only once its files exist. The state gate
# (../k8s/render.nix) checks the JetStream volume first, then the leaf is
# issued and the callout's keys and config written, each into a volume of its
# own that the server reads.
# The server starts only once its files exist: the leaf is issued and the
# callout's keys and config written, each into a volume of its own that the
# server reads.
pod =
{
env,
@ -796,8 +810,8 @@ let
field: role:
"bao write -field=${field} auth/${podAuth.mount}/login role=${role} jwt=@${podAuth.tokenFile}";
dataDir = natsSystem.services.nats.settings.jetstream.store_dir;
stateClaim = "${machine}-state";
stateClaim = "${machine}-store";
stateClass = "${machine}-store";
leaf = pkgs.writeShellScriptBin "swarm-nats-tls-issue" ''
export PATH=${lib.makeBinPath tools}
@ -939,12 +953,6 @@ let
}
];
# The JetStream volume, which the state gate checks before anything else.
state = {
volume = "nats-data";
path = dataDir;
};
# The server and the responder dial the queue by its name, which the pod
# answers with its own loopback: the leaf carries the name and no IP.
podSpec.shareProcessNamespace = true;
@ -1034,12 +1042,43 @@ let
}
];
# The JetStream store is the host unit's own directory, so a switch moves
# the process and not the bytes. A claim bound by name to a static local
# volume: the class names no provisioner, so nothing else binds either.
# `Retain` keeps the directory when the claim goes.
objects."${machine}/persistentvolume" = {
apiVersion = "v1";
kind = "PersistentVolume";
# Cluster-scoped: no namespace.
metadata = removeAttrs (metaFor stateClaim) [ "namespace" ];
spec = {
capacity.storage = "10Gi";
accessModes = [ "ReadWriteOnce" ];
persistentVolumeReclaimPolicy = "Retain";
storageClassName = stateClass;
local.path = hostStoreDir;
nodeAffinity.required.nodeSelectorTerms = [
{
matchExpressions = [
{
key = "kubernetes.io/hostname";
operator = "In";
values = [ (lib.toLower config.networking.hostName) ];
}
];
}
];
};
};
objects."${machine}/persistentvolumeclaim" = {
apiVersion = "v1";
kind = "PersistentVolumeClaim";
metadata = metaFor stateClaim;
spec = {
accessModes = [ "ReadWriteOnce" ];
storageClassName = stateClass;
volumeName = stateClaim;
resources.requests.storage = "10Gi";
};
};
@ -1253,25 +1292,13 @@ in
moves it: the container goes and the pod is applied, or the pod is
deleted and the container returns.
The pod's JetStream store is its own volume, which starts empty, and
the pod refuses to start until the volume holds the migration marker
or {option}`services.hyperhive.deploy.nats.k8s.freshState` is set.
Nothing here copies the container's store into it.
'';
};
k8s.freshState = import ./lib/fresh-state-option.nix { inherit lib; } "nats";
storeDir = lib.mkOption {
type = lib.types.str;
readOnly = true;
internal = true;
default = natsSystem.services.nats.settings.jetstream.store_dir;
description = ''
The JetStream store's directory inside the container, and the path the
pod mounts its volume at. The host's copy of it is this path under
`/var/lib/nixos-containers/swarm-nats`, which
../host-modules/k8s/migrate.nix names for `swarmctl migrate`.
The pod's JetStream store is the container's own directory on the host,
mounted into the pod as a static local volume, so a switch moves the
process and not the bytes: streams, consumers and key-value buckets are
the same files on both sides. The container's unit hands the directory
back to the server's user at each start, and the pod's group gets read
and write access from the pod's `fsGroup`. At most one server holds the
directory, since a switch stops the one before it starts the other.
'';
};
@ -1542,7 +1569,13 @@ in
# The bind source has to exist before the container starts, leaf or not:
# nixos-container refuses to start over a missing one, which would take
# the whole queue down rather than only its TLS.
systemd.tmpfiles.rules = [ "d ${tlsDir} 0755 root root -" ];
#
# The pod's local volume needs its directory to exist before the pod
# starts, which on a host that never ran the container nothing else makes.
systemd.tmpfiles.rules = [
"d ${tlsDir} 0755 root root -"
]
++ lib.optional onK8s "d ${hostStoreDir} 0700 root root -";
containers.swarm-nats = lib.mkIf (!onK8s) {
autoStart = true;

View file

@ -115,7 +115,6 @@ let
config:
lib.recursiveUpdate config {
services.hyperhive.deploy = {
nats.k8s.freshState = true;
swarm-controller.k8s.freshState = true;
};
};
@ -1595,7 +1594,7 @@ let
# Everything of the pod is read off the manifest the module renders. The
# `tmp` volume is the control that the lookup of a volume's medium finds
# a plain one.
name = "the queue's pod is one replaced copy of the responder, the server and the exporter, started after the state gate, the leaf and the callout config";
name = "the queue's pod is one replaced copy of the responder, the server and the exporter, started after the leaf and the callout config, on the host unit's own store directory";
ok =
let
o = objects."swarm-nats/deployment";
@ -1603,6 +1602,8 @@ let
named = n: lib.findFirst (c: c.name == n) { } spec.containers;
volume = n: lib.findFirst (v: v.name == n) null spec.volumes;
pvc = objects."swarm-nats/persistentvolumeclaim";
pv = objects."swarm-nats/persistentvolume";
hostStore = "/var/lib/nixos-containers/swarm-nats/var/lib/nats";
env = envOf "swarm-nats";
in
o.spec.replicas == 1
@ -1624,7 +1625,6 @@ let
)
&&
map (c: c.name) spec.initContainers == [
"state-gate"
"tls-issue"
"callout-config"
]
@ -1686,6 +1686,32 @@ let
&& !((volume "tmp").emptyDir ? medium)
&& (volume "nats-data").persistentVolumeClaim.claimName == pvc.metadata.name
&& pvc.spec.accessModes == [ "ReadWriteOnce" ]
# The claim binds by name the static local volume on the container's
# store directory, on this node, and only that: its class is its own.
# The controller's claim is the control that a claim does not.
&& pvc.spec.volumeName == pv.metadata.name
&& pvc.spec.storageClassName == pv.spec.storageClassName
&& pv.spec.storageClassName != ""
&& !(objects."swarm-controller/persistentvolumeclaim".spec ? volumeName)
&& pv.spec.local.path == hostStore
&& pv.spec.persistentVolumeReclaimPolicy == "Retain"
&& !(pv.metadata ? namespace)
&&
pv.spec.nodeAffinity.required.nodeSelectorTerms == [
{
matchExpressions = [
{
key = "kubernetes.io/hostname";
operator = "In";
values = [ (lib.toLower allLocal.networking.hostName) ];
}
];
}
]
# A pod on a host that never ran the container gets the directory made;
# a host with the container needs no rule.
&& lib.any (lib.hasPrefix "d ${hostStore} ") onCluster.systemd.tmpfiles.rules
&& !(lib.any (lib.hasPrefix "d ${hostStore} ") withNode.systemd.tmpfiles.rules)
&& !(lib.any (c: c ? resources) spec.containers)
&& !(lib.any (v: v ? secret) spec.volumes);
}
@ -1713,21 +1739,19 @@ let
volume = "state";
option = "deploy.swarm-controller.k8s.freshState";
};
swarm-nats = {
path = "/var/lib/nats";
volume = "nats-data";
option = "deploy.nats.k8s.freshState";
};
};
# The poller keeps a claim for its cursor and the speech-to-text pod
# keeps none; neither is gated.
# The poller keeps a claim for its cursor and the queue one on the host's
# directory; the speech-to-text pod keeps none. None is gated.
unclaimed = [
"swarm-notify-router"
"swarm-review-classifier"
"swarm-claude-login"
"swarm-stt"
];
ungated = unclaimed ++ [ "swarm-ci-metrics" ];
ungated = unclaimed ++ [
"swarm-ci-metrics"
"swarm-nats"
];
one =
name: g:
let
@ -1861,9 +1885,9 @@ let
services = (migrateOf withNode).services;
stateful = [
"swarm-controller"
"swarm-nats"
];
stateless = [
"swarm-nats"
"swarm-notify-router"
"swarm-review-classifier"
"swarm-claude-login"
@ -1908,8 +1932,8 @@ let
in
(migrateOf withNode).namespace == "hyperhive"
&& host.swarm-controller.state.hostPath == "/var/lib/swarm-controller"
&& host.swarm-nats.state.hostPath == "/var/lib/nixos-containers/swarm-nats/var/lib/nats"
&& host.swarm-nats.state.mount == "/var/lib/nats"
# The queue's store is mounted in place, so nothing is copied.
&& host.swarm-nats.state == null
&& host.swarm-ci-metrics.state == null
&& host.swarm-stt.state == null
&&
@ -1922,7 +1946,7 @@ let
&& lib.all (s: s.runtime == "host") (lib.attrValues host)
# The runtime follows the option: the cluster fixture has every one on k8s.
&& lib.all (s: s.runtime == "k8s") (lib.attrValues cluster)
&& cluster.swarm-nats.state == host.swarm-nats.state;
&& cluster.swarm-controller.state == host.swarm-controller.state;
}
{
# A pure function, so the case needs no host of its own. A path inside the

View file

@ -367,7 +367,7 @@ let
# The xkey exists only at runtime, so the server's config is rendered as
# it starts: always the wrapper, and never the store-rendered settings
# alone, which carry no xkey. `+` so the render may write `runtimeDir`.
name = "the queue's server starts only through the config rendered with its xkey";
name = "the queue's server starts only through the config rendered with its xkey, then takes its store directory back";
ok =
lib.all
(
@ -375,11 +375,17 @@ let
let
c = h.containers.swarm-nats.config;
nats = c.systemd.services.nats.serviceConfig;
pre = nats.ExecStartPre or "";
pre = lib.toList (nats.ExecStartPre or [ ]);
render = lib.head pre;
in
lib.hasSuffix "/bin/nats-server -c /var/lib/nats-callout/nats.conf" nats.ExecStart
&& lib.hasPrefix "+/nix/store/" pre
&& lib.hasSuffix "-swarm-nats-render-config" pre
&& lib.hasPrefix "+/nix/store/" render
&& lib.hasSuffix "-swarm-nats-render-config" render
# Then the store directory goes back to the server's user, which the
# pod, mounting it in place, leaves owned by its own.
&& lib.length pre == 2
&& lib.hasPrefix "+/nix/store/" (lib.elemAt pre 1)
&& lib.hasSuffix "/bin/chown -R nats:nats /var/lib/nats" (lib.elemAt pre 1)
&& !(c.services.nats.settings.authorization.auth_callout ? xkey)
)
[

View file

@ -36,7 +36,10 @@ pkgs.runCommand "hyperhive-script-test-nats-render-config"
{
# `removePrefix` keeps the string context, and with it the script's store
# path among this check's inputs. The `+` is systemd's, not the path's.
RENDER = lib.removePrefix "+" queue.containers.swarm-nats.config.systemd.services.nats.serviceConfig.ExecStartPre;
# The render is the first of the unit's `ExecStartPre` entries.
RENDER = lib.removePrefix "+" (
lib.head queue.containers.swarm-nats.config.systemd.services.nats.serviceConfig.ExecStartPre
);
nativeBuildInputs = [ pkgs.jq ];
}
''

View file

@ -2,24 +2,25 @@
# between their container and the host's cluster
# (`services.hyperhive.deploy.nats.runtime`), against the real secret store.
# The host boots with the queue in its container; the `k8s` specialisation has
# it in the cluster on a fresh JetStream store, and `k8s-open` adds
# it in the cluster on the container's own JetStream store, and `k8s-open` adds
# `deploy.nats.openFirewall`. The script switches to the cluster, opens the
# port, and back, and asserts that:
#
# - at most one server and one responder run at any moment of any switch (a
# sampler counts the processes every 200 ms), and the container and the pod
# never overlap;
# - the pod is Ready by its exec probe on the server's monitor, holds the store
# guard, the leaf and the callout config as init containers, and publishes
# the client port on every address and the exporter's on the bridge's;
# - the pod is Ready by its exec probe on the server's monitor, holds the leaf
# and the callout config as init containers, and publishes the client port
# on every address and the exporter's on the bridge's;
# - a client on the hive's bridge reaches the queue by name through the
# published port, and the responder in the pod admits the router's token;
# - the port is as closed to a host outside the node as the container's is, and
# open with `openFirewall`, where a second node dials it by name and verifies
# the name. The exporter's port answers the host's own processes only;
# - a stream written before the pod is deleted is read after;
# - the pod's state gate marks the empty store as fresh, and passes the volume
# with its marker after a pod delete;
# - the store is the container's own directory: a key the host server wrote is
# read by the pod, and a key the pod wrote is read by the host server after
# the switch back, which hands the files back to the server's user;
# - the switch back leaves no pod, Deployment or AddOn, and the container
# starts after the prune unit.
#
@ -177,13 +178,9 @@ pkgs.testers.runNixOSTest {
};
system.stateVersion = "25.11";
specialisation.k8s.configuration.services.hyperhive.deploy.nats = {
runtime = "k8s";
k8s.freshState = true;
};
specialisation.k8s.configuration.services.hyperhive.deploy.nats.runtime = "k8s";
specialisation.k8s-open.configuration.services.hyperhive.deploy.nats = {
runtime = "k8s";
k8s.freshState = true;
openFirewall = true;
};
@ -367,6 +364,8 @@ pkgs.testers.runNixOSTest {
"&& systemctl --machine=swarm-nats is-active swarm-nats-auth.service "
"&& [ \"$(pgrep -cx nats-server)\" = 1 ] && [ \"$(pgrep -cx swarm-nats-auth)\" = 1 ]"
)
BUCKET = "notify-router-state"
HOST_STORE = "/var/lib/nixos-containers/swarm-nats/var/lib/nats"
SUBJECT = "$SWARM.router.todo.atlas"
INBOX = "_INBOX.client.swarm-notify-router"
@ -422,7 +421,7 @@ pkgs.testers.runNixOSTest {
except Exception:
diagnose(["hyperhive-k8s-ca-trust.service"])
print(machine.execute(f"kubectl -n {NS} describe pod {name}")[1])
for container in ("state-gate", "tls-issue", "callout-config", SERVICE, "nats", "exporter"):
for container in ("tls-issue", "callout-config", SERVICE, "nats", "exporter"):
print(machine.execute(f"kubectl -n {NS} logs {name} -c {container} --tail=60")[1])
raise
return name
@ -574,6 +573,15 @@ pkgs.testers.runNixOSTest {
with subtest("the host's own processes read the exporter through the container"):
machine.succeed(f"curl -sf http://127.0.0.1:{METRICS}/metrics | grep -F gnatsd_varz_connections")
with subtest("on the host, the container's server takes a key into the router's state bucket, and the store's files belong to the server's user"):
nats(machine, f"kv add {BUCKET}")
nats(machine, f"kv put {BUCKET} host-key written-on-host")
assert "written-on-host" in nats(machine, f"kv get {BUCKET} host-key --raw")
HOST_UID = machine.succeed(f"stat -c %u {HOST_STORE}").strip()
# The control that the lookup finds files: the store is not empty.
assert int(machine.succeed(f"find {HOST_STORE} -type f | wc -l")) > 0
assert machine.succeed(f"find {HOST_STORE} ! -uid {HOST_UID} | wc -l").strip() == "0"
with subtest("the switch to the cluster stops the container before it applies the pod"):
out = switch("/run/booted-system/specialisation/k8s")
assert HOST_UNIT in out and "stopping the following units" in out, out
@ -586,9 +594,9 @@ pkgs.testers.runNixOSTest {
machine.fail("test -e /etc/nixos-containers/swarm-nats.conf")
assert counts() == (1, 1), counts()
with subtest("the pod holds the state gate, the leaf and the config as init containers, and publishes the client port on every address and the exporter's on the bridge"):
with subtest("the pod holds the leaf and the config as init containers, and publishes the client port on every address and the exporter's on the bridge"):
spec = pod(machine, pod_name)["spec"]
assert [c["name"] for c in spec["initContainers"]] == ["state-gate", "tls-issue", "callout-config"], spec["initContainers"]
assert [c["name"] for c in spec["initContainers"]] == ["tls-issue", "callout-config"], spec["initContainers"]
assert [c["name"] for c in spec["containers"]] == ["swarm-nats", "nats", "tls-renew", "exporter"], spec["containers"]
assert spec["shareProcessNamespace"] is True, spec
server = next(c for c in spec["containers"] if c["name"] == "nats")
@ -604,7 +612,7 @@ pkgs.testers.runNixOSTest {
# Ready is the exec probe's and the responder's: every container is.
statuses = {c["name"]: c["ready"] for c in pod(machine, pod_name)["status"]["containerStatuses"]}
assert statuses == {"swarm-nats": True, "nats": True, "tls-renew": True, "exporter": True}, statuses
claim = json.loads(kube(machine, f"get pvc {SERVICE}-state -o json"))
claim = json.loads(kube(machine, f"get pvc {SERVICE}-store -o json"))
assert claim["status"]["phase"] == "Bound", claim
STATE_VOLUME = claim["metadata"]["uid"]
# The leaf's key is in memory.
@ -614,8 +622,6 @@ pkgs.testers.runNixOSTest {
machine.fail(f"grep -F '{mount}/nats-config ' /proc/mounts")
issued = machine.succeed(f"kubectl -n {NS} logs {pod_name} -c tls-issue")
assert f"requesting the queue's TLS leaf for {NAME} from the store" in issued, issued
guard = machine.succeed(f"kubectl -n {NS} logs {pod_name} -c state-gate")
assert "the install is fresh: marked" in guard, guard
# The pod's server keeps the descriptors the container's did.
limits = machine.succeed("grep 'Max open files' /proc/$(pgrep -ox nats-server)/limits")
print(limits)
@ -632,6 +638,19 @@ pkgs.testers.runNixOSTest {
assert stream_messages() == 1
machine.wait_until_succeeds(f"[ \"$(grep -c '/api/oidc/introspection ${service}:{SECRET}' ${tokenLog})\" -ge 2 ]", timeout=60)
with subtest("the pod's volume is the container's own directory: it reads the host's key, writes one of its own, and leaves files the host's user does not own"):
pv = json.loads(kube(machine, f"get pv {SERVICE}-store -o json"))
assert pv["spec"]["local"]["path"] == HOST_STORE, pv["spec"]
assert pv["status"]["phase"] == "Bound" and pv["spec"]["claimRef"]["name"] == f"{SERVICE}-store", pv
assert pv["spec"]["persistentVolumeReclaimPolicy"] == "Retain", pv["spec"]
assert claim["spec"]["volumeName"] == pv["metadata"]["name"], claim["spec"]
assert "written-on-host" in nats(machine, f"kv get {BUCKET} host-key --raw")
nats(machine, f"kv put {BUCKET} pod-key written-by-pod")
assert "written-by-pod" in nats(machine, f"kv get {BUCKET} pod-key --raw")
# The stream the pod made is its own, so the host's user has to take it
# back when the container starts.
assert int(machine.succeed(f"find {HOST_STORE} ! -uid {HOST_UID} | wc -l")) > 0
with subtest("a client on the hive's bridge reaches the pod through the published port, and a host outside the node does not"):
assert machine.execute(f"ip netns exec agent nc -z -w 4 {BRIDGE} {PORT}")[0] == 0
assert machine.execute(f"ip netns exec agent nc -z -w 4 {BRIDGE} {METRICS}")[0] != 0
@ -662,11 +681,11 @@ pkgs.testers.runNixOSTest {
old_uid = pod(machine, pod_name)["metadata"]["uid"]
kube(machine, f"delete pod {pod_name} --wait=true --timeout=120s", 150)
pod_name = wait_pod_ready(old_uid)
assert json.loads(kube(machine, f"get pvc {SERVICE}-state -o json"))["metadata"]["uid"] == STATE_VOLUME
assert json.loads(kube(machine, f"get pvc {SERVICE}-store -o json"))["metadata"]["uid"] == STATE_VOLUME
machine.wait_until_succeeds(nats_cmd(SERVICES_ROOT, f"stream info {STREAM}"), timeout=120)
assert stream_messages() == 1
guard = machine.succeed(f"kubectl -n {NS} logs {pod_name} -c state-gate")
assert "state volume is migrated" in guard, guard
assert "written-on-host" in nats(machine, f"kv get {BUCKET} host-key --raw")
assert "written-by-pod" in nats(machine, f"kv get {BUCKET} pod-key --raw")
assert counts() == (1, 1), counts()
with subtest("with openFirewall a host outside the node dials the pod by name and verifies it, and is admitted"):
@ -702,9 +721,15 @@ pkgs.testers.runNixOSTest {
requires = machine.succeed(f"systemctl show -p Requires --value {HOST_UNIT}")
assert f"{PRUNE}.service" in requires, requires
# The volume is kept for the next switch.
assert json.loads(kube(machine, f"get pvc {SERVICE}-state -o json"))["metadata"]["uid"] == STATE_VOLUME
assert json.loads(kube(machine, f"get pvc {SERVICE}-store -o json"))["metadata"]["uid"] == STATE_VOLUME
settle(QUEUE_UP, 600, [HOST_UNIT])
assert counts() == (1, 1), counts()
# The container's server reads what the pod wrote: its unit took the
# files back before the server started.
machine.wait_until_succeeds(nats_cmd(SERVICES_ROOT, f"kv get {BUCKET} pod-key --raw") + " | grep -F written-by-pod", timeout=120)
assert "written-on-host" in nats(machine, f"kv get {BUCKET} host-key --raw")
assert stream_messages() == 1
assert machine.succeed(f"find {HOST_STORE} ! -uid {HOST_UID} | wc -l").strip() == "0"
# Closed to a host outside the node again, open to the node's own.
assert not reachable(outside, NODE, PORT), "the container's port is open to a host outside the node"
assert reachable(outside, NODE, CONTROL)