Watch
0
0
Fork
You've already forked hyperhive
0

k8s: pod logs and metrics reach the hive collector

This commit is contained in:
atlas 2026-11-21 14:01:39 +01:00 • committed by mara
commit dbcc47573e

View file

@ -16,9 +16,13 @@
# - a pod resolves the swarm's bao name and the hive collector's name to the
# hive bridge's address, completes TLS to a listener there that requires a
# client certificate (refused without one), and POSTs one OTLP record to
# another that receives it. The listeners are stand-ins for the store's
# passthrough and the collector: the name, the address and the route from a
# pod are what the test is about.
# another that receives it. The first listener stands in for the store's
# passthrough; the second is the collector as the node module configures it,
# writing to a file;
# - the collector runs as a static user that reads a pod's log file under
# /var/log/pods and nothing else, a pod's WARN line in hive-log's text format
# reaches the collector's output with WARN severity under the container's
# name without its `swarm-` prefix, and so does a metric a pod pushes.
#
# The poller's own host unit and its trust bundle unit stay as they are on the
# host and fail here, which nothing in this test reads.
@ -32,6 +36,8 @@ let
baoName = "bao.t.local";
baoPort = 8200;
collectorName = "hive-collector.hive";
collectorOut = "/var/lib/opentelemetry-collector/out.json";
collectorUser = "opentelemetry-collector";
# The pod the script execs into: a shell, `nslookup` and `curl`, no more.
probeImage = pkgs.dockerTools.buildLayeredImage {
@ -43,25 +49,6 @@ let
];
};
# Receives OTLP over HTTP on the address in `argv[1]` and appends each
# request's path and body to a file.
otlpReceiver = pkgs.writeText "otlp-receiver.py" ''
import http.server
import sys
class Handler(http.server.BaseHTTPRequestHandler):
def do_POST(self):
body = self.rfile.read(int(self.headers["Content-Length"]))
with open("/var/lib/otlp-standin/received", "ab") as f:
f.write(self.path.encode() + b" " + body + b"\n")
self.send_response(200)
self.end_headers()
self.wfile.write(b"{}")
http.server.HTTPServer((sys.argv[1], 4318), Handler).serve_forever()
'';
in
pkgs.testers.runNixOSTest {
name = "k8s-node";
@ -135,16 +122,38 @@ pkgs.testers.runNixOSTest {
'';
};
# An OTLP/HTTP receiver where the hive collector listens.
systemd.services.otlp-standin = {
wantedBy = [ "multi-user.target" ];
serviceConfig = {
ExecStart = "${pkgs.python3}/bin/python3 ${otlpReceiver} ${bridgeIp}";
StateDirectory = "otlp-standin";
Restart = "always";
RestartSec = 2;
# The hive collector as far as the pods go: its receiver on the bridge,
# the cursor store the pod logs receiver names, and a file where the real
# one has the swarm's collector. The pod logs pipeline, the collector's
# user and its access to /var/log/pods come from the node module.
services.opentelemetry-collector = {
enable = true;
package = pkgs.opentelemetry-collector-contrib;
settings = {
extensions.file_storage = {
directory = "/var/lib/opentelemetry-collector";
create_directory = true;
};
receivers.otlp.protocols.http.endpoint = "${bridgeIp}:4318";
exporters.file.path = collectorOut;
service.extensions = [ "file_storage" ];
service.pipelines.logs = {
receivers = [ "otlp" ];
exporters = [ "file" ];
};
service.pipelines.metrics = {
receivers = [ "otlp" ];
exporters = [ "file" ];
};
};
};
services.hyperhive.deploy.k8s.podLogsExporters = [ "file" ];
# The receiver binds the bridge address, which can come up after the
# unit's first start.
systemd.services.opentelemetry-collector = {
startLimitIntervalSec = 0;
serviceConfig.RestartSec = 2;
};
# The references `lib/k3s.py`'s `wait_images` looks for.
environment.etc."k3s-node/images".text = lib.concatMapStrings (
@ -209,7 +218,7 @@ pkgs.testers.runNixOSTest {
bridge_ip = "${bridgeIp}"
bao = "${baoName}"
collector = "${collectorName}"
for unit in ["bao-standin", "otlp-standin"]:
for unit in ["bao-standin", "opentelemetry-collector"]:
machine.wait_for_unit(unit)
machine.wait_until_succeeds("test -f /var/lib/bao-standin/client.pem")
kube(
@ -268,7 +277,75 @@ pkgs.testers.runNixOSTest {
f"http://{collector}:4318/v1/logs"
)
assert status == 0, (status, out)
received = machine.succeed("cat /var/lib/otlp-standin/received")
assert "/v1/logs " in received and "from-the-pod" in received, received
machine.wait_until_succeeds("grep -F from-the-pod ${collectorOut}", timeout=60)
with subtest("the collector runs as a static user with an ACL on the pod logs and nowhere else"):
show = machine.succeed("systemctl show -p User -p DynamicUser opentelemetry-collector")
assert "User=${collectorUser}" in show and "DynamicUser=no" in show, show
pods_acl = machine.succeed("getfacl -p /var/log/pods")
assert "user:${collectorUser}:r-x" in pods_acl, pods_acl
assert "default:user:${collectorUser}:r-x" in pods_acl, pods_acl
assert "${collectorUser}" not in machine.succeed("getfacl -p /var/log")
with subtest("a pod's log lines reach the collector's output with their severity and the container's name"):
logger = {
"apiVersion": "v1",
"kind": "Pod",
"metadata": {"name": "logprobe"},
"spec": {
"containers": [
{
"name": "swarm-logprobe",
"image": "k8s-probe:test",
"imagePullPolicy": "Never",
"command": [
"sh",
"-c",
"echo '2026-11-21T10:00:00.000000Z WARN logprobe: warn-line-from-pod'; "
"echo '2026-11-21T10:00:01.000000Z INFO logprobe: info-line-from-pod'; "
"sleep 3600",
],
}
],
},
}
machine.succeed(f"echo {shlex.quote(json.dumps(logger))} | kubectl apply -f -")
wait_pod(machine, "logprobe", phase="Running", ready=True, timeout=180)
# The file kubelet's runtime wrote, its owner and mode as containerd
# made them, and the collector's user reading it through the ACL.
log_file = machine.succeed("ls /var/log/pods/default_logprobe_*/swarm-logprobe/0.log").strip()
print(machine.succeed(f"stat -c '%U:%G %a' {log_file}"))
status, out = machine.execute(f"runuser -u ${collectorUser} -- cat {log_file}")
assert status == 0 and "warn-line-from-pod" in out, (status, out)
status, out = machine.execute("runuser -u ${collectorUser} -- cat /etc/shadow")
assert status != 0, out
machine.wait_until_succeeds("grep -F info-line-from-pod ${collectorOut}", timeout=90)
records = []
for line in machine.succeed("cat ${collectorOut}").splitlines():
for rl in json.loads(line).get("resourceLogs", []):
res = {a["key"]: a["value"].get("stringValue") for a in rl["resource"].get("attributes", [])}
for sl in rl["scopeLogs"]:
records += [(res, r) for r in sl["logRecords"]]
by_body = {r["body"].get("stringValue", ""): (res, r) for res, r in records}
warn_res, warn = next(v for k, v in by_body.items() if "warn-line-from-pod" in k)
info_res, info = next(v for k, v in by_body.items() if "info-line-from-pod" in k)
assert (warn["severityText"], warn["severityNumber"]) == ("WARN", 13), warn
assert (info["severityText"], info["severityNumber"]) == ("INFO", 9), info
for res in [warn_res, info_res]:
assert res["service.name"] == "logprobe", res
assert res["k8s.namespace.name"] == "default", res
assert res["k8s.container.name"] == "swarm-logprobe", res
with subtest("a metric a pod pushes to the collector arrives"):
status, out = probe(
"curl -sS -m 10 -X POST -H 'Content-Type: application/json' "
"-d '{\"resourceMetrics\":[{\"scopeMetrics\":[{\"metrics\":[{\"name\":\"probe.gauge\","
"\"gauge\":{\"dataPoints\":[{\"asDouble\":1,\"timeUnixNano\":\"1\"}]}}]}]}]}' "
f"http://{collector}:4318/v1/metrics"
)
assert status == 0, (status, out)
machine.wait_until_succeeds("grep -F probe.gauge ${collectorOut}", timeout=60)
'';
}