Watch
0
0
Fork
You've already forked hyperhive
0

run the log store and its auth responders as pods

swarm-logs-auth and swarm-metrics-auth take --listen for a TCP address beside
--socket. The log store is a Deployment on a static local volume that is its
old container's data directory, behind a ClusterIP Service the gateway dials by
name. Its two auth_request responders are one unpinned pod with a jwt role.
The renderer gains a plain HTTP listener, a probe path, fsGroupChangePolicy,
and one policy for a pod with both a listener and egress.
This commit is contained in:
atlas 2026-11-26 10:17:57 +01:00 • committed by maia
commit 71b2e9310c
13 changed files with 1385 additions and 746 deletions

View file

@ -66,7 +66,6 @@
./glue-secret-publisher-bao-identity.nix
./glue-swarm-bao-otel-oidc-client.nix
./glue-swarm-otel-oidc-client.nix
./glue-victorialogs-otel-oidc-client.nix
./glue-victoriametrics-otel-oidc-client.nix
./swarm-archive.nix
./swarm-attic-options.nix

View file

@ -104,14 +104,12 @@ in
one backfill pass. Remove this definition.
'')
(lib.mkRemovedOptionModule [ "services" "hyperhive" "swarm" "victorialogs" "port" ] ''
VictoriaLogs listens on a unix socket in a network namespace of its own,
and the gateway reaches it there, so it binds no host port. Remove this
definition.
VictoriaLogs runs as a pod behind a Service the gateway dials, so it
binds no host port. Remove this definition.
'')
(lib.mkRemovedOptionModule [ "services" "hyperhive" "deploy" "victorialogs" "port" ] ''
VictoriaLogs listens on a unix socket in a network namespace of its own,
and the gateway reaches it there, so it binds no host port. Remove this
definition.
VictoriaLogs runs as a pod behind a Service the gateway dials, so it
binds no host port. Remove this definition.
'')
(lib.mkRemovedOptionModule [ "services" "hyperhive" "swarm" "victoriametrics" "port" ] ''
VictoriaMetrics listens on a unix socket in a network namespace of its

View file

@ -7,7 +7,7 @@
#
# Gated on authelia being HERE, not on this host running the cache: a client is
# a row in THIS host's provider config, the split
# ./glue-victorialogs-otel-oidc-client.nix makes for the same reason.
# ./glue-victoriametrics-otel-oidc-client.nix makes for the same reason.
{
lib,
config,

View file

@ -1,37 +0,0 @@
# Glue: register the log store container's journal forwarder as an OIDC
# client wherever authelia runs.
#
# ONE PAIRING PER FILE: that forwarder ← authelia, and nothing else.
# Without it authelia mints no secret, the publisher has nothing to copy into
# the store, and the forwarder's export is a 401.
#
# Gated on authelia being HERE, not on this host running the log store: a
# client is a row in THIS host's provider config, the split
# ./glue-swarm-bao-otel-oidc-client.nix makes for the same reason.
{
lib,
config,
...
}:
let
hyperhiveCfg = config.services.hyperhive;
clientId = hyperhiveCfg.swarm.victorialogs.otel.clientId;
in
{
config = lib.mkIf hyperhiveCfg.deploy.authelia.enable {
services.hyperhive.swarm.authelia.oidc.clients = [
{
id = clientId;
description = "HyperHive log store journal forwarder";
kind = "machine";
redirectUris = [ ];
# Its own id as its own permitted audience, the one the swarm
# collector's receiver for this container checks.
audience = [ clientId ];
# The receiver verifies the token offline against `/jwks.json`;
# authelia's default opaque handle fails there.
accessTokenSignedResponseAlg = "RS256";
}
];
};
}

View file

@ -129,13 +129,14 @@ let
"claude-login"
"nats"
"swarm-controller"
"victorialogs"
];
enabledServices = lib.filter (name: deployCfg.${name}.enable) swarmServices;
# The services whose data the module keeps in the cluster. Each puts its state
# label on this node.
stateful = lib.filterAttrs (_: svc: svc.enable) {
inherit (deployCfg) nats ci-metrics;
inherit (deployCfg) nats ci-metrics victorialogs;
};
in
{
@ -264,7 +265,7 @@ in
none of those pods.
- `hyperhive.darkest.space/state-<service>` for each service whose data the
cluster keeps: `nats` and `ci-metrics`, each when enabled. A volume's `nodeAffinity` and the pod's `nodeSelector` name it.
cluster keeps: `nats`, `ci-metrics` and `victorialogs`, each when enabled. A volume's `nodeAffinity` and the pod's `nodeSelector` name it.
- `hyperhive.darkest.space/entry`: the node the hosts' DNS points at.
- `svccontroller.k3s.cattle.io/enablelb`: with it on any node, the
service load balancer binds a published port on the labelled nodes

View file

@ -125,19 +125,21 @@ let
];
};
# The swarm services that run in the cluster. `unit` is the evaluated
# systemd unit the host runs today; nothing reads it unless `enable` holds.
# The swarm services that run in the cluster. `unit` is an evaluated systemd
# unit, or the `serviceConfig`, `environment` and `path` of one; nothing reads
# it unless `enable` holds.
# `healthEnv` names the variable that binds the daemon's /healthz and
# /readyz listener. `publicCredentials` maps the ids of the credentials that
# hold a public CA file to their key in the CA ConfigMap, and `publicFiles`
# the paths the unit names that hold one to theirs. `listener`, where a
# service has one, is the TCP port a Service publishes in the cluster and the
# directory the pod's init container writes the leaf to.
# service has one, is the TCP port a Service publishes and the directory the
# pod's init container writes the leaf to; without a `tlsDir` it is plain HTTP
# and no leaf is issued. `probe` is the path a service without a `healthEnv` is
# probed on, and `fsGroupChangePolicy` the pod's setting of that name.
# `ephemeralState` gives a service an `emptyDir` in place of a claim for its
# state directory: what it keeps there is re-derived at start. A pod starts on
# whatever volume it gets.
# `otlp` is where the pod pushes
# its telemetry: `"hive"` is the hive collector. A swarm-tier producer is
# `otlp` is where the pod pushes its telemetry: `"hive"` is the hive collector. A swarm-tier producer is
# `"own"` and keeps the route its unit names, because the hive collector
# stamps the `hive` label on what it forwards and a swarm-level series must
# not carry one (../swarm-otel.nix, the swarm tier's own pipeline).
@ -255,6 +257,44 @@ let
};
otlp = "own";
};
# The log store: the VictoriaLogs daemon alone, on a static local volume
# that is the old container's data directory. It holds no store identity
# and pushes no telemetry; its own `/metrics` is scraped through the
# gateway.
swarm-victorialogs = {
inherit (deployCfg.victorialogs) enable package unit;
daemon = "victoria-logs";
kind = "Deployment";
healthEnv = null;
probe.path = "/health";
etcFiles = [ ];
publicCredentials = { };
listener.port = deployCfg.victorialogs.servicePort;
localState = {
service = "victorialogs";
hostDir = deployCfg.victorialogs.hostDataDir;
};
# The first start gives the pod's group the tree the old container wrote;
# a later one looks at the root only.
fsGroupChangePolicy = "OnRootMismatch";
otlp = "none";
};
# The two `auth_request` responders of the log store's gateway vhost, which
# log in to the store under one role. They keep no state, so they run on any
# node. The Grafana responder is the second container of the pod, in `pod`.
swarm-logs-auth = {
inherit (deployCfg.victorialogs) enable;
package = deployCfg.victorialogs.authPackage;
unit = deployCfg.victorialogs.authUnit;
inherit (deployCfg.victorialogs) pod;
kind = "Deployment";
healthEnv = "SWARM_LOGS_AUTH_HEALTH_ADDR";
etcFiles = [ ];
publicCredentials."bao-ca.pem" = baoServerCaKey;
listener.port = deployCfg.victorialogs.authServicePort;
egress = [ "store" ];
otlp = "none";
};
};
# Where a pod pushes telemetry. A `"hive"` service pushes to the hive
@ -508,6 +548,9 @@ let
sc = unit.serviceConfig;
listener = svc.listener or { };
# A listener with a `tlsDir` serves TLS with a leaf the pod issues; one
# without serves plain HTTP, for a caller that is the node.
listenerTls = listener ? tlsDir;
publicFiles = svc.publicFiles or { };
daemon = svc.daemon or name;
baoRole = svc.baoRole or name;
@ -594,7 +637,7 @@ let
++ lib.optional (runtimeDir != null) runtimeDir
++ lib.optional (stateDir != null) stateDir
++ lib.attrNames publicFiles
++ lib.optional (listener != { }) listener.tlsDir
++ lib.optional listenerTls listener.tlsDir
++ map (f: "/etc/${f}") svc.etcFiles;
under = root: v: v == root || lib.hasPrefix "${root}/" v;
unmounted = lib.filterAttrs (_: v: lib.hasPrefix "/" v && !(lib.any (r: under r v) mountRoots)) env;
@ -690,7 +733,7 @@ let
name = "ca-trust";
configMap.name = caConfigMap;
}
++ lib.optional (listener != { }) {
++ lib.optional listenerTls {
name = "tls";
# In memory: the leaf's key never reaches the node's disk.
emptyDir.medium = "Memory";
@ -745,7 +788,7 @@ let
subPath = publicFiles.${path};
readOnly = true;
}) (lib.attrNames publicFiles)
++ lib.optional (listener != { }) tlsMount
++ lib.optional listenerTls tlsMount
++ lib.optional (runtimeDir != null) {
name = "runtime";
mountPath = runtimeDir;
@ -824,6 +867,24 @@ let
}
// lib.optionalAttrs (lib.tail execWords != [ ]) { args = lib.tail execWords; }
// lib.optionalAttrs (ports != [ ]) { inherit ports; }
# A daemon that has no health variable of ours (a third-party one) is
# probed on one path of its listener.
// lib.optionalAttrs (svc ? probe) {
livenessProbe = {
httpGet = {
inherit (svc.probe) path;
port = "api";
};
periodSeconds = 10;
};
readinessProbe = {
httpGet = {
inherit (svc.probe) path;
port = "api";
};
periodSeconds = 10;
};
}
// lib.optionalAttrs (svc.healthEnv != null) {
livenessProbe = {
httpGet = {
@ -906,7 +967,7 @@ let
containers = [
container
]
++ lib.optional (listener != { }) (
++ lib.optional listenerTls (
leafContainer
// {
name = "tls-renew";
@ -923,15 +984,16 @@ let
runAsGroup = serviceUser.gid;
fsGroup = serviceUser.gid;
seccompProfile.type = "RuntimeDefault";
};
}
// lib.optionalAttrs (svc ? fsGroupChangePolicy) { inherit (svc) fsGroupChangePolicy; };
}
// lib.optionalAttrs baoLogin { serviceAccountName = name; }
// lib.optionalAttrs (svc ? hostUsers && !svc.hostUsers) { hostUsers = false; }
// lib.optionalAttrs (localState != null) {
nodeSelector = labels.stateSelector localState.service;
}
// lib.optionalAttrs (listener != { } || extra.initContainers != [ ]) {
initContainers = lib.optional (listener != { }) leafContainer ++ extra.initContainers;
// lib.optionalAttrs (listenerTls || extra.initContainers != [ ]) {
initContainers = lib.optional listenerTls leafContainer ++ extra.initContainers;
}
// lib.optionalAttrs (extra.hostAliases != [ ]) { inherit (extra) hostAliases; }
// extra.podSpec;
@ -1007,7 +1069,13 @@ let
// lib.optionalAttrs (svc ? egress) {
"${name}/networkpolicy" = networkPolicyOf name svc.egress;
}
// lib.optionalAttrs (listener != { }) (listenerObjects name listener)
// lib.optionalAttrs (listener != { }) (
# A service with an egress policy has the ingress rule in that one.
if svc ? egress then
removeAttrs (listenerObjects name listener) [ "${name}/networkpolicy" ]
else
listenerObjects name listener
)
// lib.optionalAttrs baoLogin {
# Named after the service: the store's jwt role binds this account.
"${name}/serviceaccount" = {
@ -1063,10 +1131,10 @@ let
fail name "the unit names no OTLP endpoint of its own, which the pod would push to"
else if svc.healthEnv != null && unitEnv ? ${svc.healthEnv} then
fail name "the unit already sets ${svc.healthEnv}"
else if svc ? probe && (listener == { } || svc.healthEnv != null) then
fail name "has a probe and no listener, or a health variable as well"
else if svc ? egress && !(lib.all (r: hostPorts ? ${r}) svc.egress) then
fail name "egress names a host service the renderer has no port for (${lib.concatStringsSep ", " (lib.attrNames hostPorts)})"
else if svc ? egress && listener != { } then
fail name "has an egress policy and a listener, which would share one NetworkPolicy"
else if lib.head execWords != entrypoint then
fail name "ExecStart is not ${entrypoint} with plain arguments"
else if lib.any (w: lib.hasInfix "\"" w) execWords then
@ -1079,7 +1147,7 @@ let
{
inherit objects image;
# What the pod's other containers run.
extraImages = lib.optional (listener != { }) leafImage ++ extra.images;
extraImages = lib.optional listenerTls leafImage ++ extra.images;
};
enabled = lib.mapAttrs workload (lib.filterAttrs (_: svc: svc.enable) services);

View file

@ -158,11 +158,11 @@ let
}
];
# The log store's auth responders: the agent one checks the secret an agent
# presents against the one stored for it (the same `+` leaf as the queue
# responder's) and reads the agent's mirrored `logs`/`metrics` grant, the other checks the bearer Grafana presents against
# Grafana's metrics bearer; and the store container's journal forwarder
# reads its own client secret under the same leaf. Nothing else.
# The log store's auth responders, which run in one pod under one role: the
# agent one checks the secret an agent presents against the one stored for it
# (the same `+` leaf as the queue responder's) and reads the agent's mirrored
# `logs`/`metrics` grant, the other checks the bearer Grafana presents against
# Grafana's metrics bearer. Nothing else.
logsAuthReaders = [
{
name = "swarm-logs-auth";
@ -171,9 +171,7 @@ let
policyText =
readStanza "${credentialMountPath}/data/swarm/agents/+/queue"
+ readStanza "${credentialMountPath}/data/swarm/agents/+/observability"
+ readStanza "${credentialMountPath}/data/${grafanaMetricsBearerLeaf}"
# The journal forwarder in the store's container, under this same leaf.
+ readStanza "${credentialMountPath}/data/swarm/services/${hyperhiveCfg.swarm.victorialogs.otel.clientId}/oidc/client";
+ readStanza "${credentialMountPath}/data/${grafanaMetricsBearerLeaf}";
}
];
@ -418,6 +416,9 @@ let
++ reviewClassifierReaders
++ claudeLoginWriters
++ ciMetricsReaders
# The log store's two responders hold one role, under the ServiceAccount of
# their pod (./k8s/render.nix, `swarm-logs-auth`).
++ logsAuthReaders
++ [ { name = controllerPolicyName; } ]
# The queue's pod holds both of its roles under one ServiceAccount: the
# server's leaf is issued with `swarm-nats`, and the responder reads its

