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 maia
commit ba0c41048e
6 changed files with 447 additions and 51 deletions

View file

@ -24,6 +24,7 @@ in
imports = [
./host-services.nix
./node.nix
./pod-logs.nix
];
options.services.hyperhive.k8s = {

View file

@ -0,0 +1,119 @@
# The logs of the cluster's pods, read by the host's collector.
#
# On a host that runs a collector (`services.opentelemetry-collector`, the hive
# tier's, ../otel.nix) and the k3s node, the collector reads the CRI log files
# kubelet keeps under /var/log/pods and ships them down its own exporters. The
# node is one host, so one reader covers every pod.
# docs/4-implementation/k8s/telemetry.md has the design.
#
# containerd writes each log file as root, mode 0640, so the collector's user
# needs an ACL. It is a static user rather than the nixpkgs unit's dynamic one
# because an ACL names a user that exists before the unit starts. The ACL
# covers /var/log/pods and what kubelet creates under it, and nothing else.
{
config,
lib,
...
}:
let
cfg = config.services.hyperhive.deploy.k8s;
user = "opentelemetry-collector";
logsDir = "/var/log/pods";
collector = config.services.opentelemetry-collector;
in
{
options.services.hyperhive.deploy.k8s.podLogsExporters = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [ "otlphttp/swarm" ];
internal = true;
description = ''
The exporters the pod logs pipeline ends in. The hive collector's one
exporter by default; the VM test points it at a file.
'';
};
config = lib.mkIf (cfg.enable && collector.enable) {
users.users.${user} = {
isSystemUser = true;
group = user;
};
users.groups.${user} = { };
systemd.services.opentelemetry-collector.serviceConfig = {
DynamicUser = lib.mkForce false;
User = user;
Group = user;
# What `DynamicUser` implied and a static user does not.
PrivateTmp = true;
ProtectHome = true;
RemoveIPC = true;
};
# `A+` sets the ACL on the directory and what is in it, and the default
# entry on every directory, so the per-pod directories kubelet creates
# later inherit it. The `d` line makes the directory exist before kubelet
# does, with the mode kubelet gives it.
systemd.tmpfiles.rules = [
"d ${logsDir} 0755 root root -"
"A+ ${logsDir} - - - - u:${user}:rX,d:u:${user}:rX"
];
services.opentelemetry-collector.settings = {
# `file_storage` is the extension the collector defines for its journald
# receiver's cursor (../otel.nix): the offsets survive a restart.
receivers."file_log/pods" = {
include = [ "${logsDir}/*/*/*.log" ];
include_file_path = true;
start_at = "beginning";
storage = "file_storage";
operators = [
# CRI framing; reads the namespace, pod, uid and container name from
# the file's path into resource attributes.
{ type = "container"; }
# hive-log's text format, `tracing-subscriber`'s default: a
# timestamp, then the level. A line that does not start that way
# keeps no severity.
{
type = "regex_parser";
regex = ''^\S+\s+(?P<level>TRACE|DEBUG|INFO|WARN|ERROR)\s'';
parse_from = "body";
on_error = "send_quiet";
}
{
type = "severity_parser";
"if" = "attributes.level != nil";
parse_from = "attributes.level";
overwrite_text = true;
}
{
type = "remove";
"if" = "attributes.level != nil";
field = "attributes.level";
}
];
};
# `service.name` is the container's name without the `swarm-` prefix,
# the name the swarm's container services' own forwarders stamp
# (`nix/container-modules/swarm-journal-forwarder.nix`).
processors."transform/pod-service-name" = {
error_mode = "ignore";
log_statements = [
{
context = "resource";
statements = [
''set(attributes["service.name"], attributes["k8s.container.name"])''
''replace_pattern(attributes["service.name"], "^swarm-", "")''
];
}
];
};
service.pipelines."logs/pods" = {
receivers = [ "file_log/pods" ];
processors = [ "transform/pod-service-name" ];
exporters = cfg.podLogsExporters;
};
};
};
}

View file

