The tests waited on `bao status`, which answers once the node is unsealed and before raft has elected it, so the first policy write raced the election and failed with "local node not active but active cluster node not found". `unseal_bao` unseals and then waits for sys/leader to say the node is the leader; the four tests that bootstrap the store use it at both unseal sites. Closes #6807
843 lines
43 KiB
Nix
843 lines
43 KiB
Nix
# `vmTests.<system>.k8s-nats-switch`: the swarm queue and its auth callout move
|
|
# 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 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 leaf
|
|
# and the callout config as init containers, and has no `hostPort`: the client
|
|
# port is a LoadBalancer Service with no node port, bound by the load balancer;
|
|
# - with the egress intercept on, a client on the hive's bridge reaches the
|
|
# queue by name through the published port and not by the pod's address or
|
|
# the node's, 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 answers the host only, by its Service's name;
|
|
# - a stream written before the pod is deleted is read after;
|
|
# - 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, Service, NetworkPolicy or AddOn, and the
|
|
# container starts after the prune unit.
|
|
#
|
|
# One stub is the identity provider: it introspects the test's one token as the
|
|
# notification router, whose permissions create and fill a stream. The test
|
|
# makes the hive's CA and the stub's leaf; the queue's own leaf is the store's.
|
|
{ pkgs, self }:
|
|
let
|
|
inherit (pkgs) lib;
|
|
|
|
bridgeIp = "10.42.0.1";
|
|
nodeIp = "192.168.1.10";
|
|
outsideIp = "192.168.1.20";
|
|
agentIp = "10.42.0.200";
|
|
baoName = "bao.t.local";
|
|
baoPort = 8200;
|
|
natsName = "nats.t.local";
|
|
natsPort = 4222;
|
|
metricsPort = 7777;
|
|
authName = "auth.t.local";
|
|
controlPort = 9999;
|
|
namespace = "hyperhive";
|
|
service = "swarm-nats";
|
|
prune = "${service}-k8s-prune";
|
|
hostUnit = "container@${service}.service";
|
|
pkiDir = "/var/lib/test-ca";
|
|
tlsDir = "/var/lib/hive-tls";
|
|
oidcLeaf = "swarm/services/${service}/oidc/client";
|
|
routerToken = "test-router-token";
|
|
overlapLog = "/var/log/overlap.log";
|
|
tokenLog = "/var/log/stub-token.log";
|
|
|
|
# The identity provider, by name. The token endpoint answers every
|
|
# client-credentials request with a token. The introspection endpoint
|
|
# answers `active` for the test's one token, as the notification router,
|
|
# and records the client id and secret it was asked with.
|
|
tokenStub = pkgs.writeText "token-stub.py" ''
|
|
import base64
|
|
import http.server
|
|
import json
|
|
import secrets
|
|
import ssl
|
|
import time
|
|
import urllib.parse
|
|
|
|
|
|
class Handler(http.server.BaseHTTPRequestHandler):
|
|
def reply(self, payload):
|
|
body = json.dumps(payload).encode()
|
|
self.send_response(200)
|
|
self.send_header("Content-Type", "application/json")
|
|
self.send_header("Content-Length", str(len(body)))
|
|
self.end_headers()
|
|
self.wfile.write(body)
|
|
|
|
def do_POST(self):
|
|
raw = self.rfile.read(int(self.headers.get("Content-Length", 0))).decode()
|
|
auth = self.headers.get("Authorization", "")
|
|
who = base64.b64decode(auth.removeprefix("Basic ")).decode() if auth.startswith("Basic ") else "none"
|
|
path = self.path.split("?")[0]
|
|
with open("${tokenLog}", "a") as log:
|
|
log.write(f"{path} {who}\n")
|
|
if path.endswith("/introspection"):
|
|
token = urllib.parse.parse_qs(raw).get("token", [""])[0]
|
|
if token == "${routerToken}":
|
|
self.reply({"active": True, "client_id": "swarm-notify-router", "exp": int(time.time()) + 3600})
|
|
else:
|
|
self.reply({"active": False})
|
|
return
|
|
self.reply({"access_token": secrets.token_hex(16), "token_type": "Bearer", "expires_in": 3600})
|
|
|
|
def do_GET(self):
|
|
self.send_error(404)
|
|
|
|
|
|
server = http.server.ThreadingHTTPServer(("${bridgeIp}", 443), Handler)
|
|
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
|
context.load_cert_chain("${pkiDir}/svc.pem", "${pkiDir}/svc-key.pem")
|
|
server.socket = context.wrap_socket(server.socket, server_side=True)
|
|
server.serve_forever()
|
|
'';
|
|
|
|
# Looks every 200 ms at whether the queue's container runs, how many pods
|
|
# the cluster holds for it (a terminating one included), and how many
|
|
# servers and responders the node holds: a pod's processes are the node's.
|
|
sampler = pkgs.writeShellScript "overlap-sampler" ''
|
|
while true; do
|
|
state="$(systemctl is-active ${hostUnit} || true)"
|
|
listing="$(kubectl --namespace ${namespace} get pods --selector app.kubernetes.io/name=${service} --no-headers 2>/dev/null || true)"
|
|
pods="$(printf '%s' "$listing" | grep -c . || true)"
|
|
shown="$(printf '%s' "$listing" | awk '{print $1":"$3}' | tr '\n' ',')"
|
|
servers="$(pgrep -cx nats-server || true)"
|
|
responders="$(pgrep -cx swarm-nats-auth || true)"
|
|
echo "$(date +%s.%N) ${service} host=$state pods=$pods servers=$servers responders=$responders pods-are=''${shown:--}" >> ${overlapLog}
|
|
sleep 0.2
|
|
done
|
|
'';
|
|
|
|
# What a client sees of the queue's certificate. The server speaks first
|
|
# and upgrades to TLS on the same connection, so `openssl s_client` cannot
|
|
# dial it: this reads the server's greeting, then verifies the certificate
|
|
# against a root for a name, and prints its serial.
|
|
tlsProbe = pkgs.writeText "natstls.py" ''
|
|
import socket
|
|
import ssl
|
|
import sys
|
|
|
|
host, name, root = sys.argv[1:4]
|
|
sock = socket.create_connection((host, ${toString natsPort}), timeout=10)
|
|
greeting = sock.recv(4096)
|
|
assert greeting.startswith(b"INFO"), greeting
|
|
context = ssl.create_default_context(cafile=root)
|
|
context.verify_flags &= ~ssl.VERIFY_X509_STRICT
|
|
tls = context.wrap_socket(sock, server_hostname=name)
|
|
print(tls.getpeercert()["serialNumber"])
|
|
'';
|
|
|
|
# A port the node's firewall opens, which the second node reaches: the control
|
|
# for every refusal it sees.
|
|
controlListener = pkgs.writeText "control.py" ''
|
|
import http.server
|
|
|
|
http.server.ThreadingHTTPServer(("0.0.0.0", ${toString controlPort}), http.server.SimpleHTTPRequestHandler).serve_forever()
|
|
'';
|
|
in
|
|
pkgs.testers.runNixOSTest {
|
|
name = "k8s-nats-switch";
|
|
|
|
# The store takes a few minutes to open its raft storage, and the script
|
|
# switches the configuration three times. Under the 1 h job bound with room
|
|
# for the build before the test starts.
|
|
globalTimeout = 2700;
|
|
|
|
nodes.machine =
|
|
{ config, ... }:
|
|
{
|
|
imports = [ self.nixosModules.default ];
|
|
|
|
services.hyperhive = {
|
|
deploy.k8s.enable = true;
|
|
network.enable = true;
|
|
network.bridgeIp = bridgeIp;
|
|
# The egress intercept is on, which makes the forward chain refuse an
|
|
# agent's traffic to anything but the bridge, as on a hive controller host.
|
|
deploy.hive-controller.egress.intercept = {
|
|
enable = true;
|
|
refuseEch = false;
|
|
};
|
|
deploy.bao.enable = true;
|
|
deploy.bao.seal = "shamir";
|
|
deploy.bao.bootstrapTokenFile = "/var/lib/swarm-bao-bootstrap/grant.token";
|
|
deploy.nats.enable = true;
|
|
deploy.hive-controller.hiveName = "h1";
|
|
swarm.domain = "t.local";
|
|
swarm.bao.domain = baoName;
|
|
swarm.bao.port = baoPort;
|
|
swarm.hives.h1.domain = "h1.t.local";
|
|
# The identity provider is host-run: its name goes to the bridge for the
|
|
# queue's responder, as the hive's own do.
|
|
gateway.localNames = [ authName ];
|
|
};
|
|
system.stateVersion = "25.11";
|
|
|
|
specialisation.k8s.configuration.services.hyperhive.deploy.nats.runtime = "k8s";
|
|
specialisation.k8s-open.configuration.services.hyperhive.deploy.nats = {
|
|
runtime = "k8s";
|
|
openFirewall = true;
|
|
};
|
|
|
|
# The store's TLS passthrough is a stream server of the host's nginx,
|
|
# which needs certificates this host does not mint, so a second nginx
|
|
# carries the passthrough alone, as `k8s-runtime-switch` does.
|
|
services.nginx.enable = lib.mkForce false;
|
|
networking.hosts."${bridgeIp}" = [
|
|
baoName
|
|
natsName
|
|
authName
|
|
];
|
|
systemd.services.bao-stream = {
|
|
wantedBy = [ "multi-user.target" ];
|
|
after = [ "network.target" ];
|
|
serviceConfig = {
|
|
RuntimeDirectory = "bao-stream";
|
|
Restart = "always";
|
|
RestartSec = 2;
|
|
ExecStart =
|
|
let
|
|
conf = pkgs.writeText "bao-stream.conf" ''
|
|
pid /run/bao-stream/nginx.pid;
|
|
error_log stderr;
|
|
events {}
|
|
stream {
|
|
${config.services.nginx.streamConfig}
|
|
}
|
|
'';
|
|
in
|
|
"${pkgs.nginx}/bin/nginx -c ${conf} -g 'daemon off;'";
|
|
};
|
|
};
|
|
|
|
# The hive's CA, and one leaf for the identity provider's name, which this
|
|
# test makes. The trust bundle is the unit `hive-tls-ca`'s, and the
|
|
# store's services-root unit reloads that unit when it has fetched the
|
|
# store's root, so the test's own script is the one the unit runs on
|
|
# every reload. The queue's leaf chains to that root.
|
|
systemd.services.hive-tls-ca = {
|
|
path = [
|
|
pkgs.openssl
|
|
pkgs.coreutils
|
|
];
|
|
script = lib.mkForce ''
|
|
set -euo pipefail
|
|
install -d -m 0755 ${pkiDir} ${tlsDir}
|
|
cd ${pkiDir}
|
|
if [ ! -s ca.pem ]; then
|
|
openssl req -x509 -newkey rsa:2048 -nodes -keyout ca-key.pem -out ca.pem \
|
|
-subj "/CN=test-ca" -days 3650 \
|
|
-addext basicConstraints=critical,CA:TRUE -addext keyUsage=critical,keyCertSign
|
|
openssl req -newkey rsa:2048 -nodes -keyout svc-key.pem -out svc.csr -subj "/CN=${authName}"
|
|
printf 'subjectAltName=DNS:${authName}\n' > svc.ext
|
|
openssl x509 -req -in svc.csr -CA ca.pem -CAkey ca-key.pem -CAcreateserial \
|
|
-days 3650 -extfile svc.ext -out svc.pem
|
|
chmod 0644 ca.pem svc.pem svc-key.pem
|
|
fi
|
|
cat ca.pem > ${tlsDir}/trust-bundle.pem
|
|
if [ -s ${tlsDir}/swarm-services-root.pem ]; then
|
|
cat ${tlsDir}/swarm-services-root.pem >> ${tlsDir}/trust-bundle.pem
|
|
fi
|
|
chmod 0644 ${tlsDir}/trust-bundle.pem
|
|
'';
|
|
};
|
|
|
|
systemd.services.token-stub = {
|
|
wantedBy = [ "multi-user.target" ];
|
|
after = [ "hive-tls-ca.service" ];
|
|
requires = [ "hive-tls-ca.service" ];
|
|
serviceConfig = {
|
|
ExecStart = "${pkgs.python3}/bin/python3 ${tokenStub}";
|
|
Restart = "always";
|
|
RestartSec = 2;
|
|
};
|
|
};
|
|
|
|
systemd.services.control-listener = {
|
|
wantedBy = [ "multi-user.target" ];
|
|
serviceConfig = {
|
|
ExecStart = "${pkgs.python3}/bin/python3 ${controlListener}";
|
|
WorkingDirectory = "/etc";
|
|
};
|
|
};
|
|
networking.firewall.allowedTCPPorts = [ controlPort ];
|
|
|
|
systemd.services.overlap-sampler = {
|
|
path = [
|
|
pkgs.kubectl
|
|
pkgs.coreutils
|
|
pkgs.gnugrep
|
|
pkgs.gawk
|
|
pkgs.procps
|
|
pkgs.systemd
|
|
];
|
|
environment.KUBECONFIG = "/etc/rancher/k3s/k3s.yaml";
|
|
serviceConfig.ExecStart = sampler;
|
|
};
|
|
|
|
networking.interfaces.eth1.ipv4.addresses = lib.mkForce [
|
|
{
|
|
address = nodeIp;
|
|
prefixLength = 24;
|
|
}
|
|
];
|
|
|
|
environment.systemPackages = [
|
|
pkgs.kubectl
|
|
pkgs.curl
|
|
pkgs.jq
|
|
pkgs.openssl
|
|
pkgs.natscli
|
|
pkgs.netcat
|
|
pkgs.iproute2
|
|
pkgs.procps
|
|
pkgs.python3
|
|
];
|
|
environment.etc."natstls.py".source = tlsProbe;
|
|
environment.variables.KUBECONFIG = "/etc/rancher/k3s/k3s.yaml";
|
|
environment.etc."k3s-node/images".text = lib.concatMapStrings (
|
|
i: "${i.imageName}:${i.imageTag}\n"
|
|
) config.system.build.k8sImages;
|
|
|
|
# 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 = 8192;
|
|
cores = 4;
|
|
diskSize = 20480;
|
|
};
|
|
};
|
|
|
|
# A host outside the node, on its network: it dials the queue by name.
|
|
nodes.outside =
|
|
{ ... }:
|
|
{
|
|
networking.interfaces.eth1.ipv4.addresses = lib.mkForce [
|
|
{
|
|
address = outsideIp;
|
|
prefixLength = 24;
|
|
}
|
|
];
|
|
networking.hosts."${nodeIp}" = [ natsName ];
|
|
environment.systemPackages = [
|
|
pkgs.natscli
|
|
pkgs.openssl
|
|
pkgs.netcat
|
|
pkgs.curl
|
|
pkgs.python3
|
|
];
|
|
environment.etc."natstls.py".source = tlsProbe;
|
|
};
|
|
|
|
testScript = builtins.readFile ./lib/k3s.py + ''
|
|
INIT = "/root/bao-init.json"
|
|
NS = "${namespace}"
|
|
SERVICE = "${service}"
|
|
HOST_UNIT = "${hostUnit}"
|
|
PRUNE = "${prune}"
|
|
NAME = "${natsName}"
|
|
PORT = ${toString natsPort}
|
|
METRICS = ${toString metricsPort}
|
|
METRICS_SERVICE = "${service}-metrics"
|
|
METRICS_HOST = f"{METRICS_SERVICE}.{NS}.svc.cluster.local"
|
|
NODE = "${nodeIp}"
|
|
BRIDGE = "${bridgeIp}"
|
|
CONTROL = ${toString controlPort}
|
|
MANIFESTS = "/var/lib/rancher/k3s/server/manifests"
|
|
SERVICES_ROOT = "${tlsDir}/swarm-services-root.pem"
|
|
TOKEN = "${routerToken}"
|
|
STREAM = "ROUTER_TODOS"
|
|
QUEUE_UP = (
|
|
"systemctl --machine=swarm-nats is-active nats.service "
|
|
"&& 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"
|
|
|
|
|
|
def as_root(command: str) -> str:
|
|
return machine.succeed(f'BAO_TOKEN="$(jq -r .root_token {INIT})" {command}')
|
|
|
|
|
|
def diagnose(units: list[str]) -> None:
|
|
for unit in units:
|
|
print(f"--- {unit}")
|
|
print(machine.execute(f"systemctl status {unit} --no-pager -l; journalctl -u {unit} --no-pager -n 60")[1])
|
|
if unit == HOST_UNIT:
|
|
print(machine.execute("journalctl --machine=swarm-nats -u nats.service -u swarm-nats-auth.service --no-pager -n 40")[1])
|
|
|
|
|
|
def settle(command: str, timeout: int, units: list[str]) -> None:
|
|
try:
|
|
machine.wait_until_succeeds(command, timeout=timeout)
|
|
except Exception:
|
|
diagnose(units)
|
|
raise
|
|
|
|
|
|
def pods() -> list[str]:
|
|
return machine.succeed(f"kubectl -n {NS} get pods --selector app.kubernetes.io/name={SERVICE} -o name || true").split()
|
|
|
|
|
|
def pod_pid(container: str) -> str:
|
|
id_ = machine.succeed(f"k3s crictl ps --name '^{container}$' --state running -q").split()[0]
|
|
return machine.succeed(f"k3s crictl inspect {id_} | jq -r .info.pid").strip()
|
|
|
|
|
|
def dials(pid: str, address: str, port: int) -> str:
|
|
"""A command that opens a TCP connection from the network namespace of
|
|
the process `pid`, as the pod in it would."""
|
|
return f"nsenter --target {pid} --net -- timeout 5 bash -c '</dev/tcp/{address}/{port}'"
|
|
|
|
|
|
def host_state() -> str:
|
|
return machine.execute(f"systemctl is-active {HOST_UNIT}")[1].strip()
|
|
|
|
|
|
def stopped_at(unit: str) -> int:
|
|
return int(machine.succeed(f"date -d \"$(systemctl show -p InactiveEnterTimestamp --value {unit})\" +%s"))
|
|
|
|
|
|
def created_at_of(pod_name: str) -> int:
|
|
stamp = machine.succeed(f"kubectl -n {NS} get pod {pod_name} -o jsonpath='{{.metadata.creationTimestamp}}'")
|
|
return int(machine.succeed(f"date -d \"{stamp}\" +%s"))
|
|
|
|
|
|
def wait_pod_ready(not_uid: str = "", timeout: int = 600) -> str:
|
|
"""The name of the Ready pod of the queue that is not terminating and
|
|
has a uid other than `not_uid`."""
|
|
live = (
|
|
f"kubectl -n {NS} get pods --selector app.kubernetes.io/name={SERVICE} -o json "
|
|
f"| jq -r '.items[] | select(.metadata.deletionTimestamp == null and .metadata.uid != \"{not_uid}\") | .metadata.name'"
|
|
)
|
|
machine.wait_until_succeeds(f"{live} | grep -q .", timeout=timeout)
|
|
name = machine.succeed(live).split()[0]
|
|
try:
|
|
wait_pod(machine, name, phase="Running", ready=True, timeout=timeout)
|
|
except Exception:
|
|
diagnose(["hyperhive-k8s-ca-trust.service"])
|
|
print(machine.execute(f"kubectl -n {NS} describe pod {name}")[1])
|
|
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
|
|
|
|
|
|
def switch(target: str) -> str:
|
|
"""Switches to `target`. Units of this host that fail for reasons of
|
|
their own make the exit status 4; the units the switch is about must
|
|
not be among them."""
|
|
status, out = machine.execute(f"{target}/bin/switch-to-configuration test 2>&1")
|
|
print(out)
|
|
assert status in (0, 4), out
|
|
failed = next((line for line in out.splitlines() if "the following units failed" in line), "")
|
|
ours = [HOST_UNIT, f"{PRUNE}.service", "hyperhive-k8s-ca-trust.service", "k3s.service", "firewall.service"]
|
|
assert not any(unit in failed for unit in ours), failed
|
|
return out
|
|
|
|
|
|
def nats_cmd(root: str, *args: str) -> str:
|
|
"""The `nats` client dialling the queue by name, trusting the root at
|
|
`root`, as the notification router: its token and its inbox."""
|
|
return f"nats --server tls://{NAME}:{PORT} --tlsca {root} --token {TOKEN} --inbox-prefix {INBOX} {' '.join(args)} 2>&1"
|
|
|
|
|
|
def nats(node: QemuMachine, *args: str) -> str:
|
|
return node.succeed(nats_cmd(SERVICES_ROOT, *args), timeout=60)
|
|
|
|
|
|
def stream_messages() -> int:
|
|
out = nats(machine, f"stream info {STREAM} --json")
|
|
return int(json.loads(out)["state"]["messages"])
|
|
|
|
|
|
def probe(node: QemuMachine, address: str, name: str = NAME, root: str = SERVICES_ROOT) -> tuple[bool, str]:
|
|
"""Whether the queue at `address` presents a certificate that `root`
|
|
verifies for `name`, and what it printed: the certificate's serial."""
|
|
status, out = node.execute(f"python3 /etc/natstls.py {address} {name} {root} 2>&1")
|
|
return status == 0, out.strip()
|
|
|
|
|
|
def probe_from_agent() -> tuple[bool, str]:
|
|
"""`probe` from the netns of the client on the bridge, at the bridge's
|
|
address, by the name an agent dials."""
|
|
status, out = machine.execute(f"ip netns exec agent python3 /etc/natstls.py {BRIDGE} {NAME} {SERVICES_ROOT} 2>&1")
|
|
return status == 0, out.strip()
|
|
|
|
|
|
def reachable(node: QemuMachine, address: str, port: int) -> bool:
|
|
return node.execute(f"nc -z -w 4 {address} {port}")[0] == 0
|
|
|
|
|
|
def counts() -> tuple[int, int]:
|
|
"""How many servers and responders the node runs."""
|
|
servers = int(machine.execute("pgrep -cx nats-server")[1].strip() or 0)
|
|
responders = int(machine.execute("pgrep -cx swarm-nats-auth")[1].strip() or 0)
|
|
return servers, responders
|
|
|
|
|
|
with subtest("the node is Ready and holds every image"):
|
|
wait_node_ready(machine, timeout=300)
|
|
wait_images(machine, timeout=300)
|
|
kube(machine, f"config set-context --current --namespace={NS}")
|
|
outside.start()
|
|
outside.wait_for_unit("multi-user.target")
|
|
|
|
with subtest("the store is initialised, unsealed and bootstrapped"):
|
|
machine.wait_until_succeeds('[ "$(bao status >/dev/null 2>&1; echo $?)" = 2 ]', timeout=900)
|
|
machine.succeed(f"umask 077 && bao operator init -key-shares=1 -key-threshold=1 -format=json > {INIT}")
|
|
unseal_bao(machine, INIT)
|
|
machine.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"
|
|
)
|
|
machine.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 queue's policies and roles, and the jwt mount"):
|
|
machine.succeed("systemctl reset-failed 'swarm-bao-*-policy.service' swarm-bao-agent-pki.service || true")
|
|
machine.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"])
|
|
if machine.execute("journalctl -u swarm-bao-agent-pki --no-pager | grep -F 'restart openbao.service'")[0] == 0:
|
|
machine.succeed("systemctl --machine=swarm-bao restart openbao.service")
|
|
machine.wait_until_succeeds('[ "$(bao status >/dev/null 2>&1; echo $?)" = 2 ]', timeout=900)
|
|
unseal_bao(machine, INIT)
|
|
for unit in [
|
|
"swarm-bao-nats-tls-policy",
|
|
"swarm-bao-nats-auth-policy",
|
|
"swarm-bao-services-issuer-policy",
|
|
"swarm-bao-k8s-jwt-policy",
|
|
]:
|
|
settle(f'[ "$(systemctl is-active {unit}.service)" = active ]', 900, [f"{unit}.service"])
|
|
machine.wait_until_succeeds(
|
|
"journalctl -u swarm-bao-k8s-jwt-policy --no-pager | grep -F 'Success! Data written to: auth/jwt-k8s/role/swarm-nats-auth'",
|
|
timeout=300,
|
|
)
|
|
# The responder's client secret at the identity provider, which the
|
|
# identity provider's mint stores in production.
|
|
SECRET = machine.succeed("openssl rand -hex 16").strip()
|
|
as_root(f"bao kv put -mount=secret ${oidcLeaf} value={SECRET}")
|
|
|
|
with subtest("the store's services root is in the trust bundle, and the identity provider's stub runs"):
|
|
machine.wait_for_unit("hive-tls-ca.service")
|
|
machine.succeed("systemctl reset-failed swarm-services-cert.service || true")
|
|
machine.succeed("systemctl restart --no-block swarm-services-cert.service")
|
|
settle(f"test -s {SERVICES_ROOT} && grep -c BEGIN ${tlsDir}/trust-bundle.pem | grep -qx 2", 600, ["swarm-services-cert.service"])
|
|
machine.wait_for_unit("token-stub.service")
|
|
machine.wait_for_unit("control-listener.service")
|
|
machine.succeed("systemctl start overlap-sampler.service")
|
|
|
|
with subtest("on the host, the container's server and responder run, and the cluster holds none of the queue"):
|
|
# The container starts before the store has anything for it: the
|
|
# delivery units land the keys, the leaf and the identity, and restart
|
|
# the server. The container rebuilds its trust bundle by itself when the
|
|
# host's file changes, so the root the store gave is in it.
|
|
for unit in ["swarm-nats-auth-secrets", "swarm-bao-nats-callout-xkey", "swarm-bao-nats-tls"]:
|
|
machine.succeed(f"systemctl reset-failed {unit}.service || true")
|
|
settle(f"systemctl restart {unit}.service", 900, [f"{unit}.service"])
|
|
settle(QUEUE_UP, 600, [HOST_UNIT])
|
|
assert machine.succeed(f"systemctl is-active {PRUNE}.service").strip() == "active"
|
|
assert pods() == [], pods()
|
|
assert machine.execute(f"kubectl -n {NS} get deployment {SERVICE}")[0] != 0
|
|
assert machine.execute(f"kubectl -n {NS} get service {METRICS_SERVICE}")[0] != 0
|
|
assert machine.execute(f"kubectl -n {NS} get networkpolicy {SERVICE}")[0] != 0
|
|
# The control for its absence under the cluster.
|
|
machine.succeed("test -e /etc/nixos-containers/swarm-nats.conf")
|
|
assert counts() == (1, 1), counts()
|
|
# The queue answers by name on the bridge's address, with its name
|
|
# verified against the store's root, and admits the router's token.
|
|
settle(f"python3 /etc/natstls.py {BRIDGE} {NAME} {SERVICES_ROOT}", 120, [HOST_UNIT])
|
|
machine.wait_until_succeeds(nats_cmd(SERVICES_ROOT, "account info"), timeout=120)
|
|
machine.wait_until_succeeds(f"grep -F '/api/oidc/introspection ${service}:{SECRET}' ${tokenLog}", timeout=60)
|
|
|
|
with subtest("a host outside the node cannot reach the queue's port, while it reaches a port the node opens"):
|
|
assert reachable(outside, NODE, CONTROL), "the control port is unreachable: the node cannot be told from a closed port"
|
|
assert not reachable(outside, NODE, PORT), "the container's port is open to a host outside the node"
|
|
assert machine.execute(f"nc -z -w 4 {NODE} {PORT}")[0] == 0
|
|
|
|
with subtest("a client on the hive's bridge reaches the queue by its name, as an agent does"):
|
|
BRIDGE_IF = machine.succeed("ip -o -4 addr show | grep -F 'inet ${bridgeIp}/' | cut -d' ' -f2").strip()
|
|
machine.succeed(
|
|
"ip netns add agent && ip link add va type veth peer name vb && ip link set vb netns agent "
|
|
f"&& ip link set va master {BRIDGE_IF} && ip link set va up "
|
|
"&& ip -n agent addr add ${agentIp}/24 dev vb && ip -n agent link set vb up && ip -n agent link set lo up "
|
|
"&& ip -n agent route add default via ${bridgeIp}"
|
|
)
|
|
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
|
|
|
|
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
|
|
assert host_state() == "inactive", host_state()
|
|
machine.succeed(f"test -L {MANIFESTS}/{SERVICE}.yaml")
|
|
pod_name = wait_pod_ready()
|
|
assert stopped_at(HOST_UNIT) <= created_at_of(pod_name)
|
|
assert machine.execute("machinectl list --no-legend | grep -q swarm-nats")[0] != 0
|
|
# The configuration has no container left to start beside the pod.
|
|
machine.fail("test -e /etc/nixos-containers/swarm-nats.conf")
|
|
assert counts() == (1, 1), counts()
|
|
|
|
with subtest("the pod holds the leaf and the config as init containers, and has no hostPort on the server or the exporter"):
|
|
spec = pod(machine, pod_name)["spec"]
|
|
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")
|
|
client = next(p for p in server["ports"] if p["name"] == "client")
|
|
assert client == {"name": "client", "containerPort": PORT, "protocol": "TCP"}, client
|
|
command = server["readinessProbe"]["exec"]["command"]
|
|
assert command[0] == "/bin/wget" and command[-1].endswith("/healthz?js-enabled-only=true"), command
|
|
exporter = next(c for c in spec["containers"] if c["name"] == "exporter")
|
|
assert exporter["ports"] == [{"name": "metrics", "containerPort": METRICS, "protocol": "TCP"}], exporter["ports"]
|
|
assert not any(c.get("resources") for c in spec["containers"]), spec["containers"]
|
|
assert not any("secret" in v for v in spec["volumes"]), spec["volumes"]
|
|
assert spec["hostAliases"] == [{"ip": "127.0.0.1", "hostnames": [NAME]}], spec["hostAliases"]
|
|
# 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}-store -o json"))
|
|
assert claim["status"]["phase"] == "Bound", claim
|
|
STATE_VOLUME = claim["metadata"]["uid"]
|
|
# The leaf's key is in memory.
|
|
uid = pod(machine, pod_name)["metadata"]["uid"]
|
|
mount = f"pods/{uid}/volumes/kubernetes.io~empty-dir"
|
|
assert machine.succeed(f"grep -F '{mount}/nats-tls ' /proc/mounts | cut -d' ' -f3").strip() == "tmpfs"
|
|
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
|
|
# 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)
|
|
assert int(limits.split()[3]) >= 800000, limits
|
|
|
|
with subtest("the exporter is a ClusterIP Service, and the pod's policy admits the client port from any source and nothing else"):
|
|
svc = json.loads(kube(machine, f"get service {METRICS_SERVICE} -o json"))
|
|
assert svc["spec"]["type"] == "ClusterIP", svc["spec"]
|
|
assert [(p["port"], p["targetPort"]) for p in svc["spec"]["ports"]] == [(METRICS, "metrics")], svc["spec"]
|
|
policy = json.loads(kube(machine, f"get networkpolicy {SERVICE} -o json"))["spec"]
|
|
assert policy["policyTypes"] == ["Ingress"], policy
|
|
assert policy["ingress"] == [{"ports": [{"port": PORT, "protocol": "TCP"}]}], policy
|
|
|
|
with subtest("the client port is a LoadBalancer Service with no node port, which the cluster's load balancer binds on the node from kube-system"):
|
|
machine.wait_until_succeeds(
|
|
f"kubectl -n {NS} get service {SERVICE} -o jsonpath='{{.status.loadBalancer.ingress[0].ip}}' | grep -q .",
|
|
timeout=300,
|
|
)
|
|
svc = json.loads(kube(machine, f"get service {SERVICE} -o json"))
|
|
assert svc["spec"]["type"] == "LoadBalancer", svc["spec"]
|
|
assert svc["spec"]["allocateLoadBalancerNodePorts"] is False, svc["spec"]
|
|
assert [(p["port"], p["targetPort"]) for p in svc["spec"]["ports"]] == [(PORT, "client")], svc["spec"]
|
|
assert not any("nodePort" in p for p in svc["spec"]["ports"]), svc["spec"]
|
|
lb_pods = json.loads(kube(machine, f"-n kube-system get pods --selector svccontroller.k3s.cattle.io/svcname={SERVICE} -o json"))["items"]
|
|
assert len(lb_pods) == 1, lb_pods
|
|
lb_ports = [p for c in lb_pods[0]["spec"]["containers"] for p in c.get("ports", [])]
|
|
assert [(p["hostPort"], p["containerPort"]) for p in lb_ports] == [(PORT, PORT)], lb_ports
|
|
assert all(p.get("hostIP", "") in ("", "0.0.0.0") for p in lb_ports), lb_ports
|
|
# No node port: the Service has a rule for its cluster address, the
|
|
# control that the lookup finds it, and none in the chain of node ports.
|
|
assert f"hyperhive/{SERVICE}:client" in machine.succeed("iptables -t nat -S KUBE-SERVICES")
|
|
assert f"hyperhive/{SERVICE}:client" not in machine.succeed("iptables -t nat -S KUBE-NODEPORTS")
|
|
|
|
with subtest("one server and one responder run, and the queue answers by name with its name verified"):
|
|
assert counts() == (1, 1), counts()
|
|
assert probe(machine, BRIDGE)[0], probe(machine, BRIDGE)
|
|
assert probe(machine, NODE)[0], probe(machine, NODE)
|
|
|
|
with subtest("the pod's responder admits the router's token and the account holds a stream the router fills"):
|
|
nats(machine, f"stream add {STREAM} --subjects '{SUBJECT}' --storage file --defaults")
|
|
nats(machine, f"pub '{SUBJECT}' --count 1 'a todo'")
|
|
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, behind the egress chain that refuses it everything else of the cluster, 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 probe_from_agent()[0], probe_from_agent()
|
|
# The same pod by its own address, and the queue by the node's address,
|
|
# are no flow the host published for the agent: both are refused.
|
|
pod_ip = kube(machine, f"get pod {pod_name} -o jsonpath='{{.status.podIP}}'").strip()
|
|
assert pod_ip.startswith("10.200."), pod_ip
|
|
assert machine.execute(f"ip netns exec agent nc -z -w 4 {pod_ip} {PORT}")[0] != 0
|
|
assert machine.execute(f"ip netns exec agent nc -z -w 4 {NODE} {PORT}")[0] != 0
|
|
assert machine.execute(f"ip netns exec agent nc -z -w 4 {BRIDGE} {METRICS}")[0] != 0
|
|
assert reachable(outside, NODE, CONTROL)
|
|
assert not reachable(outside, NODE, PORT), "the pod's port is open to a host outside the node"
|
|
|
|
with subtest("the exporter answers the host's own processes by its Service's name, and refuses a client of the bridge and a pod of the cluster"):
|
|
ip = kube(machine, f"get service {METRICS_SERVICE} -o jsonpath='{{.spec.clusterIP}}'").strip()
|
|
assert machine.succeed(f"getent ahostsv4 {METRICS_HOST}").split()[0] == ip
|
|
body = machine.succeed(f"curl -sf http://{METRICS_HOST}:{METRICS}/metrics")
|
|
assert "gnatsd_varz_connections" in body, body[:500]
|
|
# The bridge's client has the route to the Service's address through the
|
|
# host, and the pod's policy refuses it. A pod of the cluster reaches the
|
|
# queue's client port, the control that it can dial out, and not the
|
|
# exporter.
|
|
assert machine.execute(f"ip netns exec agent nc -z -w 4 {ip} {METRICS}")[0] != 0
|
|
other = pod_pid("coredns")
|
|
machine.succeed(dials(other, BRIDGE, PORT))
|
|
machine.wait_until_fails(dials(other, ip, METRICS), timeout=120)
|
|
for _ in range(3):
|
|
assert machine.execute(dials(other, ip, METRICS))[0] != 0
|
|
|
|
with subtest("a leaf that has to be issued again is issued beside the running server, which reloads it for new connections"):
|
|
uid = pod(machine, pod_name)["metadata"]["uid"]
|
|
leaf_dir = machine.succeed(f"grep -F 'pods/{uid}/volumes/kubernetes.io~empty-dir/nats-tls ' /proc/mounts | cut -d' ' -f2").strip()
|
|
|
|
before = probe(machine, NODE)
|
|
assert before[0], before
|
|
machine.succeed(f"rm {leaf_dir}/cert.pem")
|
|
machine.wait_until_succeeds(
|
|
f"kubectl -n {NS} logs {pod_name} -c tls-renew | grep -F 'leaf was renewed'",
|
|
timeout=900,
|
|
)
|
|
machine.wait_until_succeeds(f"[ \"$(python3 /etc/natstls.py {NODE} {NAME} {SERVICES_ROOT})\" != \"{before[1]}\" ]", timeout=60)
|
|
assert probe(machine, NODE)[0]
|
|
nats(machine, "account info")
|
|
assert counts() == (1, 1), counts()
|
|
|
|
with subtest("deleting the pod keeps the stream: the volume is the same and the message is read after"):
|
|
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}-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
|
|
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"):
|
|
switch("/run/booted-system/specialisation/k8s-open")
|
|
assert len(pods()) == 1, pods()
|
|
machine.wait_until_succeeds(f"nc -z -w 4 {NODE} {PORT}", timeout=60)
|
|
assert reachable(outside, NODE, PORT), "openFirewall left the pod's port closed to a host outside the node"
|
|
root = machine.succeed(f"cat {SERVICES_ROOT}")
|
|
outside.succeed(f"cat > /root/root.pem <<'EOF'\n{root}EOF")
|
|
verified = probe(outside, NAME, root="/root/root.pem")
|
|
assert verified[0], verified
|
|
# By name, as the store's root verifies it, and with the token the
|
|
# responder in the pod admits.
|
|
listed = outside.succeed(nats_cmd("/root/root.pem", f"stream info {STREAM} --json"), timeout=60)
|
|
assert json.loads(listed)["state"]["messages"] == 1, listed
|
|
# A name the leaf does not carry is refused.
|
|
wrong = probe(outside, NODE, name="other.t.local", root="/root/root.pem")
|
|
assert not wrong[0], wrong
|
|
# The exporter's port stays closed to everyone but the host.
|
|
assert not reachable(outside, NODE, METRICS)
|
|
|
|
with subtest("the switch back removes the Deployment, pod and AddOn before the container starts"):
|
|
switch("/run/booted-system")
|
|
settle(f"[ \"$(systemctl is-active {HOST_UNIT})\" = active ]", 600, [HOST_UNIT, f"{PRUNE}.service"])
|
|
assert pods() == [], pods()
|
|
assert machine.execute(f"kubectl -n {NS} get deployment {SERVICE}")[0] != 0
|
|
assert machine.execute(f"kubectl -n {NS} get service {METRICS_SERVICE}")[0] != 0
|
|
assert machine.execute(f"kubectl -n {NS} get service {SERVICE}")[0] != 0
|
|
assert machine.execute(f"kubectl -n {NS} get networkpolicy {SERVICE}")[0] != 0
|
|
# The load balancer's pod and its `hostPort` rule are gone before the
|
|
# container listens on the port.
|
|
assert machine.succeed(f"kubectl -n kube-system get pods --selector svccontroller.k3s.cattle.io/svcname={SERVICE} -o name").strip() == ""
|
|
assert f"--dport {PORT} " not in machine.succeed("iptables -t nat -S")
|
|
assert machine.execute(f"kubectl -n kube-system get addons.k3s.cattle.io {SERVICE}")[0] != 0
|
|
assert machine.execute(f"test -e {MANIFESTS}/{SERVICE}.yaml")[0] != 0
|
|
assert machine.execute(f"test -e {MANIFESTS}/{SERVICE}.yaml.pruning")[0] != 0
|
|
pruned = int(machine.succeed(f"systemctl show -p ExecMainExitTimestampMonotonic --value {PRUNE}.service"))
|
|
started = int(machine.succeed(f"systemctl show -p InactiveExitTimestampMonotonic --value {HOST_UNIT}"))
|
|
assert 0 < pruned <= started, (pruned, started)
|
|
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}-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)
|
|
|
|
with subtest("no moment of any switch had two servers or two responders, or the container and a pod together"):
|
|
machine.succeed("systemctl stop overlap-sampler.service")
|
|
lines = machine.succeed("cat ${overlapLog}").splitlines()
|
|
host_up = {"active", "activating", "deactivating", "reloading"}
|
|
samples = []
|
|
for fields in (line.split() for line in lines):
|
|
if len(fields) == 7:
|
|
samples.append(
|
|
(
|
|
fields[2].removeprefix("host="),
|
|
int(fields[3].removeprefix("pods=")),
|
|
int(fields[4].removeprefix("servers=")),
|
|
int(fields[5].removeprefix("responders=")),
|
|
)
|
|
)
|
|
both = [s for s in samples if s[0] in host_up and s[1] > 0]
|
|
assert not both, [line for line in lines if "pods=0" not in line and "host=inactive" not in line][:8]
|
|
many = [s for s in samples if s[2] > 1 or s[3] > 1]
|
|
assert not many, many[:5]
|
|
# The controls: the sampler saw the container alone, a pod alone, and
|
|
# a server and a responder in each.
|
|
assert any(s[0] in host_up and s[1] == 0 and s[2] == 1 and s[3] == 1 for s in samples), lines[:5]
|
|
assert any(s[0] not in host_up and s[1] > 0 and s[2] == 1 and s[3] == 1 for s in samples), lines[:5]
|
|
print(f"${service}: {len(samples)} samples, none with two copies")
|
|
'';
|
|
}
|