View file

@ -242,9 +242,8 @@ in
swarm-stt = {
clientId = hyperhiveCfg.swarm.stt.clientId;
};
# The forwarders in ./swarm-attic.nix, ./swarm-ci-runner.nix,
# ./swarm-grafana.nix and ./swarm-victorialogs.nix, each authenticated as a
# client of its own.
# The forwarders in ./swarm-attic.nix, ./swarm-ci-runner.nix and
# ./swarm-grafana.nix, each authenticated as a client of its own.
swarm-attic = {
clientId = hyperhiveCfg.swarm.attic.otel.clientId;
};
@ -254,9 +253,6 @@ in
swarm-grafana = {
clientId = hyperhiveCfg.swarm.grafana.otel.clientId;
};
swarm-victorialogs = {
clientId = hyperhiveCfg.swarm.victorialogs.otel.clientId;
};
# The forwarders in ./hive-forge/default.nix and ./hive-matrix.nix, each
# authenticated as a client of its own.
hive-forge = {

View file

@ -250,8 +250,8 @@ let
# Every container with a `serviceProducers` entry (`swarm-bao`, `swarm-nats`,
# `swarm-builder`, `swarm-claude-login`, `swarm-notify-router`,
# `swarm-review-classifier`, `swarm-ci-runner`, `swarm-grafana`,
# `swarm-victorialogs`, `hive-forge`, `hive-matrix`, `swarm-victoriametrics`,
# `swarm-authelia`, `swarm-attic`) forwards its own
# `hive-forge`, `hive-matrix`, `swarm-victoriametrics`, `swarm-authelia`,
# `swarm-attic`) forwards its own
# journal from its own collector, so this receiver never sees their units.
hostJournalDir = "/var/log/journal";
hostJournalMount = "/run/host-journal";

View file

@ -55,13 +55,12 @@ let
hyperhiveCfg.swarm.notify-router.clientId
# The speech-to-text service, which reads it itself inside its container.
hyperhiveCfg.swarm.stt.clientId
# The journal forwarders in the CI runner's, Grafana's, the log store's,
# the cache's, the forge's and the homeserver's containers, each reading it
# inside its container.
# The journal forwarders in the CI runner's, Grafana's, the cache's, the
# forge's and the homeserver's containers, each reading it inside its
# container.
hyperhiveCfg.swarm.attic.otel.clientId
hyperhiveCfg.swarm.ci-runner.otel.clientId
hyperhiveCfg.swarm.grafana.otel.clientId
hyperhiveCfg.swarm.victorialogs.otel.clientId
hyperhiveCfg.swarm.forge.otel.clientId
hyperhiveCfg.swarm.matrix.otel.clientId
# The metrics store container's journal forwarder, whose host reads it.

View file

@ -1,6 +1,6 @@
# The swarm's log store as every hive sees it: the name it answers on and its
# port, identical on every host. What the host running it decides, and the
# container itself, are in ./swarm-victorialogs.nix.
# The swarm's log store as every hive sees it: the name it answers on,
# identical on every host. What the host running it decides, and its pods, are
# in ./swarm-victorialogs.nix.
{
lib,
config,
@ -16,37 +16,10 @@ let
domainBase = if swarmDomain == null then "invalid" else swarmDomain;
in
{
# What the store IS from any hive's point of view: the name it answers on and
# the port. `enable`, `package` and `retentionPeriod` are decisions of the
# host that runs it and live under `deploy.*`.
# What the store IS from any hive's point of view: the name it answers on.
# `enable`, `package` and `retentionPeriod` are decisions of the host that runs
# it and live under `deploy.*`.
options.services.hyperhive.swarm.victorialogs = {
machine = lib.mkOption {
type = lib.types.str;
readOnly = true;
default = "swarm-victorialogs";
description = ''
Container name. Read-only: the name appears in host paths and in
`machinectl`, so it is a fact other modules may read rather than a
knob.
'';
};
otel.clientId = lib.mkOption {
type = lib.types.str;
readOnly = true;
default = "swarm-victorialogs-collector";
description = ''
OAuth2 client id the journal forwarder inside the log store's
container authenticates as, and the audience it asks its token for.
Read-only because three hosts have to agree on it: authelia
registers the client (`glue-victorialogs-otel-oidc-client.nix`),
the swarm collector admits it on the container's receiver
(`swarm.otel.serviceProducers`), and authelia's mint stores
its secret in the store.
'';
};
domain = lib.mkOption {
type = lib.types.str;
default = "logs.${domainBase}";
@ -61,6 +34,5 @@ in
registered for that to actually happen.
'';
};
};
}

View file

@ -1,5 +1,6 @@
# The swarm's log store: one VictoriaLogs for the whole swarm, in a
# `swarm-victorialogs` nixos-container beside the metrics store it mirrors.
# The swarm's log store: one VictoriaLogs for the whole swarm and the gateway's
# `auth_request` responders for it, each a pod in the host's cluster
# (./k8s/render.nix, docs/4-implementation/k8s/runtime.md).
#
# Why a store at all rather than reading journals directly: an agent can
# verify that a unit was *launched* and never that it is *working*. The
@ -14,13 +15,12 @@
# Gateway vhost is authenticated, unlike the metrics store's: an operator
# reaches this at `https://${cfg.domain}/` gated by the same `auth_request`
# check against authelia that swarm-ui's own vhost uses (`swarmAuthRequest`
# below, same shape as `swarm-ui.nix`'s) — see that file's copy for the full
# rationale (forceSSL is load-bearing there too: authelia answers a plain-http
# auth subrequest with 400, which `auth_request` cannot interpret as anything
# but a broken check). The store's own listener is a unix socket in a
# netns of its own and is unauthenticated, and the vhost is the ONLY way in: the
# collector pushes through it too, at its own `= /insert/...` location, because
# a swarm has one log store and the collector need not share a host with it.
# below; `swarm-ui.nix` says why forceSSL is load-bearing: authelia answers a
# plain-http auth subrequest with 400). The store's own listener is unauthenticated and takes
# writes as well as reads. Its Service admits only the node's own traffic, and
# the vhost, which dials it by name, is the ONLY way in: the collector pushes
# through it too, at its own `= /insert/...` location, because the collector
# need not share a host with the store.
# ⚠️ That ingest location deliberately does not carry `swarmAuthRequest` — a
# pusher handed its `error_page 401 =302` follows the redirect and POSTs at a
# login page, which answers 200. See the location itself.
@ -40,6 +40,8 @@ let
networkCfg = config.services.hyperhive.network;
hyperhiveCfg = config.services.hyperhive;
gatewayCfg = hyperhiveCfg.gateway;
k8sCfg = hyperhiveCfg.k8s;
inherit (import ../images { inherit pkgs lib; }) mkServiceImage;
# Copy of `swarm-ui.nix`'s own `swarmAuthRequest` — not shared code because
# this vhost needs exactly the two locations that reference it (`/` and the
@ -75,74 +77,192 @@ let
proxy_ignore_headers Cache-Control Expires Set-Cookie Vary;
'';
# The agents' `auth_request` responder (`swarm-logs-auth`). Its socket's
# directory holds that socket alone and is traverse-only for others, the
# shape `swarm-controller.nix` gives its own.
logsAuthUnit = "swarm-logs-auth";
logsAuthSocket = "/run/${logsAuthUnit}/auth.sock";
logsAuthCredential = id: "/run/credentials/${logsAuthUnit}.service/${id}";
# Credential id → host path of the responder's store identity.
logsAuthStoreFiles = {
"bao-client.pem" = deployCfg.victorialogs.authBaoClientCertFile;
"bao-client-key.pem" = deployCfg.victorialogs.authBaoClientKeyFile;
}
// lib.optionalAttrs (deployCfg.bao.serverCaFile != null) {
"bao-ca.pem" = deployCfg.bao.serverCaFile;
};
# The store identity the responders' units name by credential id: the pod
# logs in with its ServiceAccount token instead, and mounts the CA file.
logsAuthStoreIds = [
"bao-client.pem"
"bao-client-key.pem"
]
++ lib.optional (deployCfg.bao.serverCaFile != null) "bao-ca.pem";
baoCfg = hyperhiveCfg.swarm.bao;
# Grafana's bearer, checked by a second `swarm-metrics-auth` instance. It
# reads the store with the same leaf as `swarm-logs-auth`, which is granted
# the one extra path below. The same leaf as `grafanaBearerStorePath` in
# ./swarm-victoriametrics.nix and `grafanaMetricsBearerLeaf` in ./swarm-bao.nix.
grafanaAuthUnit = "swarm-logs-grafana-auth";
grafanaAuthSocket = "/run/${grafanaAuthUnit}/auth.sock";
grafanaAuthCredential = id: "/run/credentials/${grafanaAuthUnit}.service/${id}";
grafanaBearerStorePath = "swarm/services/${hyperhiveCfg.swarm.grafana.oidc.clientId}/metrics/bearer";
# A netns of its own on the hive bridge, as the cache's container has
# (./swarm-attic.nix): the forwarder below dials the swarm collector, authelia
# and the store by name, so the container keeps an interface and the bridge's
# resolver. The store listens on a unix socket only, so no host port is
# bound. Grafana reaches the store by its domain through the gateway.
privateNetwork = true;
# The workloads, as the cluster names them: the store, and the one pod that
# holds both responders. Each has a Service of its name, which the gateway
# dials. `legacyContainer` is the name of the container the store ran in
# before it ran in the cluster, whose data directory the volume is.
storeService = "swarm-victorialogs";
authService = "swarm-logs-auth";
grafanaAuthService = "swarm-logs-grafana-auth";
legacyContainer = "swarm-victorialogs";
storePort = 9428;
authPort = 8081;
grafanaAuthPort = 8082;
# The Grafana responder's own `/healthz` and `/readyz`, beside the logs
# responder's on 8080 in the same pod.
grafanaAuthHealthPort = 8083;
dataDir = "/var/lib/victorialogs";
hostDataDir = "/var/lib/nixos-containers/${legacyContainer}${dataDir}";
# The unix socket the gateway's nginx connects to. The directory's mode is
# what keeps it private, so it holds this one socket.
socketDir = "/run/swarm-victorialogs";
socketPath = "${socketDir}/victorialogs.sock";
socketGroup = "gateway-nginx";
# Only the number crosses into the container, which knows the group by name.
nginxGid = config.ids.gids.nginx;
# The upstream every location below forwards to. A location that adds a path
# writes `<upstream>:<path>`; one with no path leaves the request's own.
upstream = "http://unix:${socketPath}";
serviceHost = service: "${service}.${k8sCfg.namespace}.svc.${deployCfg.k8s.clusterDomain}";
# The container's journal forwarder pushes to its own receiver on the swarm
# collector, the route `serviceProducers.swarm-victorialogs` in
# ./swarm-otel-service.nix declares.
forwarderClientId = cfg.otel.clientId;
forwarderEndpoint = "https://${hyperhiveCfg.swarm.otel.domain}/${cfg.machine}";
forwarderUnit = "swarm-journal-forwarder-oidc";
# Loopback, in the container's own netns.
forwarderTelemetryPort = 8897;
forwarderCredential = id: "/run/credentials/${forwarderUnit}.service/${id}";
# The responder's store identity, handed into the container as system
# credentials for the forwarder's fetch unit. The host units keep reading
# the same files.
forwarderStoreFiles = lib.filterAttrs (_: source: source != null) logsAuthStoreFiles;
# nixos-container expands `extraFlags` unquoted, so a source path must be
# one word.
oneWord = path: builtins.match ".*[[:space:]].*" path == null;
# What a location needs to dial a Service: the host's resolver, which hands
# the cluster's domain to CoreDNS, and the name in a variable, so that nginx
# looks it up per request. A name written into `proxy_pass` gets one lookup
# when the configuration loads, which fails the load while the cluster is
# down. A `proxy_pass` with a variable and a URI part sends that URI and not
# the request's own, so the store's locations write none. Each role has a
# variable of its own, so that an auth subrequest's `set` can never change
# where the request it checks is sent.
viaService = variable: service: port: ''
resolver ${networkCfg.bridgeIp} valid=10s ipv6=off;
set ${variable} ${serviceHost service}:${toString port};
'';
storeVariable = "$swarm_logs_store_upstream";
upstream = "http://${storeVariable}";
agentAuthVariable = "$swarm_logs_agent_auth_upstream";
grafanaAuthVariable = "$swarm_logs_grafana_auth_upstream";
rootfsCheck = import ./lib/container-rootfs-check.nix { inherit config; };
# The forwarder reaches the swarm collector and authelia by name over TLS; in
# self-signed mode their leaves chain to the hive CA.
caTrust = import ./lib/hive-ca-trust.nix {
inherit lib gatewayCfg;
tlsCfg = deployCfg.hive-controller.tls;
# The store's unit: the daemon, its flags and its state directory, which is
# all the pod is rendered from. Nothing evaluates a systemd unit for it.
storeUnit = {
serviceConfig = {
ExecStart = lib.concatStringsSep " " [
"${deployCfg.victorialogs.package}/bin/victoria-logs"
"-storageDataPath=${dataDir}"
"-httpListenAddr=:${toString storePort}"
"-retentionPeriod=${deployCfg.victorialogs.retentionPeriod}"
];
StateDirectory = "victorialogs";
};
environment = { };
path = [ ];
};
# The agents' `auth_request` responder, with the cert and key ids that the
# pod's login drops.
authCredential = id: "/run/credentials/${authService}.service/${id}";
authUnit = {
serviceConfig = {
ExecStart = lib.concatStringsSep " " [
"${deployCfg.victorialogs.authPackage}/bin/swarm-logs-auth"
"--listen 0.0.0.0:${toString authPort}"
# The role ./swarm-bao.nix writes on the store's `cert` mount.
"--store-cert-role swarm-logs-auth"
"--surface logs"
"--verdict-ttl ${toString deployCfg.victorialogs.authVerdictTtl}"
];
LoadCredential = logsAuthStoreIds;
};
environment = {
BAO_ADDR = "https://${baoCfg.domain}:${toString baoCfg.port}";
BAO_CLIENT_CERT = authCredential "bao-client.pem";
BAO_CLIENT_KEY = authCredential "bao-client-key.pem";
}
// lib.optionalAttrs (builtins.elem "bao-ca.pem" logsAuthStoreIds) {
BAO_CACERT = authCredential "bao-ca.pem";
};
path = [ ];
};
# What the responders' pod holds besides `swarm-logs-auth`: Grafana's
# responder, the metrics store's binary pointed at the bearer Grafana's
# datasources share. It logs in under the pod's one ServiceAccount, with the
# environment and mounts of the first container.
authPod =
{
env,
volumeMounts,
metaFor,
securityContext,
}:
let
image = mkServiceImage {
name = grafanaAuthService;
package = deployCfg.victorialogs.grafanaAuthPackage;
bin = "swarm-metrics-auth";
};
probe = path: {
httpGet = {
inherit path;
port = "health";
};
periodSeconds = 10;
};
in
{
containers = [
{
name = "grafana-auth";
image = "${image.imageName}:${image.imageTag}";
imagePullPolicy = "IfNotPresent";
args = [
"--listen"
"0.0.0.0:${toString grafanaAuthPort}"
"--store-cert-role"
"swarm-logs-auth"
"--store-path"
grafanaBearerStorePath
];
env = lib.mapAttrsToList (name: value: { inherit name value; }) (
lib.filterAttrs (n: _: lib.hasPrefix "BAO_" n) env
// {
SWARM_METRICS_AUTH_HEALTH_ADDR = "0.0.0.0:${toString grafanaAuthHealthPort}";
}
);
ports = [
{
name = "api";
containerPort = grafanaAuthPort;
}
{
name = "health";
containerPort = grafanaAuthHealthPort;
}
];
livenessProbe = probe "/healthz";
readinessProbe = probe "/readyz";
volumeMounts = lib.filter (
m:
lib.elem m.name [
"credentials"
"bao-token"
"tmp"
]
) volumeMounts;
inherit securityContext;
}
];
# The pod's policy, from ./k8s/render.nix, covers this port too: only the
# node reaches it.
objects."${grafanaAuthService}/service" = {
apiVersion = "v1";
kind = "Service";
metadata = metaFor authService // {
name = grafanaAuthService;
};
spec = {
type = "ClusterIP";
selector = (metaFor authService).labels;
ports = [
{
name = "api";
protocol = "TCP";
port = grafanaAuthPort;
targetPort = "api";
}
];
};
};
images = [ image ];
};
in
{
# What the store IS from any hive's point of view, the name it answers on, is
@ -151,10 +271,10 @@ in
# runs it and live under `deploy.*`.
# Retention is a property of the store this host runs, not something the
# swarm has to agree on: it is read only where the container is defined,
# and a hive that is a *client* of the log store never consults it. That
# makes it a `deploy.*` value by the same rule as the seal on the secret
# store — options on the auto-deployed service itself.
# swarm has to agree on: it is read only where the pod is defined, and a hive
# that is a *client* of the log store never consults it. That makes it a
# `deploy.*` value by the same rule as the seal on the secret store —
# options on the auto-deployed service itself.
options.services.hyperhive.deploy.victorialogs.package = lib.mkOption {
type = lib.types.package;
default = pkgs.victorialogs;
@ -271,6 +391,68 @@ in
'';
};
options.services.hyperhive.deploy.victorialogs.unit = lib.mkOption {
type = lib.types.raw;
readOnly = true;
internal = true;
default = storeUnit;
description = ''
The store's unit, the `serviceConfig`, `environment` and `path` that
../host-modules/k8s/render.nix renders its pod from.
'';
};
options.services.hyperhive.deploy.victorialogs.authUnit = lib.mkOption {
type = lib.types.raw;
readOnly = true;
internal = true;
default = authUnit;
description = ''
The agents' responder's unit, which the first container of the
responders' pod is rendered from.
'';
};
options.services.hyperhive.deploy.victorialogs.pod = lib.mkOption {
type = lib.types.raw;
readOnly = true;
internal = true;
default = authPod;
description = ''
What the responders' pod holds besides the agents' responder: a function
of that container that ../host-modules/k8s/render.nix calls, giving
Grafana's responder, its Service and its image.
'';
};
options.services.hyperhive.deploy.victorialogs.servicePort = lib.mkOption {
type = lib.types.port;
readOnly = true;
internal = true;
default = storePort;
description = "The port the store's Service publishes.";
};
options.services.hyperhive.deploy.victorialogs.authServicePort = lib.mkOption {
type = lib.types.port;
readOnly = true;
internal = true;
default = authPort;
description = "The port the agents' responder's Service publishes.";
};
options.services.hyperhive.deploy.victorialogs.hostDataDir = lib.mkOption {
type = lib.types.str;
readOnly = true;
internal = true;
default = hostDataDir;
description = ''
The store's data directory on the host, which the pod's volume is: the
directory of the container the store ran in. A host that never ran it gets
the directory made.
'';
};
config = lib.mkIf deployCfg.victorialogs.enable {
assertions = [
{
@ -289,37 +471,6 @@ in
both options.
'';
}
{
assertion = lib.all oneWord (lib.attrValues forwarderStoreFiles);
message = ''
The log store responder's store identity paths must not contain
whitespace: nspawn's --load-credential receives them through
nixos-container's unquoted extra flags.
'';
}
{
assertion =
(hyperhiveCfg.swarm.otel.serviceProducers.${cfg.machine}.clientId or null) == forwarderClientId;
message = ''
services.hyperhive.swarm.otel.serviceProducers has no entry
"${cfg.machine}" with clientId "${forwarderClientId}", so the swarm
collector has no receiver for the log store's journal forwarder.
Declare it in swarm-otel-service.nix.
'';
}
];
# nspawn fails to start the container when a credential source is
# missing, so where this host mints the leaf the container pulls the
# minting unit in and waits for it, as ./swarm-builder.nix's does. The CA
# ordering keeps the trust bundle's bind source there first.
systemd.services."container@${cfg.machine}" = lib.mkMerge [
caTrust.containerOrdering
(rootfsCheck.warnOnly cfg.machine)
{
after = [ "swarm-bao-pki.service" ];
wants = [ "swarm-bao-pki.service" ];
}
];
# Which check a `/select/logsql/` request gets. `auth_request` takes a
@ -353,14 +504,14 @@ in
# `swarm-victoriametrics.nix`).
services.hyperhive.gateway.localNames = [ cfg.domain ];
# This host serves the vhost, and the container behind it resolves
# This host serves the vhost and resolves the cluster's names for it
# through the hive's dnsmasq.
services.hyperhive.gateway.enable = lib.mkDefault true;
services.hyperhive.gateway.dns.enable = lib.mkDefault true;
# Authenticated front door onto the store's socket — see the
# file-top comment for why this is safe to add without touching the
# store's own (still unauthenticated, socket-only) listener at all.
# Authenticated front door onto the store's Service — see the file-top
# comment for why the store's own unauthenticated listener is reached
# through this vhost alone.
# `forceSSL`: same asymmetry `swarm-ui.nix` documents —
# authelia answers a plain-http auth subrequest with 400, which
# `auth_request` cannot read as anything but a broken check, so this
@ -370,8 +521,8 @@ in
forceSSL = true;
locations = {
"/" = {
proxyPass = "${upstream}:/";
extraConfig = swarmAuthRequest;
proxyPass = upstream;
extraConfig = viaService storeVariable storeService storePort + swarmAuthRequest;
};
# The swarm collector's ingest route. `=` so it outranks the `/`
@ -389,8 +540,9 @@ in
# note on `swarmAuthRequest` above), so naming it here is required
# rather than redundant.
"= /insert/opentelemetry/v1/logs" = {
proxyPass = "${upstream}:/insert/opentelemetry/v1/logs";
proxyPass = upstream;
extraConfig = ''
${viaService storeVariable storeService storePort}
auth_request /__swarm_logs_ingest_authz;
'';
};
@ -425,6 +577,7 @@ in
# the store as the caller sent them.
proxyPass = upstream;
extraConfig = ''
${viaService storeVariable storeService storePort}
auth_request /__swarm_logs_auth;
'';
};
@ -440,8 +593,9 @@ in
# authelia's rules for this URL admit the collector's client and
# deny every other subject (see `metricsRules` in ./swarm-authelia.nix).
"= /metrics" = {
proxyPass = "${upstream}:/metrics";
proxyPass = upstream;
extraConfig = ''
${viaService storeVariable storeService storePort}
auth_request /__hive_authelia;
'';
};
@ -463,8 +617,9 @@ in
# statuses `auth_request` passes through are 401 and 403, and
# `swarm-logs` retries a 401.
"= /__swarm_logs_agent_auth" = {
proxyPass = "http://unix:${logsAuthSocket}:/";
proxyPass = "http://${agentAuthVariable}/";
extraConfig = ''
${viaService agentAuthVariable authService authPort}
internal;
limit_req zone=swarm_logs_agent_auth burst=${toString deployCfg.victorialogs.authBurst} nodelay;
limit_req_status 403;
@ -477,8 +632,9 @@ in
# `swarm-metrics-auth`. The responder reads the store at most once per
# its cache TTL whatever the bearers, so no rate limit sits in front.
"= /__swarm_logs_grafana_auth" = {
proxyPass = "http://unix:${grafanaAuthSocket}:/";
proxyPass = "http://${grafanaAuthVariable}/";
extraConfig = ''
${viaService grafanaAuthVariable grafanaAuthService grafanaAuthPort}
internal;
proxy_pass_request_body off;
proxy_set_header Content-Length "";
@ -529,241 +685,14 @@ in
};
};
# The agents' check on `/select/logsql/`. On the host rather than in the
# store's container: it needs nothing of the store, only nginx's reach to
# its socket and its own store identity.
users.users.${logsAuthUnit} = {
isSystemUser = true;
group = logsAuthUnit;
description = "swarm log store auth_request responder";
};
users.groups.${logsAuthUnit} = { };
# The store's volume is its old container's data directory, which a host
# that never ran the container does not have. The rule leaves an existing
# directory's owner and mode alone: the pod's group is given the tree when
# it starts.
systemd.tmpfiles.rules = [ "d ${hostDataDir} - - - -" ];
systemd.services.${logsAuthUnit} = {
description = "swarm log store auth_request responder for agent credentials";
wantedBy = [ "multi-user.target" ];
# Where the store's PKI is minted on this host, the leaf is one of its
# files. Ordering only: elsewhere the unit does not exist.
after = [
"network.target"
"swarm-bao-pki.service"
];
serviceConfig = {
ExecStart = lib.concatStringsSep " " [
"${deployCfg.victorialogs.authPackage}/bin/swarm-logs-auth"
"--socket ${logsAuthSocket}"
# The role ./swarm-bao.nix writes on the store's `cert` mount.
"--store-cert-role swarm-logs-auth"
"--surface logs"
"--verdict-ttl ${toString deployCfg.victorialogs.authVerdictTtl}"
];
# Paths only: `argv` is world-readable via /proc/<pid>/cmdline.
LoadCredential = lib.mapAttrsToList (id: path: "${id}:${path}") logsAuthStoreFiles;
# ⚠️ A static user, never `DynamicUser`: with `RuntimeDirectoryPreserve`
# systemd puts a dynamic user's runtime directory under
# `/run/private/` (0700 root:root), which nginx cannot traverse.
User = logsAuthUnit;
Group = logsAuthUnit;
RuntimeDirectory = logsAuthUnit;
# Traverse-only for others, so nginx reaches the socket path.
RuntimeDirectoryMode = "0751";
# The path never vanishes from under a running nginx; the responder
# unlinks a stale socket as it starts.
RuntimeDirectoryPreserve = "yes";
Restart = "on-failure";
RestartSec = "5s";
SyslogIdentifier = logsAuthUnit;
ProtectSystem = "strict";
ProtectHome = true;
PrivateTmp = "disconnected";
PrivateDevices = true;
NoNewPrivileges = true;
RestrictSUIDSGID = true;
RemoveIPC = true;
};
environment = {
BAO_ADDR = "https://${baoCfg.domain}:${toString baoCfg.port}";
BAO_CLIENT_CERT = logsAuthCredential "bao-client.pem";
BAO_CLIENT_KEY = logsAuthCredential "bao-client-key.pem";
}
// lib.optionalAttrs (logsAuthStoreFiles ? "bao-ca.pem") {
BAO_CACERT = logsAuthCredential "bao-ca.pem";
};
};
# Grafana's check on `/select/logsql/`: the metrics store's responder
# binary, pointed at the bearer Grafana's datasources share.
users.users.${grafanaAuthUnit} = {
isSystemUser = true;
group = grafanaAuthUnit;
description = "swarm log store auth_request responder for Grafana's bearer";
};
users.groups.${grafanaAuthUnit} = { };
systemd.services.${grafanaAuthUnit} = {
description = "swarm log store auth_request responder for Grafana's bearer";
wantedBy = [ "multi-user.target" ];
after = [
"network.target"
"swarm-bao-pki.service"
];
serviceConfig = {
ExecStart = lib.concatStringsSep " " [
"${deployCfg.victorialogs.grafanaAuthPackage}/bin/swarm-metrics-auth"
"--socket ${grafanaAuthSocket}"
"--store-cert-role swarm-logs-auth"
"--store-path ${grafanaBearerStorePath}"
];
LoadCredential = lib.mapAttrsToList (id: path: "${id}:${path}") logsAuthStoreFiles;
# ⚠️ A static user, never `DynamicUser`: see the `swarm-logs-auth` unit above.
User = grafanaAuthUnit;
Group = grafanaAuthUnit;
RuntimeDirectory = grafanaAuthUnit;
RuntimeDirectoryMode = "0751";
RuntimeDirectoryPreserve = "yes";
Restart = "on-failure";
RestartSec = "5s";
SyslogIdentifier = grafanaAuthUnit;
ProtectSystem = "strict";
ProtectHome = true;
PrivateTmp = "disconnected";
PrivateDevices = true;
NoNewPrivileges = true;
RestrictSUIDSGID = true;
RemoveIPC = true;
};
environment = {
BAO_ADDR = "https://${baoCfg.domain}:${toString baoCfg.port}";
BAO_CLIENT_CERT = grafanaAuthCredential "bao-client.pem";
BAO_CLIENT_KEY = grafanaAuthCredential "bao-client-key.pem";
}
// lib.optionalAttrs (logsAuthStoreFiles ? "bao-ca.pem") {
BAO_CACERT = grafanaAuthCredential "bao-ca.pem";
};
};
# The socket directory is the gateway's way in: its group is nginx's.
systemd.tmpfiles.rules = [ "d ${socketDir} 0770 root ${toString nginxGid} - -" ];
# The hive bridge carries the container's DHCP lease and its resolver.
# The pods reach the secret store through the hive bridge.
services.hyperhive.network.enable = lib.mkDefault true;
containers.${cfg.machine} = {
autoStart = true;
ephemeral = false;
# No `--link-journal=host`: the journal stays in the guest, where the
# container's own forwarder reads it (../container-modules/swarm-journal-forwarder.nix).
extraFlags = lib.mapAttrsToList (
id: source: "--load-credential=${id}:${source}"
) forwarderStoreFiles;
inherit privateNetwork;
hostBridge = networkCfg.bridgeName;
# A bind mount, not a path both sides know: a container's `/run` is an
# nspawn tmpfs the host cannot see into. Connecting to a socket is a
# write to it.
bindMounts = {
${socketDir} = {
hostPath = socketDir;
isReadOnly = false;
};
}
// caTrust.bindMount;
config =
{ pkgs, ... }:
{
imports = [
../container-modules/swarm-container.nix
../container-modules/swarm-journal-forwarder.nix
(import ../container-modules/swarm-container-resolver.nix {
inherit (networkCfg) bridgeIp;
# The forwarder and its secret fetch dial the swarm collector,
# authelia and the store by name too.
dnsConsumers = [
"victorialogs.service"
"opentelemetry-collector.service"
"${forwarderUnit}.service"
];
})
# Go: `SSL_CERT_FILE` replaces its trust store, for the swarm
# collector's and authelia's names.
(caTrust.trustBundle {
inherit pkgs;
name = cfg.machine;
consumers = [ "opentelemetry-collector" ];
})
];
services.hyperhive.swarmContainer = { inherit privateNetwork; };
# The bridge address comes from the gateway's DHCP. `swarm-bridge-dns`
# owns resolv.conf, so dhcpcd must not write it over that unit.
networking.interfaces.eth0.useDHCP = true;
networking.dhcpcd.extraConfig = "nohook resolv.conf";
# The socket's group is the store's primary group, so that group is
# nginx's gid. A static user, not nixpkgs' DynamicUser: a dynamic
# user's group is allocated per start, and nginx is never in it.
users.groups.${socketGroup}.gid = nginxGid;
users.users.victorialogs = {
isSystemUser = true;
group = socketGroup;
};
systemd.services.victorialogs = {
serviceConfig = {
DynamicUser = lib.mkForce false;
User = "victorialogs";
Group = socketGroup;
# The store creates its socket under the process umask, so `0007`
# makes it `0770` and nginx's group can connect.
UMask = "0007";
};
# nixpkgs' readiness loop curls a TCP URL, which no `unix:` address
# answers.
postStart = lib.mkForce ''
until ${lib.getExe pkgs.curl} -s -o /dev/null --unix-socket ${socketPath} http://localhost/ping; do
sleep 1;
done
'';
};
# Authenticated as the forwarder's own OIDC client, with the
# responder's store identity: one identity for the whole container.
# It is a system credential, so the fetch unit loads it.
services.hyperhive.swarmJournalForwarder = {
enable = true;
serviceName = "victorialogs";
endpoint = forwarderEndpoint;
clientId = forwarderClientId;
tokenUrl = "${toString hyperhiveCfg.swarm.authelia.url}/api/oidc/token";
telemetryPort = forwarderTelemetryPort;
store = {
package = deployCfg.bao.package;
addr = "https://${baoCfg.domain}:${toString baoCfg.port}";
secretPath = "secret/swarm/services/${forwarderClientId}/oidc/client";
clientCertFile = forwarderCredential "bao-client.pem";
clientKeyFile = forwarderCredential "bao-client-key.pem";
caFile = if forwarderStoreFiles ? "bao-ca.pem" then forwarderCredential "bao-ca.pem" else null;
};
};
systemd.services.${forwarderUnit}.serviceConfig.LoadCredential = lib.attrNames forwarderStoreFiles;
services.victorialogs = {
enable = true;
package = deployCfg.victorialogs.package;
# ⚠️ A SOCKET, not upstream's default of every interface: this
# endpoint accepts writes as well as reads. Nothing authenticates it
# either — upstream offers one basic-auth pair
# (`-httpAuth.username` / `-httpAuth.password`) and this module sets
# neither. The socket's directory mode is the boundary: only the
# gateway's group can connect.
listenAddress = "unix:${socketPath}";
extraOptions = [ "-retentionPeriod=${deployCfg.victorialogs.retentionPeriod}" ];
};
};
};
};
# 🔑 OTLP ingest is served at `/insert/opentelemetry/v1/logs`, measured
@ -780,7 +709,7 @@ in
# code is not evidence.
#
# ⚠️ Like the metrics store's, that endpoint is unauthenticated — which is
# why `listenAddress` above is a socket and why nothing reaches it except
# through the gateway, where the ingest route is authenticated. (This module
# declares a vhost.)
# why the Service's policy admits only the node and why nothing reaches it
# except through the gateway, where the ingest route is authenticated. (This
# module declares a vhost.)
}

View file

@ -133,7 +133,7 @@ let
# The `auth_request` responder for Grafana's bearer (`swarm-metrics-auth`).
# Its socket's directory holds that socket alone and is traverse-only for
# others, the shape `swarm-logs-auth` in ./swarm-victorialogs.nix has.
# others.
metricsAuthUnit = "swarm-metrics-auth";
metricsAuthSocket = "/run/${metricsAuthUnit}/auth.sock";
metricsAuthCredential = id: "/run/credentials/${metricsAuthUnit}.service/${id}";
@ -152,8 +152,7 @@ let
# The agents' check on the read API: a `swarm-logs-auth` binary, logging in
# under this host's `swarm-metrics-auth` leaf, whose grant covers every
# agent's queue secret. The log store's host runs `swarm-metrics-auth` under
# its `swarm-logs-auth` leaf the same way.
# agent's queue secret.
agentAuthUnit = "swarm-metrics-agent-auth";
agentAuthSocket = "/run/${agentAuthUnit}/auth.sock";
agentAuthCredential = id: "/run/credentials/${agentAuthUnit}.service/${id}";