@ -73,6 +73,25 @@ let
};
};
# Where a pod pushes telemetry: the hive collector, by the name the node's
# CoreDNS answers with the bridge address (./host-services.nix). A unit's own
# endpoint is a loopback forwarder or a gateway route that needs a token, and
# a pod has neither. `otlpEndpointVars` are the variables a unit may name its
# endpoint in; the first is the standard one and is always set.
otelCfg = hyperhiveCfg.otel;
collectorEndpoint = "http://${otelCfg.collector.host}:${toString hyperhiveCfg.swarm.hiveOtel.collectorPort}";
otlpEndpointVars = [
"OTEL_EXPORTER_OTLP_ENDPOINT"
"SWARM_CI_METRICS_OTLP_ENDPOINT"
];
podOtlpEnv =
unitEnv:
lib.optionalAttrs otelCfg.collector.enable (
lib.genAttrs (lib.filter (
n: n == "OTEL_EXPORTER_OTLP_ENDPOINT" || unitEnv ? ${n}
) otlpEndpointVars) (_: collectorEndpoint)
);
fail = name: msg: throw "services.hyperhive.k8s: ${name}: ${msg}";
labelsFor = name: {
@ -127,6 +146,7 @@ let
env =
unitEnv
// podOtlpEnv unitEnv
// lib.optionalAttrs (runtimeDir != null) { RUNTIME_DIRECTORY = runtimeDir; }
// lib.optionalAttrs (stateDir != null) { STATE_DIRECTORY = stateDir; }
// lib.optionalAttrs (svc.healthEnv != null) {

View file

@ -943,9 +943,8 @@ in
exit 1
fi
# Root-owned 0400: the collector runs under `DynamicUser`, so there is
# no stable uid to hand the file to, and `LoadCredential` reads it as
# root before the sandbox exists.
# Root-owned 0400: `LoadCredential` reads it as root before the
# collector's user exists, so that user needs no access to it.
install -d -m 0700 ${lib.escapeShellArg hiveOtelSecret.dir}
if secret_differs ${lib.escapeShellArg fetchedSecretPath} "$secret"; then
atomic_write_secret 0400 "" ${lib.escapeShellArg fetchedSecretPath} "$secret"

View file

@ -92,14 +92,27 @@ let
_: v: builtins.replaceStrings [ "%d" ] [ "/run/credentials/${name}.service" ] (toString v)
) (removeAttrs units.${name}.environment [ "PATH" ]);
# Where a pod pushes telemetry: the name the hive collector answers to, on
# the port it binds. A literal, so the render and the collector are not
# compared with themselves.
collectorEndpoint = "http://hive-collector.hive:4318";
# What the pod adds on top of the unit's own environment.
added = {
swarm-controller = {
OTEL_EXPORTER_OTLP_ENDPOINT = collectorEndpoint;
RUNTIME_DIRECTORY = "/run/swarm-controller";
STATE_DIRECTORY = "/var/lib/swarm-controller";
};
swarm-notify-router.SWARM_NOTIFY_ROUTER_HEALTH_ADDR = "0.0.0.0:8080";
swarm-ci-metrics.STATE_DIRECTORY = "/var/lib/swarm-ci-metrics";
swarm-notify-router = {
OTEL_EXPORTER_OTLP_ENDPOINT = collectorEndpoint;
SWARM_NOTIFY_ROUTER_HEALTH_ADDR = "0.0.0.0:8080";
};
swarm-ci-metrics = {
OTEL_EXPORTER_OTLP_ENDPOINT = collectorEndpoint;
SWARM_CI_METRICS_OTLP_ENDPOINT = collectorEndpoint;
STATE_DIRECTORY = "/var/lib/swarm-ci-metrics";
};
};
# Host paths the credentials are loaded from: the host units' own
@ -241,11 +254,19 @@ let
&& lib.subtractLists (names withNode.systemd.services) (names allLocal.systemd.services) == [ ]
&& lib.elem "k3s" added
&& lib.all (n: lib.hasPrefix "k3s" n) added
&& lib.all (
n:
withNode.systemd.services.${n}.serviceConfig.ExecStart or null
== allLocal.systemd.services.${n}.serviceConfig.ExecStart or null
) (lib.remove "firewall" (names allLocal.systemd.services))
&&
lib.all
(
n:
withNode.systemd.services.${n}.serviceConfig.ExecStart or null
== allLocal.systemd.services.${n}.serviceConfig.ExecStart or null
)
(
lib.subtractLists [
"firewall"
"opentelemetry-collector"
] (names allLocal.systemd.services)
)
&& withNode.system.build.k8sManifests.drvPath == allLocal.system.build.k8sManifests.drvPath;
}
{
@ -305,6 +326,105 @@ let
&& nodeNoBridge.services.hyperhive.deploy.k8s.hostServices == { }
&& !(nodeNoBridge.services.k3s.manifests ? coredns-custom);
}
{
# The units' own endpoints are the control: each differs from the
# collector's, so the override replaces something. The host's units keep
# theirs.
name = "every pod pushes telemetry to the hive collector, and the host units keep their endpoints";
ok =
lib.all (
name:
(envOf name).OTEL_EXPORTER_OTLP_ENDPOINT == collectorEndpoint
&& (units.${name}.environment.OTEL_EXPORTER_OTLP_ENDPOINT or null) != collectorEndpoint
) (lib.attrNames units)
&& units.swarm-ci-metrics.environment.SWARM_CI_METRICS_OTLP_ENDPOINT != collectorEndpoint
&& (envOf "swarm-ci-metrics").SWARM_CI_METRICS_OTLP_ENDPOINT == collectorEndpoint
&& !(envOf "swarm-notify-router" ? SWARM_CI_METRICS_OTLP_ENDPOINT)
&&
allLocal.systemd.services.swarm-controller.environment.OTEL_EXPORTER_OTLP_ENDPOINT
== "https://${allLocal.services.hyperhive.swarm.otel.domain}/${allLocal.services.hyperhive.swarm.otel.producerName}";
}
{
# Off, the collector's configuration holds nothing of the pod logs, and
# on, taking that out leaves the configuration it has off. The host with
# the node on is the control that the lookups find what is there.
name = "the collector reads pod logs only where deploy.k8s.enable is set";
ok =
let
mine = {
receivers = [ "file_log/pods" ];
processors = [ "transform/pod-service-name" ];
};
settings = c: c.services.opentelemetry-collector.settings;
bare =
s:
s
// {
receivers = removeAttrs s.receivers mine.receivers;
processors = removeAttrs s.processors mine.processors;
service = s.service // {
pipelines = removeAttrs s.service.pipelines [ "logs/pods" ];
};
};
unit = c: c.systemd.services.opentelemetry-collector.serviceConfig;
collectorAcls = c: lib.filter (lib.hasInfix "u:opentelemetry-collector:") c.systemd.tmpfiles.rules;
in
!((settings allLocal).receivers ? "file_log/pods")
&& !((settings allLocal).service.pipelines ? "logs/pods")
&& (settings withNode).receivers ? "file_log/pods"
&& (settings withNode).service.pipelines ? "logs/pods"
&& bare (settings withNode) == settings allLocal
&& (unit allLocal).DynamicUser
&& !(unit allLocal ? User)
&& !(allLocal.users.users ? opentelemetry-collector)
&& collectorAcls allLocal == [ ]
&& !(unit withNode).DynamicUser
&& (unit withNode).User == "opentelemetry-collector"
&& withNode.users.users.opentelemetry-collector.isSystemUser;
}
{
# The receiver reads the files kubelet's runtime writes, the parser reads
# the CRI framing and then hive-log's level, and the service name is the
# container's without `swarm-`. The ACL is on /var/log/pods alone, access
# and default, for the collector's user.
name = "the pod logs receiver parses CRI and the text level, names the service, and the ACL covers /var/log/pods only";
ok =
let
s = withNode.services.opentelemetry-collector.settings;
r = s.receivers."file_log/pods";
ops = r.operators;
op = t: lib.findFirst (o: o.type == t) null ops;
statements = lib.concatMap (
l: l.statements
) s.processors."transform/pod-service-name".log_statements;
acls = lib.filter (lib.hasInfix "u:opentelemetry-collector:") withNode.systemd.tmpfiles.rules;
in
r.include == [ "/var/log/pods/*/*/*.log" ]
&& r.include_file_path
&& r.storage == "file_storage"
&& (lib.head ops).type == "container"
&& lib.all (l: lib.hasInfix l (op "regex_parser").regex) [
"WARN"
"ERROR"
"INFO"
"DEBUG"
"TRACE"
]
&& (op "severity_parser").parse_from == "attributes.level"
&& (op "severity_parser").overwrite_text
&& lib.elem ''set(attributes["service.name"], attributes["k8s.container.name"])'' statements
&& lib.elem ''replace_pattern(attributes["service.name"], "^swarm-", "")'' statements
&&
s.service.pipelines."logs/pods" == {
receivers = [ "file_log/pods" ];
processors = [ "transform/pod-service-name" ];
exporters = [ "otlphttp/swarm" ];
}
&& s.exporters ? "otlphttp/swarm"
&& lib.elem "file_storage" s.service.extensions
&&
acls == [ "A+ /var/log/pods - - - - u:opentelemetry-collector:rX,d:u:opentelemetry-collector:rX" ];
}
];
in
runGroup "k8s" cases

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)
'';
}