k8s: pod logs and metrics reach the hive collector
This commit is contained in:
parent
f7f298ff4f
commit
ba0c41048e
8 changed files with 447 additions and 51 deletions
|
|
@ -35,9 +35,10 @@ The renderer reads the service's evaluated unit, not a copy of its settings:
|
||||||
|
|
||||||
- **Environment:** the unit's `environment`, including what other modules
|
- **Environment:** the unit's `environment`, including what other modules
|
||||||
merge into it, minus `PATH`. A systemd `%d` becomes the credential
|
merge into it, minus `PATH`. A systemd `%d` becomes the credential
|
||||||
directory it stands for. The renderer fails if the unit's `path` holds
|
directory it stands for. On a host with a hive collector, the OTLP endpoint
|
||||||
anything beyond the NixOS default tools, because the image doesn't carry
|
variables point at it ([Pod logs and metrics](telemetry.md)) instead. The
|
||||||
them.
|
renderer fails if the unit's `path` holds anything beyond the NixOS default
|
||||||
|
tools, because the image doesn't carry them.
|
||||||
- **Files:** the pod mounts each file the unit names at the same path,
|
- **Files:** the pod mounts each file the unit names at the same path,
|
||||||
so the environment carries over unchanged:
|
so the environment carries over unchanged:
|
||||||
- credentials at `/run/credentials/<service>.service/<id>`, from the Secret
|
- credentials at `/run/credentials/<service>.service/<id>`, from the Secret
|
||||||
|
|
@ -98,11 +99,8 @@ object.
|
||||||
## Not covered yet
|
## Not covered yet
|
||||||
|
|
||||||
- The pods reach the swarm's host-run services (store, queue, identity
|
- The pods reach the swarm's host-run services (store, queue, identity
|
||||||
provider) by the same names as the units do. Those names don't resolve to
|
provider) by the same names as the units do. The node's CoreDNS answers those
|
||||||
the host from inside a cluster yet.
|
names with the hive bridge's address.
|
||||||
- `OTEL_EXPORTER_OTLP_ENDPOINT` keeps the unit's value. For
|
|
||||||
`swarm-notify-router` that's its container's local log and metrics
|
|
||||||
forwarder, which a pod doesn't have.
|
|
||||||
- `swarm-controller`'s socket lives in an `emptyDir`, so only the pod can
|
- `swarm-controller`'s socket lives in an `emptyDir`, so only the pod can
|
||||||
reach it.
|
reach it.
|
||||||
|
|
||||||
|
|
|
||||||
62
docs/4-implementation/k8s/telemetry.md
Normal file
62
docs/4-implementation/k8s/telemetry.md
Normal file
|
|
@ -0,0 +1,62 @@
|
||||||
|
# Pod logs and metrics
|
||||||
|
|
||||||
|
The swarm's log and metric stores stay where they are. A pod's output reaches
|
||||||
|
them through the hive collector that runs on the host
|
||||||
|
(`opentelemetry-collector`, [Telemetry](../swarm/telemetry.md)), so
|
||||||
|
`swarm-logs query` and `swarm-metrics` show a pod's records next to the ones
|
||||||
|
the same service produced as a host unit.
|
||||||
|
|
||||||
|
## Metrics
|
||||||
|
|
||||||
|
A pod pushes OTLP to `http://hive-collector.hive:4318`, the address agents use.
|
||||||
|
The node's CoreDNS answers the name with the hive bridge's address
|
||||||
|
([The cluster node](node.md)). The [renderer](manifests.md) sets
|
||||||
|
`OTEL_EXPORTER_OTLP_ENDPOINT` to that address in every pod. For
|
||||||
|
`swarm-ci-metrics`, whose poller reads `SWARM_CI_METRICS_OTLP_ENDPOINT`, it sets
|
||||||
|
that variable too. A unit's own endpoint is a loopback forwarder or a gateway
|
||||||
|
route that needs a token, and a pod has neither. A host without a hive
|
||||||
|
collector keeps the unit's value.
|
||||||
|
|
||||||
|
The collector stamps the hive's `hive` label on what it forwards, as it does for
|
||||||
|
agents. The pods run on that hive's node.
|
||||||
|
|
||||||
|
## Logs
|
||||||
|
|
||||||
|
With `services.hyperhive.deploy.k8s.enable` on a host that runs the hive
|
||||||
|
collector, the collector gains a `file_log/pods` receiver on
|
||||||
|
`/var/log/pods/*/*/*.log`, where the container runtime writes each container's
|
||||||
|
output. One node means one reader, with no per-node agent. The receiver:
|
||||||
|
|
||||||
|
- reads the CRI framing, and takes the namespace, pod, uid and container name
|
||||||
|
from the file's path into resource attributes (`k8s.*`);
|
||||||
|
- reads the level of hive-log's text format, a timestamp then the level
|
||||||
|
(`WARN`, `INFO`), into the record's severity. A line in another shape
|
||||||
|
keeps no severity;
|
||||||
|
- keeps its read offsets in the collector's `file_storage`, so a restart resumes
|
||||||
|
where it stopped.
|
||||||
|
|
||||||
|
`service.name` is the container's name without `swarm-`: `controller`,
|
||||||
|
`notify-router`, `ci-metrics`. That matches what the swarm's container services
|
||||||
|
stamp on their journal records. The host units of `swarm-controller` and
|
||||||
|
`swarm-ci-metrics` carry no `service.name` on their journal records, so a pod's
|
||||||
|
output is the first to carry one for them.
|
||||||
|
|
||||||
|
## Access to the files
|
||||||
|
|
||||||
|
The container runtime writes a log file as root with mode 0640, and the
|
||||||
|
nixpkgs collector unit runs as a dynamic user. With the node on, the collector
|
||||||
|
runs as the static user `opentelemetry-collector`, and `systemd-tmpfiles` puts
|
||||||
|
an ACL on `/var/log/pods`: read and traverse for that user on the directory and
|
||||||
|
on everything under it, with a default entry so the directories kubelet creates
|
||||||
|
later inherit it. The rule also creates the directory, mode 0755 as kubelet
|
||||||
|
creates it. The user reads nothing else the file mode doesn't already let
|
||||||
|
every user read. With the node off, the unit and the collector's configuration
|
||||||
|
are the ones it has without the module.
|
||||||
|
|
||||||
|
## Validation
|
||||||
|
|
||||||
|
`module-eval-k8s` checks the configuration with the option on and off, the
|
||||||
|
rendered endpoints, and the ACL's path. The VM test `k8s-node` runs a pod that
|
||||||
|
writes a `WARN` and an `INFO` line, and checks that the collector's user reads
|
||||||
|
the pod's log file, that the lines arrive with those severities under the
|
||||||
|
container's name, and that a metric a pod pushes arrives.
|
||||||
|
|
@ -24,6 +24,7 @@ in
|
||||||
imports = [
|
imports = [
|
||||||
./host-services.nix
|
./host-services.nix
|
||||||
./node.nix
|
./node.nix
|
||||||
|
./pod-logs.nix
|
||||||
];
|
];
|
||||||
|
|
||||||
options.services.hyperhive.k8s = {
|
options.services.hyperhive.k8s = {
|
||||||
|
|
|
||||||
119
nix/host-modules/k8s/pod-logs.nix
Normal file
119
nix/host-modules/k8s/pod-logs.nix
Normal 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;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
@ -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}";
|
fail = name: msg: throw "services.hyperhive.k8s: ${name}: ${msg}";
|
||||||
|
|
||||||
labelsFor = name: {
|
labelsFor = name: {
|
||||||
|
|
@ -127,6 +146,7 @@ let
|
||||||
|
|
||||||
env =
|
env =
|
||||||
unitEnv
|
unitEnv
|
||||||
|
// podOtlpEnv unitEnv
|
||||||
// lib.optionalAttrs (runtimeDir != null) { RUNTIME_DIRECTORY = runtimeDir; }
|
// lib.optionalAttrs (runtimeDir != null) { RUNTIME_DIRECTORY = runtimeDir; }
|
||||||
// lib.optionalAttrs (stateDir != null) { STATE_DIRECTORY = stateDir; }
|
// lib.optionalAttrs (stateDir != null) { STATE_DIRECTORY = stateDir; }
|
||||||
// lib.optionalAttrs (svc.healthEnv != null) {
|
// lib.optionalAttrs (svc.healthEnv != null) {
|
||||||
|
|
|
||||||
|
|
@ -943,9 +943,8 @@ in
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Root-owned 0400: the collector runs under `DynamicUser`, so there is
|
# Root-owned 0400: `LoadCredential` reads it as root before the
|
||||||
# no stable uid to hand the file to, and `LoadCredential` reads it as
|
# collector's user exists, so that user needs no access to it.
|
||||||
# root before the sandbox exists.
|
|
||||||
install -d -m 0700 ${lib.escapeShellArg hiveOtelSecret.dir}
|
install -d -m 0700 ${lib.escapeShellArg hiveOtelSecret.dir}
|
||||||
if secret_differs ${lib.escapeShellArg fetchedSecretPath} "$secret"; then
|
if secret_differs ${lib.escapeShellArg fetchedSecretPath} "$secret"; then
|
||||||
atomic_write_secret 0400 "" ${lib.escapeShellArg fetchedSecretPath} "$secret"
|
atomic_write_secret 0400 "" ${lib.escapeShellArg fetchedSecretPath} "$secret"
|
||||||
|
|
|
||||||
|
|
@ -92,14 +92,27 @@ let
|
||||||
_: v: builtins.replaceStrings [ "%d" ] [ "/run/credentials/${name}.service" ] (toString v)
|
_: v: builtins.replaceStrings [ "%d" ] [ "/run/credentials/${name}.service" ] (toString v)
|
||||||
) (removeAttrs units.${name}.environment [ "PATH" ]);
|
) (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.
|
# What the pod adds on top of the unit's own environment.
|
||||||
added = {
|
added = {
|
||||||
swarm-controller = {
|
swarm-controller = {
|
||||||
|
OTEL_EXPORTER_OTLP_ENDPOINT = collectorEndpoint;
|
||||||
RUNTIME_DIRECTORY = "/run/swarm-controller";
|
RUNTIME_DIRECTORY = "/run/swarm-controller";
|
||||||
STATE_DIRECTORY = "/var/lib/swarm-controller";
|
STATE_DIRECTORY = "/var/lib/swarm-controller";
|
||||||
};
|
};
|
||||||
swarm-notify-router.SWARM_NOTIFY_ROUTER_HEALTH_ADDR = "0.0.0.0:8080";
|
swarm-notify-router = {
|
||||||
swarm-ci-metrics.STATE_DIRECTORY = "/var/lib/swarm-ci-metrics";
|
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
|
# 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.subtractLists (names withNode.systemd.services) (names allLocal.systemd.services) == [ ]
|
||||||
&& lib.elem "k3s" added
|
&& lib.elem "k3s" added
|
||||||
&& lib.all (n: lib.hasPrefix "k3s" n) added
|
&& lib.all (n: lib.hasPrefix "k3s" n) added
|
||||||
&& lib.all (
|
&&
|
||||||
n:
|
lib.all
|
||||||
withNode.systemd.services.${n}.serviceConfig.ExecStart or null
|
(
|
||||||
== allLocal.systemd.services.${n}.serviceConfig.ExecStart or null
|
n:
|
||||||
) (lib.remove "firewall" (names allLocal.systemd.services))
|
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;
|
&& withNode.system.build.k8sManifests.drvPath == allLocal.system.build.k8sManifests.drvPath;
|
||||||
}
|
}
|
||||||
{
|
{
|
||||||
|
|
@ -305,6 +326,105 @@ let
|
||||||
&& nodeNoBridge.services.hyperhive.deploy.k8s.hostServices == { }
|
&& nodeNoBridge.services.hyperhive.deploy.k8s.hostServices == { }
|
||||||
&& !(nodeNoBridge.services.k3s.manifests ? coredns-custom);
|
&& !(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
|
in
|
||||||
runGroup "k8s" cases
|
runGroup "k8s" cases
|
||||||
|
|
|
||||||
|
|
@ -16,9 +16,13 @@
|
||||||
# - a pod resolves the swarm's bao name and the hive collector's name to the
|
# - 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
|
# hive bridge's address, completes TLS to a listener there that requires a
|
||||||
# client certificate (refused without one), and POSTs one OTLP record to
|
# client certificate (refused without one), and POSTs one OTLP record to
|
||||||
# another that receives it. The listeners are stand-ins for the store's
|
# another that receives it. The first listener stands in for the store's
|
||||||
# passthrough and the collector: the name, the address and the route from a
|
# passthrough; the second is the collector as the node module configures it,
|
||||||
# pod are what the test is about.
|
# 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
|
# 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.
|
# host and fail here, which nothing in this test reads.
|
||||||
|
|
@ -32,6 +36,8 @@ let
|
||||||
baoName = "bao.t.local";
|
baoName = "bao.t.local";
|
||||||
baoPort = 8200;
|
baoPort = 8200;
|
||||||
collectorName = "hive-collector.hive";
|
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.
|
# The pod the script execs into: a shell, `nslookup` and `curl`, no more.
|
||||||
probeImage = pkgs.dockerTools.buildLayeredImage {
|
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
|
in
|
||||||
pkgs.testers.runNixOSTest {
|
pkgs.testers.runNixOSTest {
|
||||||
name = "k8s-node";
|
name = "k8s-node";
|
||||||
|
|
@ -135,16 +122,38 @@ pkgs.testers.runNixOSTest {
|
||||||
'';
|
'';
|
||||||
};
|
};
|
||||||
|
|
||||||
# An OTLP/HTTP receiver where the hive collector listens.
|
# The hive collector as far as the pods go: its receiver on the bridge,
|
||||||
systemd.services.otlp-standin = {
|
# the cursor store the pod logs receiver names, and a file where the real
|
||||||
wantedBy = [ "multi-user.target" ];
|
# one has the swarm's collector. The pod logs pipeline, the collector's
|
||||||
serviceConfig = {
|
# user and its access to /var/log/pods come from the node module.
|
||||||
ExecStart = "${pkgs.python3}/bin/python3 ${otlpReceiver} ${bridgeIp}";
|
services.opentelemetry-collector = {
|
||||||
StateDirectory = "otlp-standin";
|
enable = true;
|
||||||
Restart = "always";
|
package = pkgs.opentelemetry-collector-contrib;
|
||||||
RestartSec = 2;
|
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.
|
# The references `lib/k3s.py`'s `wait_images` looks for.
|
||||||
environment.etc."k3s-node/images".text = lib.concatMapStrings (
|
environment.etc."k3s-node/images".text = lib.concatMapStrings (
|
||||||
|
|
@ -209,7 +218,7 @@ pkgs.testers.runNixOSTest {
|
||||||
bridge_ip = "${bridgeIp}"
|
bridge_ip = "${bridgeIp}"
|
||||||
bao = "${baoName}"
|
bao = "${baoName}"
|
||||||
collector = "${collectorName}"
|
collector = "${collectorName}"
|
||||||
for unit in ["bao-standin", "otlp-standin"]:
|
for unit in ["bao-standin", "opentelemetry-collector"]:
|
||||||
machine.wait_for_unit(unit)
|
machine.wait_for_unit(unit)
|
||||||
machine.wait_until_succeeds("test -f /var/lib/bao-standin/client.pem")
|
machine.wait_until_succeeds("test -f /var/lib/bao-standin/client.pem")
|
||||||
kube(
|
kube(
|
||||||
|
|
@ -268,7 +277,75 @@ pkgs.testers.runNixOSTest {
|
||||||
f"http://{collector}:4318/v1/logs"
|
f"http://{collector}:4318/v1/logs"
|
||||||
)
|
)
|
||||||
assert status == 0, (status, out)
|
assert status == 0, (status, out)
|
||||||
received = machine.succeed("cat /var/lib/otlp-standin/received")
|
machine.wait_until_succeeds("grep -F from-the-pod ${collectorOut}", timeout=60)
|
||||||
assert "/v1/logs " in received and "from-the-pod" in received, received
|
|
||||||
|
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)
|
||||||
'';
|
'';
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue