Watch
0
0
Fork
You've already forked hyperhive
0
hyperhive/nix/host-modules/swarm-grafana.nix
atlas f8fb71253e let the init container's temp file take its umask
fetch-secrets ran under umask 0227 for the files it writes, which made the
mktemp file of grafana_secret_key mode 0400: the redirect of bao's stderr
into it failed, every bao call in the helper answered 1, and the init
container exited 1 before it stored or read the key. The umask now covers
only the writes of put(), the helper chmods its own file, the script test runs
under that umask, and a pod that does not start prints its init containers'
logs.
2026-11-28 10:01:39 +01:00

1564 lines
69 KiB
Nix
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# The swarm's metrics UI: one Grafana for the whole swarm, a pod in the host's
# cluster (./k8s/render.nix, docs/4-implementation/k8s/runtime.md), reading the
# VictoriaMetrics and VictoriaLogs stores through the gateway.
#
# Dashboards, datasources and alert rules are provisioned from this repo and
# baked into the pod's image, deliberately not created in the UI: the store path
# is immutable, so Grafana is told not to accept UI edits it would lose on the
# next rebuild.
{
pkgs,
lib,
config,
...
}:
let
cfg = config.services.hyperhive.swarm.grafana;
deployCfg = config.services.hyperhive.deploy;
networkCfg = config.services.hyperhive.network;
hyperhiveCfg = config.services.hyperhive;
gatewayCfg = hyperhiveCfg.gateway;
autheliaDomain = hyperhiveCfg.swarm.authelia.domain;
baoCfg = hyperhiveCfg.swarm.bao;
baoDeploy = deployCfg.bao;
caTrust = import ./lib/hive-ca-trust.nix {
inherit lib gatewayCfg;
tlsCfg = deployCfg.hive-controller.tls;
};
# Spelled ONCE. The provisioned datasource declares it and every panel in the
# provisioned dashboards references it; a second literal would be free to
# drift, and the failure is a dashboard that renders with empty panels rather
# than an error.
datasourceUid = "swarm-victoriametrics";
# The logs store's own uid. Separate from the metrics one and spelled once for
# the same reason: a dashboard panel names it, and a second literal would be
# free to drift into a panel that renders empty rather than erroring.
logsDatasourceUid = "swarm-victorialogs";
# Which field carries the log level, told to the READER because the writer
# cannot be told: VictoriaLogs' OTLP ingester names the stored field
# `severity_text` unconditionally, with no option to rename it, but
# Grafana's log-level buttons filter on a field called `level`. So the
# mapping is made here, one `logLevelRules` entry per level below.
#
# 🔑 A rule wrong in any of three ways provisions cleanly and its level
# button silently returns zero rows — `enabled` must be literally `true`,
# `level` must be a canonical Grafana `LogLevel` (not an alias like `warn`
# or `fatal`), and `value` must match ../journald-severity.nix's uppercase
# STORED text, not its lowercase keys. `Unspecified` is deliberately left
# unmapped so the "no severity" panel keeps counting it. Full walkthrough
# (why each rule shape is what it is, the query a level button actually
# emits): docs/4-implementation/scheduler/observability.md#why-explores-level-buttons-need-the-datasource-told
logLevelRules =
let
fromSeverityText = value: level: {
field = "severity_text";
operator = "equals";
enabled = true;
inherit value level;
};
in
[
(fromSeverityText "FATAL" "critical")
(fromSeverityText "ERROR" "error")
(fromSeverityText "WARN" "warning")
(fromSeverityText "INFO" "info")
(fromSeverityText "DEBUG" "debug")
(fromSeverityText "TRACE" "trace")
];
# An alert rule that fires while a LogsQL stats query counts more than zero
# lines. `expr` carries its own `_time:` window, so the count covers exactly
# that span; `relativeTimeRange` matches it so the rule editor's preview
# queries the same span.
#
# No lines is the healthy state, so no data is `OK`. A query that fails is
# `Error`, which the rule list shows separately from both.
logCountRule =
{
uid,
title,
windowSeconds,
expr,
for,
summary,
}:
{
inherit uid title for;
condition = "C";
data = [
{
refId = "A";
relativeTimeRange = {
from = windowSeconds;
to = 0;
};
datasourceUid = logsDatasourceUid;
model = {
refId = "A";
datasource = {
type = "victoriametrics-logs-datasource";
uid = logsDatasourceUid;
};
queryType = "stats";
inherit expr;
};
}
{
refId = "B";
datasourceUid = "__expr__";
model = {
refId = "B";
type = "reduce";
expression = "A";
reducer = "last";
};
}
{
refId = "C";
datasourceUid = "__expr__";
model = {
refId = "C";
type = "threshold";
expression = "B";
conditions = [
{
evaluator = {
type = "gt";
params = [ 0 ];
};
}
];
};
}
];
noDataState = "OK";
execErrState = "Error";
annotations = { inherit summary; };
};
# An alert rule that fires while a metric query's latest value is above
# `threshold`. `expr` is an instant MetricsQL query; names with dots are
# selected as `{__name__="a.b"}`, the way the dashboards do.
#
# No data is `OK`: a series that is absent means the condition is not
# raised (hive-c0re stops reporting a warning once it clears), and a hive
# that stopped exporting at all is the log-absence rules' job.
metricThresholdRule =
{
uid,
title,
windowSeconds ? 600,
expr,
threshold,
for,
summary,
}:
{
inherit uid title for;
condition = "C";
data = [
{
refId = "A";
relativeTimeRange = {
from = windowSeconds;
to = 0;
};
inherit datasourceUid;
model = {
refId = "A";
datasource = {
type = "prometheus";
uid = datasourceUid;
};
inherit expr;
instant = true;
range = false;
};
}
{
refId = "B";
datasourceUid = "__expr__";
model = {
refId = "B";
type = "reduce";
expression = "A";
reducer = "last";
};
}
{
refId = "C";
datasourceUid = "__expr__";
model = {
refId = "C";
type = "threshold";
expression = "B";
conditions = [
{
evaluator = {
type = "gt";
params = [ threshold ];
};
}
];
};
}
];
noDataState = "OK";
execErrState = "Error";
annotations = { inherit summary; };
};
# `logCountRule` inverted: fires while the count is below one. `expr` must
# be an ungrouped `stats count()`, which answers 0 rather than no row when
# nothing matched; a grouped count drops the group instead, and a dropped
# instance resolves rather than fires. No data is `Alerting` so a query
# that returns nothing at all still fires.
logAbsenceRule =
args:
let
rule = logCountRule args;
in
rule
// {
data = map (
query:
if query.refId == "C" then
lib.recursiveUpdate query {
model.conditions = [
{
evaluator = {
type = "lt";
params = [ 1 ];
};
}
];
}
else
query
) rule.data;
noDataState = "Alerting";
};
# The shipped dashboards carry `@datasourceUid@` / `@logsDatasourceUid@` where
# a real deployment needs the uids above. They are substituted here rather
# than committed with the literals so the single binding stays single.
renderDashboard =
name:
pkgs.writeText name (
builtins.replaceStrings
[ "@datasourceUid@" "@logsDatasourceUid@" ]
[ datasourceUid logsDatasourceUid ]
(builtins.readFile (./swarm-grafana/dashboards + "/${name}"))
);
# Grafana's file provider wants a DIRECTORY to scan, so the rendered files are
# collected into one.
dashboardDir = pkgs.linkFarm "hyperhive-grafana-dashboards" (
map
(name: {
inherit name;
path = renderDashboard name;
})
[
"agents.json"
"archive.json"
"attic.json"
"authelia.json"
"bao.json"
"builder.json"
"builds.json"
"ci-runner.json"
"claude-usage.json"
"collector.json"
"controller.json"
"egress.json"
"forge.json"
"gateway.json"
"grafana.json"
"host.json"
"logstore.json"
"matrix.json"
"metricstore.json"
"notify-router.json"
"queue.json"
"review-classifier.json"
"stt.json"
]
);
# A reader of the store is defined by holding a certificate the store
# accepts, never by standing next to it — the rule ./swarm-bao.nix's
# `deploy.bao` options block states in full.
#
# Also asserted rather than gating anything, and that is the ruling this
# module's second delivery route was deleted under: the store exists so that
# ONE secret is placed out of band per host — this certificate — and every
# other secret is read with it. A Grafana host without it has not been given
# its identity yet, which is a thing to say out loud rather than to route
# around by reaching into authelia's tree whenever it happens to be local.
#
# 🩸 Grafana's OWN leaf, not `clientCertFile` — the hive's. Bao matches a
# cert-auth role on the CN, so one leaf shared by four readers would be ONE
# principal holding the union of four grants: this unit could read every
# agent credential in the swarm, when what it needs is the one path
# `storeSecretPath` names.
haveClientIdentity =
baoDeploy.grafanaOidcClientCertFile != null && baoDeploy.grafanaOidcClientKeyFile != null;
autheliaUrl = toString hyperhiveCfg.swarm.authelia.url;
k8sCfg = hyperhiveCfg.k8s;
labels = import ./k8s/labels.nix;
inherit (import ../images { inherit pkgs lib; }) mkServiceImage;
storeAuth = import ./lib/store-auth.nix;
podAuth = import ./lib/bao-pod-auth.nix;
# The workload, as the cluster names it. Its Service has the name, which the
# gateway dials. The pod runs under the ServiceAccount of that name and logs
# in to the secret store with the role the certificate's holds
# (`grafanaOidcReaders` in ./swarm-bao-readers.nix).
service = "swarm-grafana";
oidcRole = "swarm-grafana-oidc";
grafanaPort = 3000;
dataDir = "/var/lib/grafana";
hostDataDir = "/var/lib/nixos-containers/swarm-grafana${dataDir}";
credDir = "/run/credentials/${service}.service";
serviceHost = name: "${name}.${k8sCfg.namespace}.svc.${deployCfg.k8s.clusterDomain}";
# What a location needs to dial the 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 (./swarm-victoriametrics.nix says why).
grafanaVariable = "$swarm_grafana_upstream";
viaGrafana = ''
resolver ${networkCfg.bridgeIp} valid=10s ipv6=off;
set ${grafanaVariable} ${serviceHost service}:${toString grafanaPort};
'';
# The secrets land in the pod's in-memory runtime directory: the init
# container writes them before Grafana starts, and none reaches a disk. Each
# file is absent until the init container has run, and Grafana does not
# start without them: `$__file{}` on a missing path is a startup error, and an
# empty admin password would fall back to the upstream default. They are
# read once, at start (docs/4-implementation/k8s/runtime.md says what a
# rotation needs).
#
# Spelled once: the script that writes a file and the config that names it
# are a few hundred lines apart, and a Grafana reading a path nothing writes
# is a login that fails with nothing in any log about the file.
secretDirName = "grafana-secrets";
secretDir = "/run/${secretDirName}";
secretPath = "${secretDir}/${cfg.oidc.clientId}.secret";
# Where authelia's mint, in its container, stores this client's secret. A
# swarm service's client is registered once for the whole swarm, so its
# secret is one value and not one per hive. Both ends compose this from the
# same swarm-wide client id, so a rename cannot leave one of them behind.
#
# ⚠️ The prefix is not decoration: it is what the role's grant covers, so a
# path outside it answers 403 rather than a miss, however correct it looks.
storeSecretPath = "secret/swarm/services/${cfg.oidc.clientId}/oidc/client";
# Grafana's datasource-encryption key. Stored once in the store by the init
# container, which `swarm-bao-readers.nix`'s `grafanaOidcReaders` grants create
# and read on this one leaf. It wraps the data keys of Grafana's database, and
# rotating it does not re-encrypt them, so a different key leaves Grafana
# unable to read what the first one encrypted: the order of what the init
# container stores is in ./lib/grafana-secret-key.nix.
secretKeyStorePath = "secret/swarm/services/${cfg.oidc.clientId}/secret-key";
secretKeyPath = "${secretDir}/secret-key";
# The key an earlier release generated in the container, as the host sees it:
# the seed for an empty leaf. Once every host's leaf is filled it has no
# reader, and this volume, the helper's seed branch and the mount go with it. It sits beside the data directory, so the pod
# reads it through a volume of its own, read-only and in the init container
# only (the namespace's Pod Security level refuses a `hostPath`).
legacyKeyDir = "/var/lib/nixos-containers/swarm-grafana/var/lib/grafana-secret";
legacyKeyClaim = "${service}-legacy-key";
legacyKeyMount = "/legacy-secret-key";
databasePath = "${dataDir}/grafana.db";
grafanaSecretKey = import ./lib/grafana-secret-key.nix { };
# The built-in `admin` account's password. Grafana's API takes basic auth
# whatever the login form says, so this account is reachable from the public
# vhost and its password cannot be the upstream default. Created once in the
# store by the init container, under the same grant as the key.
adminPasswordStorePath = "secret/swarm/services/${cfg.oidc.clientId}/admin/password";
adminPasswordPath = "${secretDir}/admin-password";
# The bearer the datasources present at the stores' query APIs through the
# gateway, which the stores' Grafana responders check against the same store
# path (`swarm-metrics-grafana-auth` and `swarm-logs-grafana-auth`). Created
# once by the init container, under the same grant. The file holds the whole
# header value, `Bearer <value>`: nixpkgs accepts a `secureJsonData` entry
# only when it is exactly one `$__file{}`.
metricsBearerStorePath = "secret/swarm/services/${cfg.oidc.clientId}/metrics/bearer";
metricsBearerPath = "${secretDir}/metrics-bearer";
# swarm-controller's token for Grafana's API, minted by the sidecar for a
# Viewer service account of this name. `controllerGrafanaTokenLeaf` in
# ./swarm-bao.nix is the nix half of the path,
# `swarm_secret_client::grafana::controller_token_path` the Rust half.
controllerAccountName = "swarm-controller";
controllerTokenStorePath = "secret/swarm/controller/swarm-controller/grafana/token";
pluginDir = pkgs.linkFarm "grafana-plugins" (
map (pkg: {
name = pkg.pname;
path = pkg;
}) deployCfg.grafana.plugins
);
# The provisioning directory upstream's module builds, as a link farm: the
# same three kinds of file in the same places.
yaml = pkgs.formats.yaml { };
provisioningDir = pkgs.linkFarm "grafana-provisioning" [
{
name = "datasources/datasource.yaml";
path = yaml.generate "datasource.yaml" grafana.provision.datasources.settings;
}
{
name = "dashboards/dashboard.yaml";
path = yaml.generate "dashboard.yaml" grafana.provision.dashboards.settings;
}
{
name = "alerting/rules.yaml";
path = yaml.generate "rules.yaml" grafana.provision.alerting.rules.settings;
}
];
# The ini file as nixpkgs' module renders it.
settingsFormat = pkgs.formats.ini {
listToValue = lib.concatMapStringsSep " " (lib.generators.mkValueStringDefault { });
mkKeyValue = lib.generators.mkKeyValueDefault {
mkValueString = v: if v == null then "" else lib.generators.mkValueStringDefault { } v;
} "=";
};
configFile = settingsFormat.generate "config.ini" grafana.settings;
homePath = "${deployCfg.grafana.package}/share/grafana";
# What the pod runs: the admin password is applied to the database before the
# server listens, because the setting gives only a newly created database
# its password and a database created earlier keeps the one it was created
# with. `grafana cli` opens the database the server opens, which the same
# config names.
start = pkgs.writeShellScriptBin service ''
set -euo pipefail
grafana=${lib.getExe' deployCfg.grafana.package "grafana"}
"$grafana" cli --homepath ${homePath} --config ${configFile} \
admin reset-admin-password --password-from-stdin < ${adminPasswordPath}
exec "$grafana" server --homepath ${homePath} --config ${configFile}
'';
# Everything the init container and the sidecar need to speak to the store
# and Grafana's API. The store's `bao` is the one client both scripts use.
tools = [
baoDeploy.package
pkgs.coreutils
pkgs.curl
pkgs.gnugrep
pkgs.jq
pkgs.openssl
pkgs.sqlite
];
# Logs in with the pod's ServiceAccount token, under the role the pod's
# environment names (`BAO_JWT_*`, from ./k8s/render.nix).
login = ''
BAO_TOKEN="$(bao write -field=token "auth/$BAO_JWT_MOUNT/login" role="$BAO_JWT_ROLE" jwt="@$BAO_JWT_FILE")"
export BAO_TOKEN
'';
# The init container: Grafana's secrets, from the store. The store's value
# wins and a leaf that holds none is created, so the first value stored is
# the one every later start reads (`-cas=0` never replaces one, and a lost
# race reads the winner's back).
fetch = pkgs.writeShellScriptBin "swarm-grafana-fetch" ''
export PATH=${lib.makeBinPath tools}
set -euo pipefail
${login}
${grafanaSecretKey}
d=${lib.escapeShellArg secretDir}
put() {
# Group-readable (0440): the pod's group is how Grafana reads what the init
# container, running as another uid, wrote. Only the writes take the umask:
# a temporary file made under it could not be written to again.
( umask 0227; printf '%s' "$2" > "$d/$1.new" )
mv -f "$d/$1.new" "$d/$1"
}
stored() {
bao kv get -field=value "$1" 2>/dev/null || true
}
seeded() {
local value
value="$(stored "$1")"
if [ -z "$value" ]; then
openssl rand -hex 32 | tr -d '\n' | bao kv put -cas=0 "$1" value=- >/dev/null 2>&1 || true
value="$(stored "$1")"
fi
if [ -z "$value" ]; then
echo "swarm-bao holds nothing at $1 and took no value; Grafana does not start without it." >&2
exit 1
fi
printf '%s' "$value"
}
oidc="$(stored ${lib.escapeShellArg storeSecretPath})"
if [ -z "$oidc" ]; then
echo "swarm-bao holds nothing at ${storeSecretPath}; Grafana has no OIDC client secret yet." >&2
exit 1
fi
# Each value is read into a variable first: an `exit` inside a command
# substitution in an argument ends only the substitution, and `put` would
# write an empty file.
put ${lib.escapeShellArg "${cfg.oidc.clientId}.secret"} "$oidc"
admin="$(seeded ${lib.escapeShellArg adminPasswordStorePath})"
put admin-password "$admin"
bearer="$(seeded ${lib.escapeShellArg metricsBearerStorePath})"
put metrics-bearer "Bearer $bearer"
grafana_secret_key ${lib.escapeShellArg secretKeyStorePath} ${lib.escapeShellArg "${legacyKeyMount}/secret_key"} ${lib.escapeShellArg databasePath} openssl rand -hex 32 || exit 1
put secret-key "$GRAFANA_KEY"
echo "Grafana's secrets are in $d"
'';
# The sidecar: keeps swarm-controller's Viewer service account and its token.
# Every pass checks the stored token with the call the controller makes with
# it, and replaces it when Grafana refuses it, as it does after its database
# is recreated. Grafana's API takes the admin password the init container
# wrote, on the pod's loopback.
controllerToken = pkgs.writeShellScriptBin "swarm-grafana-controller-token" ''
export PATH=${lib.makeBinPath tools}
set -uo pipefail
base=http://127.0.0.1:${toString grafanaPort}
body="$(mktemp)"
grafana() {
local auth="$1" method="$2" path="$3"
shift 3
curl --silent --show-error --connect-timeout 5 --max-time 15 \
-H @<(printf 'Authorization: %s\n' "$auth") \
-H 'Content-Type: application/json' \
-X "$method" -o "$body" -w '%{http_code}' "$@" \
"$base$path"
}
expect() {
local what="$1" status="$2"
shift 2
for ok in "$@"; do
[ "$status" = "$ok" ] && return 0
done
echo "Grafana answered $status to $what:" >&2
cat "$body" >&2
return 1
}
pass() {
local admin status account id stored key token_id
admin="Basic $(printf 'admin:%s' "$(< ${lib.escapeShellArg adminPasswordPath})" | base64 -w0)"
status="$(grafana "$admin" GET '/api/serviceaccounts/search?perpage=1000&query=${controllerAccountName}')"
expect "the service account search" "$status" 200 || return 1
account="$(jq -c --arg n ${controllerAccountName} '[.serviceAccounts[] | select(.name == $n)][0] // empty' "$body")"
if [ -z "$account" ]; then
status="$(grafana "$admin" POST /api/serviceaccounts \
--data '{"name":"${controllerAccountName}","role":"Viewer","isDisabled":false}')"
expect "creating the ${controllerAccountName} service account" "$status" 200 201 || return 1
account="$(jq -c . "$body")"
echo "created the ${controllerAccountName} service account as a Viewer"
fi
id="$(jq -r .id <<<"$account")"
if [ "$(jq -r '"\(.role) \(.isDisabled // false)"' <<<"$account")" != "Viewer false" ]; then
status="$(grafana "$admin" PATCH "/api/serviceaccounts/$id" \
--data '{"role":"Viewer","isDisabled":false}')"
expect "setting the ${controllerAccountName} service account to an enabled Viewer" "$status" 200 || return 1
echo "set the ${controllerAccountName} service account back to an enabled Viewer"
fi
${login}
stored="$(bao kv get -field=value ${lib.escapeShellArg controllerTokenStorePath} 2>/dev/null || true)"
if [ -n "$stored" ]; then
status="$(grafana "Bearer $stored" GET /api/prometheus/grafana/api/v1/alerts)"
case "$status" in
200) return 0 ;;
401) echo "Grafana refuses the stored token for ${controllerAccountName}; replacing it." ;;
*) expect "reading alerts with the stored token" "$status" 200 || return 1 ;;
esac
fi
status="$(grafana "$admin" GET "/api/serviceaccounts/$id/tokens")"
expect "listing the ${controllerAccountName} tokens" "$status" 200 || return 1
for token_id in $(jq -r '.[].id' "$body"); do
status="$(grafana "$admin" DELETE "/api/serviceaccounts/$id/tokens/$token_id")"
expect "deleting token $token_id of ${controllerAccountName}" "$status" 200 || return 1
done
status="$(grafana "$admin" POST "/api/serviceaccounts/$id/tokens" \
--data "{\"name\":\"${controllerAccountName}-$(date +%s)\"}")"
expect "minting a ${controllerAccountName} token" "$status" 200 || return 1
key="$(jq -r .key "$body")"
: >"$body"
if ! printf '%s' "$key" | bao kv put ${lib.escapeShellArg controllerTokenStorePath} value=- >/dev/null; then
echo "could not store the new ${controllerAccountName} token at ${controllerTokenStorePath}; the next pass replaces it." >&2
return 1
fi
echo "stored a new ${controllerAccountName} token at ${controllerTokenStorePath}"
}
while true; do
if curl --silent --fail --output /dev/null --connect-timeout 5 --max-time 15 "$base/api/health"; then
pass || echo "the pass failed; the next one retries." >&2
sleep 300
else
sleep 5
fi
done
'';
setupImage = mkServiceImage {
name = "${service}-setup";
package = pkgs.symlinkJoin {
name = "${service}-setup";
paths = [
fetch
controllerToken
];
};
bin = "swarm-grafana-fetch";
};
# Upstream's `services.grafana` options, as plain data: what the pod's
# config file, provisioning and plugins are rendered from (above).
grafana = {
package = deployCfg.grafana.package;
# Passed through unconditionally, empty default included.
# Upstream distinguishes `null` from `[ ]`, and both differences
# favour always handing it a list:
#
# - `null` points the plugin path at grafana's mutable
# `<dataDir>/plugins`; any list points it at a store path.
# Switching on the day someone adds their first plugin would
# bury that change inside an unrelated one.
# - upstream defaults its plugin update-check to
# `declarativePlugins == null`, so a list also stops the
# pod phoning grafana.com. That is the no-runtime-egress
# property this option exists for — it should not arrive only
# once a plugin happens to be listed.
#
# - 🩸 it also sets upstream's `plugins.preinstall_disabled`
# (nixpkgs'
# grafana.nix defaults it to `declarativePlugins != null`,
# saying preinstall "causes issues with declarativePlugins").
# Preinstall is what fetches the Drilldown apps on first
# start, so claiming this directory silently removes them.
# That is why the option's default is not empty.
#
# Taking this directory over is not harmless on a hive with no
# plugins: that reasoning covers only plugins a PERSON installs,
# and upstream installs some itself.
declarativePlugins = deployCfg.grafana.plugins;
settings = {
server = {
# TCP, for the gateway on the node: the pod's Service reaches
# this port and the namespace's policy admits only the node to
# it. Grafana's own login (SSO, or basic auth on the API) is
# the credential of every route but `/api/health`, `/healthz`
# and `/metrics`, which `metrics.basic_auth_*` below gates.
protocol = "http";
http_addr = "0.0.0.0";
http_port = grafanaPort;
domain = cfg.domain;
# Grafana builds its own OAuth redirect from this. Left at
# upstream's `%(protocol)s://%(domain)s:%(http_port)s/` it
# would name `http://<domain>:3000/`, which authelia has
# never heard of.
root_url = "https://${cfg.domain}/";
};
paths = {
data = dataDir;
plugins = pluginDir;
provisioning = provisioningDir;
};
# Pod logs are the container's output: the host collector reads
# them from the node.
log.mode = "console";
analytics = {
reporting_enabled = false;
check_for_updates = false;
# The plugin directory is the store's, so nothing checks for updates.
check_for_plugin_updates = false;
};
# Stated rather than inherited. This is upstream's default, but
# a scrape target now depends on it, and a default that changes
# silently takes the target with it — the endpoint disappears,
# nginx keeps answering, and the scrape fails with a 404 far
# from anything that mentions Grafana.
#
# The endpoint answers anyone who reaches the port, so it takes the
# login every store takes (`swarm-store` and the password the
# unit publishes as the Secret the pod loads): the vhost sends it
# after authelia has admitted the collector. Both keys are read at
# start by Grafana's settings (`MetricsEndpointBasicAuthUsername`
# and `...Password`, in `pkg/setting/setting.go`).
metrics = {
enabled = true;
basic_auth_username = storeAuth.user;
basic_auth_password = "$__file{${credDir}/${storeAuth.credentialId}}";
};
# Grafana hands an external backend plugin only an allow-list of
# its environment (the proxy variables), so without this the logs
# datasource never sees the unit's `SSL_CERT_FILE` and rejects the
# log store's certificate as `x509: unknown authority`. The value
# is plugin ids, not variable names: each listed plugin gets the
# whole environment.
plugins = {
forward_host_env_vars = "victoriametrics-logs-datasource";
preinstall_disabled = true;
};
users.auto_assign_org_role = cfg.oidc.role;
# ⚠️ `$__file{}`, and required rather than optional: nixpkgs
# dropped the default and asserts on null, so without this the
# whole host fails to build. Written by the init container.
security.secret_key = "$__file{${secretKeyPath}}";
# The password a newly created database gets; the start script
# gives an existing one the same. Written by the init container.
security.admin_password = "$__file{${adminPasswordPath}}";
# No password box on the public login page: people log in through
# SSO. This hides the form only; the API still takes basic auth,
# which is why the admin password above is minted.
#
# Not conditional on anything, and the block below is not
# either, which is what keeps the two from ever disagreeing.
# Whether a password box sits on a public login page cannot
# depend on which host happens to run authelia.
auth.disable_login_form = true;
# Emitted in every deployment, because SSO is a requirement of
# running this service rather than a feature of some topologies:
# the assertions above refuse to build a Grafana that lacks an
# IdP to point at or the identity to fetch its secret with. A
# `lib.optionalAttrs` here would be the silent half of that pair,
# dropping the only login this pod has whenever a value
# went null.
"auth.generic_oauth" = {
enabled = true;
name = "HyperHive";
client_id = cfg.oidc.clientId;
# ⚠️ `$__file{}`, never the secret itself — anything else
# here is world-readable in the nix store. Note the module's
# own leak assertion does NOT cover this key (it checks
# `database.password`, `security.admin_password` and
# datasource `secureJsonData`), so nothing but this comment
# stands between a literal and the store.
#
# The init container `fetch-secrets` writes this path before
# Grafana starts.
client_secret = "$__file{${secretPath}}";
scopes = "openid profile email groups";
auth_url = "${autheliaUrl}/api/oidc/authorization";
token_url = "${autheliaUrl}/api/oidc/token";
api_url = "${autheliaUrl}/api/oidc/userinfo";
use_pkce = true;
};
};
provision.datasources.settings = {
apiVersion = 1;
datasources = [
{
name = "VictoriaMetrics";
type = "prometheus";
uid = datasourceUid;
url = deployCfg.grafana.datasourceUrl;
access = "proxy";
isDefault = true;
# The store's query routes admit this bearer or an operator's
# session, and nothing else.
jsonData.httpHeaderName1 = "Authorization";
secureJsonData.httpHeaderValue1 = "$__file{${metricsBearerPath}}";
}
{
name = "VictoriaLogs";
# The plugin's own id, read from its `plugin.json` rather
# than guessed. A `type` Grafana does not recognise is
# provisioned without complaint and every query against it
# fails at use, far from anything naming this file.
type = "victoriametrics-logs-datasource";
uid = logsDatasourceUid;
url = deployCfg.grafana.logsDatasourceUrl;
access = "proxy";
# Exactly one datasource may claim this, and metrics has it:
# two defaults is a coin toss over which one an untyped panel
# gets.
isDefault = false;
# See `logLevelRules` above for why the level lives here and
# not in the pipeline.
jsonData = {
inherit logLevelRules;
httpHeaderName1 = "Authorization";
};
# The metrics datasource's bearer; the log store's vhost
# accepts it on `/select/logsql/`.
secureJsonData.httpHeaderValue1 = "$__file{${metricsBearerPath}}";
}
];
};
provision.dashboards.settings = {
apiVersion = 1;
providers = [
{
name = "hyperhive";
type = "file";
# Read-only in the UI: the store path is immutable, so an edit
# saved here would be silently discarded on the next rebuild.
# Better to refuse the edit than to lose it.
allowUiUpdates = false;
options.path = dashboardDir;
}
];
};
# Rules only. With no policy provisioned, Grafana routes every alert
# to its built-in `empty` receiver, which has no integrations: a
# firing rule shows under Alerting → Alert rules and is sent nowhere.
provision.alerting.rules.settings = {
apiVersion = 1;
groups = [
{
orgId = 1;
name = "hyperhive";
folder = "hyperhive";
interval = "1m";
rules = [
# The controller re-runs the forge objects pass every 5m
# (`RECONCILE_INTERVAL` in swarm-controller's
# forge/objects.rs) and warns once per failed write. A
# 10m window always spans the previous tick, so a pass
# failing on every tick keeps the count above zero
# continuously and fires after `for`. One failed pass
# keeps it above zero for only 10m, short of the 15m
# `for`, so it never fires; about three failed passes in
# a row do.
(logCountRule {
uid = "hh-forge-objects-write-failed";
title = "forge reconcile failing";
windowSeconds = 600;
expr = ''_time:10m _msg:"swarm forge objects: write failed; retrying next pass" | stats count() as failures'';
for = "15m";
summary = "swarm-controller has failed to write forge objects on consecutive reconcile passes";
})
# `agent` is the resource attribute every agent container's log
# forwarder carries, and agent names are unique in the swarm, so
# each agent is its own alert instance.
(logCountRule {
uid = "hh-swarm-term-publish-skipped";
title = "swarm terminal publish skipped";
windowSeconds = 900;
expr = ''_time:15m _msg:"swarm terminal: publish skipped" | stats by (agent) count() as skipped'';
for = "5m";
summary = "{{ $labels.agent }} is dropping swarm terminal rows: the harness is not connected to the queue";
})
# `CONNECT_EXHAUSTED` in hive-agent's swarm_queue.rs,
# logged when the harness's first-connect retries
# (about five minutes) all fail, just before it exits.
# systemd restarts it 30s later, so an agent that never
# connects logs it about every six minutes. The window
# is how long the rule stays firing after the last one.
(logCountRule {
uid = "hh-swarm-queue-connect-failed";
title = "swarm queue connect failed";
windowSeconds = 3600;
expr = ''_time:1h _msg:"no swarm queue connection; exiting, since this agent cannot run without one" | stats by (agent) count() as failures'';
for = "0s";
summary = "{{ $labels.agent }} could not connect to the swarm queue and its harness exited; systemd starts it again 30s later";
})
# A run that ends without a verdict leaves that PR with no
# classifier review. `swarm-review-classifier` logs four
# `warn` lines for it: `review classification run failed`
# (a rejected or unreadable API key, a failed model call;
# the cause is in `F_ERROR`), an undecodable request, and a
# reply it could not encode or publish. The window is how
# long the rule stays firing after the last one.
(logCountRule {
uid = "hh-review-classifier-run-failed";
title = "review classifier run failed";
windowSeconds = 1800;
expr = ''_time:30m (_msg:"review classification run failed" OR _msg:"an undecodable try-out; answering with the error" OR _msg:"encoding a try-out's reply failed" OR _msg:"publishing a try-out's reply failed") | stats count() as failures'';
for = "0s";
summary = "a review-classifier run ended without a verdict, so that PR has no classifier review; the log line names the cause (F_ERROR on a failed run)";
})
(logCountRule {
uid = "hh-swarm-agent-state-publish-skipped";
title = "swarm agent state publish skipped";
windowSeconds = 900;
expr = ''_time:15m _msg:"swarm agent state: publish skipped" | stats by (agent) count() as skipped'';
for = "5m";
summary = "{{ $labels.agent }} is dropping agent state updates: the harness is not connected to the queue";
})
# Logged on every connection attempt, so it repeats under
# the reconnect backoff for as long as the path is empty.
(logCountRule {
uid = "hh-swarm-queue-credential-missing";
title = "swarm queue credential missing";
windowSeconds = 900;
expr = ''_time:15m _msg:"nothing is stored at this agent's queue credential path; its queue connection retries under backoff" | stats by (agent) count() as missing'';
for = "5m";
summary = "{{ $labels.agent }} finds nothing at its queue credential path and cannot connect to the queue";
})
# Logged once per failed turn, by `emit_turn_end` in
# hive-agent's turn.rs; the window is how long the rule
# stays firing after it. The exact `_msg` match and the
# unit keep out the subagent daemon's `subagent: turn
# failed` and the ACP backend's `ACP checkpoint turn
# failed`, which a phrase match would also count.
(logCountRule {
uid = "hh-agent-turn-failed";
title = "agent turn failed";
windowSeconds = 900;
expr = ''_time:15m _SYSTEMD_UNIT:="hive-agent.service" _msg:="turn failed" | stats by (agent) count() as failures'';
for = "0s";
summary = "{{ $labels.agent }} had a claude turn fail; the reason is the `F_ERROR` field of the harness's `turn failed` log line";
})
# Same cadence as the forge rule: one pass every 5m
# (`RECONCILE_INTERVAL` in swarm-controller's
# agent_renewal.rs), one line per failed pass, so one
# failed pass never fires and about three in a row do.
(logCountRule {
uid = "hh-agent-credential-renewal-failed";
title = "agent credential renewal failing";
windowSeconds = 600;
expr = ''_time:10m _msg:"agent credential renewal: pass failed; retrying next tick" | stats count() as failures'';
for = "15m";
summary = "swarm-controller has failed the agent credential renewal pass on consecutive ticks";
})
# `MINT_IDENTITY_FAILED` in swarm-controller's jobq.rs,
# logged once per failed `MintAgentIdentity` job node, at
# agent creation or on a certificate renewal; the window
# is how long the rule stays firing after it. Host
# journal records carry the tracing fields as `F_<NAME>`.
(logCountRule {
uid = "hh-agent-identity-mint-failed";
title = "agent identity mint failed";
windowSeconds = 900;
expr = ''_time:15m _SYSTEMD_UNIT:="swarm-controller.service" _msg:"swarm jobq: mint_agent_identity failed" | stats by (F_AGENT) count() as failures'';
for = "0s";
summary = "swarm-controller failed to mint agent {{ $labels.F_AGENT }}'s store identity; the reason is the `F_ERROR` field of the swarm-controller log line";
})
# `hive-archive-backup` (nix/host-modules/hive-archive-backup.nix)
# prints one `archive backup failed: <agent>` line per agent
# it could not back up, and one for a hive swarm-controller
# has granted nothing. The backup runs hourly, so `for`
# rides out the minutes a newly placed agent waits for its
# grant, and a second failed run keeps it firing.
(logCountRule {
uid = "hh-archive-backup-failed";
title = "archive backup failed";
windowSeconds = 7800;
expr = ''_time:130m _SYSTEMD_UNIT:="hive-archive-backup.service" _msg:"archive backup failed" | stats by (_HOSTNAME) count() as failures'';
for = "30m";
summary = "{{ $labels._HOSTNAME }} failed to back up an agent to the archive; the unit's journal names the agent and the cause";
})
# `swarm-archive-prune` prints `archive prune failed: <agent>`.
(logCountRule {
uid = "hh-archive-prune-failed";
title = "archive prune failed";
windowSeconds = 90000;
expr = ''_time:25h _SYSTEMD_UNIT:="swarm-archive-prune.service" _msg:"archive prune failed" | stats count() as failures'';
for = "0s";
summary = "the archive's daily prune failed for an agent's repository, so its retention is not applied; the unit's journal names the agent";
})
# `swarm-archive-check` prints `archive check failed: <agent>`; it runs
# weekly, so the window spans a missed week.
(logCountRule {
uid = "hh-archive-check-failed";
title = "archive check failed";
windowSeconds = 700000;
expr = ''_time:8d _SYSTEMD_UNIT:="swarm-archive-check.service" _msg:"archive check failed" | stats count() as failures'';
for = "0s";
summary = "the archive's weekly integrity check failed for an agent's repository, so its backups may not restore; the unit's journal names the agent and the restic error";
})
# Logged once per detected crash, by `emit_crash_transitions`
# in hive-c0re's crash_watch.rs (10s poll interval). Replaces
# the old per-hive dashboard `agents_crashing` banner — see
# that function's module doc for why the banner went away
# in favour of this. Host journal records carry the
# tracing fields as `F_<NAME>` and no `sender` attribute,
# so the machine is `_HOSTNAME`. The unit
# filter keeps out an agent's own log line if one ever
# quotes the same message.
(logCountRule {
uid = "hh-container-crashed";
title = "container crashed";
windowSeconds = 900;
expr = ''_time:15m _SYSTEMD_UNIT:="hive-c0re.service" _msg:"container crash detected" | stats by (_HOSTNAME, F_AGENT) count() as crashes'';
for = "0s";
summary = "{{ $labels._HOSTNAME }} detected agent {{ $labels.F_AGENT }}'s container crash (not an operator-initiated stop)";
})
# hive-c0re's readiness verdict, the one `/health/ready`
# gives: degraded while any `crit`-level warning is raised.
# Read from the per-warning series (`hyperhive.hive.warning`)
# rather than the `hyperhive.hive.degraded` gauge, so each
# critical `kind` is its own instance and the alert names
# the warning that triggered it. `for` rides out a
# restart-time blip.
(metricThresholdRule {
uid = "hh-hive-degraded";
title = "hive degraded";
expr = ''max by (sender, kind) ({__name__="hyperhive.hive.warning", level="crit"})'';
threshold = 0;
for = "2m";
summary = "{{ $labels.sender }} is degraded by the critical warning {{ $labels.kind }}; the message is the `hive warning raised` line in the hive-c0re log";
})
# One series per raised warning (`hyperhive.hive.warning`),
# so each `kind` is its own alert instance. The text is the
# `hive warning raised` line in the hive-c0re log. Disk
# pressure is left out: it has its own thresholds below, on
# the filesystem metric rather than the registry entry.
# Sweeps raise their warning only after several misses, so
# `for` is short. `pending_logins` is dropped for a hive that exports
# `hyperhive.agent.needs_login`, where `hh-agent-needs-login`
# below pages once per agent; a hive on an older hive-c0re
# has no such series, so it keeps paging here.
(metricThresholdRule {
uid = "hh-hive-warning";
title = "hive warning raised";
expr = ''max by (sender, kind, level) ({__name__="hyperhive.hive.warning", kind!~"disk_pressure|pending_logins"} or ({__name__="hyperhive.hive.warning", kind="pending_logins"} unless on (sender) group by (sender) ({__name__="hyperhive.agent.needs_login"})))'';
threshold = 0;
for = "2m";
summary = "{{ $labels.sender }} has a {{ $labels.level }} warning raised: {{ $labels.kind }}; the message is the `hive warning raised` line in the hive-c0re log";
})
# `hyperhive.agent.needs_login` is `1` for a running agent
# without a usable claude login; stopped agents report
# nothing. One alert instance per `agent`; `for`
# lets a login in progress finish first.
(metricThresholdRule {
uid = "hh-agent-needs-login";
title = "agent needs a claude login";
expr = ''max by (agent) ({__name__="hyperhive.agent.needs_login"}) == 1'';
threshold = 0;
for = "5m";
summary = "agent {{ $labels.agent }} has needed a claude login for 5 minutes; open its page in the dashboard to complete it";
})
# Processes the kernel OOM-killed in an agent's container, from
# the counter hive-c0re exports (`otel_metrics.rs`). A budgeted
# agent has no swap, so each kill is a subagent run, bash task or
# the agent's claude that hit its RAM budget. More than three in
# an hour is a budget that is too small for the work, not a
# one-off peak. One alert instance per `agent`.
(metricThresholdRule {
uid = "hh-agent-oom-kills";
title = "agent OOM-killed repeatedly";
windowSeconds = 3600;
expr = ''sum by (agent) (increase({__name__="hyperhive.container.memory.oom_kills", agent!=""}[1h]))'';
threshold = 3;
for = "0m";
summary = "agent {{ $labels.agent }} had more than 3 processes OOM-killed in the last hour: it keeps hitting its RAM budget; see \"OOM kills by agent\" on the agents dashboard, and raise its memory cap if the work needs it";
})
# `hyperhive.hive.nix_store.utilization` is the used fraction of the
# filesystem holding the nix store, the one that failed CI
# with ENOSPC before the GC guardrails.
(metricThresholdRule {
uid = "hh-host-disk-high";
title = "host disk filling";
expr = ''max by (sender) ({__name__="hyperhive.hive.nix_store.utilization"})'';
threshold = 0.85;
for = "10m";
summary = "the nix store's filesystem of {{ $labels.sender }} is over 85% full; garbage-collect before it runs out of space";
})
(metricThresholdRule {
uid = "hh-host-disk-critical";
title = "host disk almost full";
expr = ''max by (sender) ({__name__="hyperhive.hive.nix_store.utilization"})'';
threshold = 0.95;
for = "2m";
summary = "the nix store's filesystem of {{ $labels.sender }} is over 95% full; garbage-collect now";
})
# The fraction of a store client certificate's validity
# already used, from the `bao.client_cert.*` gauges the
# services export (`swarm_secret_client::cert_metrics`). Both gauges of a
# series carry identical labels, so the division matches
# one-to-one on all of them without `on()`/`group_left`.
# `last_over_time` rides out the five-minute cadence of
# the one-shot reporter (`swarm-ci-metrics`). Agent leaves
# renew at half their life, so a fraction over 0.8 means
# the renewal has been stuck for days. `sender` and `agent`
# stay in the grouping so the alert names the holder.
# Agents whose deploy the build gate holds back, from the gauge
# swarm-controller exports (`observability/held_deploys.rs`): a build that
# fails, or that keeps getting no answer from the builder. A deploy
# whose facts copy to its hive fails is held too.
# Thirty minutes covers a builder restart and the controller's
# ten-minute retries.
(metricThresholdRule {
uid = "hh-deploys-held";
title = "deploys held by the build gate";
expr = ''sum({__name__="swarm.deploys.held"})'';
threshold = 0;
for = "30m";
summary = "swarm-controller is holding back the deploy of one or more agents because the builder's build of internal/meta fails or gets no answer, or the cache facts can't be copied to its hive; the failed `build_meta` or `copy_attic_facts` node on the Jobs page says which";
})
(metricThresholdRule {
uid = "hh-bao-client-cert-lifetime";
title = "bao client certificate past 80% of its lifetime";
expr = ''max by ("service.name", cert, sender, agent) ((time() - last_over_time({__name__="bao.client_cert.not_before"}[15m])) / (last_over_time({__name__="bao.client_cert.not_after"}[15m]) - last_over_time({__name__="bao.client_cert.not_before"}[15m])))'';
threshold = 0.8;
for = "10m";
summary = "the store client certificate {{ $labels.cert }} (sender {{ $labels.sender }}, agent {{ $labels.agent }}) is past 80% of its validity";
})
# Usage share ahead of the clock share, per claude account and
# window: percent used minus the percent of the window already
# elapsed, so above zero means ahead. The window length comes
# from the `window` label (`seven_day`, `five_hour`); other
# windows are not selected. `account` is stamped by hive-agent
# (`claude_usage_watch`); series without it (older agent builds)
# are not selected. `max by` collapses the agents that share an
# account. A `resets_at` in the past makes the elapsed share
# exceed 100, so a stale series cannot fire.
(metricThresholdRule {
uid = "hh-claude-usage-ahead-of-clock";
title = "claude usage ahead of the clock";
expr =
let
ahead =
window: seconds:
''max by (account, window) (last_over_time({__name__="hyperhive.agent.claude_usage.percent", window="${window}", account!=""}[15m])) - 100 * (1 - (max by (account, window) (last_over_time({__name__="hyperhive.agent.claude_usage.resets_at", window="${window}", account!=""}[15m])) - time()) / ${toString seconds})'';
in
"(${ahead "seven_day" 604800}) or (${ahead "five_hour" 18000})";
threshold = 0;
for = "1h";
summary = "claude account {{ $labels.account }} has used more of its {{ $labels.window }} usage window than the window has elapsed";
})
]
# One rule per declared hive's collector rather than one grouped by
# `sender`, so a collector that sends nothing at all still has an
# instance to fire. The swarm collector stamps `sender` with the
# client id the hive's collector authenticated as, the same
# `hiveClientPrefix` name the OIDC client is registered under.
++ lib.mapAttrsToList (
name: _:
logAbsenceRule {
uid = "hh-logs-absent-${name}";
title = "no log records from ${name}";
windowSeconds = 600;
expr = ''_time:10m sender:="${hyperhiveCfg.swarm.authelia.hiveClientPrefix}${name}" | stats count() as records'';
for = "5m";
summary = "hive ${name} has sent no log records to VictoriaLogs for at least 10m";
}
) hyperhiveCfg.swarm.hives;
}
];
};
};
# The credentials the unit names are ids: the store identity the pod's login
# replaces, the store's CA (a public file the pod mounts from the cluster's CA
# ConfigMap) and the listener credential the pod loads from its Secret.
unit = {
serviceConfig = {
ExecStart = "${start}/bin/${service}";
StateDirectory = "grafana";
RuntimeDirectory = secretDirName;
LoadCredential = [
"bao-client.pem"
"bao-client-key.pem"
storeAuth.credentialId
]
++ lib.optional (baoDeploy.serverCaFile != null) "bao-ca.pem";
};
environment = {
BAO_ADDR = "https://${baoCfg.domain}:${toString baoCfg.port}";
BAO_CLIENT_CERT = "${credDir}/bao-client.pem";
BAO_CLIENT_KEY = "${credDir}/bao-client-key.pem";
}
// lib.optionalAttrs (baoDeploy.serverCaFile != null) {
BAO_CACERT = "${credDir}/bao-ca.pem";
}
# Go: `SSL_CERT_FILE` replaces its trust store, which the hive's CA joins
# for the names the pod dials through the gateway.
// lib.optionalAttrs caTrust.useSelfSigned {
SSL_CERT_FILE = caTrust.bundlePathFor service;
};
path = [ ];
};
# The init container and the sidecar log in as the pod does, with the
# environment and mounts of Grafana's container.
#
# The init container also reads two things of the container this pod
# replaces, both read-only: the key it generated (a volume of its own, on the
# directory beside the data directory) and the data directory, to see whether
# the carried database already holds encrypted data. It runs as the uid that
# container ran under, because that user owns the key file (mode 0600, in a
# directory of 0700) and the database; its files in the pod's secret volume
# are group-readable by the pod's group, which Grafana reads them through.
pod =
{
env,
volumeMounts,
securityContext,
metaFor,
...
}:
let
ref = "${setupImage.imageName}:${setupImage.imageTag}";
container = name: bin: mounts: extra: {
inherit name;
securityContext = securityContext // (extra.securityContext or { });
image = ref;
imagePullPolicy = "IfNotPresent";
command = [ "/bin/${bin}" ];
env = lib.mapAttrsToList (n: v: {
name = n;
value = v;
}) (lib.filterAttrs (n: _: lib.hasPrefix "BAO_" n) env // { HOME = "/tmp"; });
volumeMounts =
lib.filter (
m:
lib.elem m.name [
"credentials"
"bao-token"
"runtime"
"tmp"
]
) volumeMounts
++ mounts;
};
readOnlyState = map (m: m // { readOnly = true; }) (lib.filter (m: m.name == "state") volumeMounts);
in
{
initContainers = [
(container "fetch-secrets" "swarm-grafana-fetch" (
readOnlyState
++ [
{
name = "legacy-key";
mountPath = legacyKeyMount;
readOnly = true;
}
]
) { securityContext.runAsUser = config.ids.uids.grafana; })
];
containers = [ (container "controller-token" "swarm-grafana-controller-token" [ ] { }) ];
volumes = [
{
name = "legacy-key";
persistentVolumeClaim = {
claimName = legacyKeyClaim;
readOnly = true;
};
}
];
# A static local volume on the key's directory: the namespace's Pod
# Security level admits a claim and refuses a `hostPath`. Pinned to the
# node that holds Grafana's data, as the data volume is.
objects = {
"${legacyKeyClaim}/persistentvolume" = {
apiVersion = "v1";
kind = "PersistentVolume";
metadata = removeAttrs (metaFor legacyKeyClaim) [ "namespace" ];
spec = {
capacity.storage = "1Mi";
accessModes = [ "ReadOnlyMany" ];
persistentVolumeReclaimPolicy = "Retain";
storageClassName = legacyKeyClaim;
local.path = legacyKeyDir;
nodeAffinity = labels.stateAffinity "grafana";
};
};
"${legacyKeyClaim}/persistentvolumeclaim" = {
apiVersion = "v1";
kind = "PersistentVolumeClaim";
metadata = metaFor legacyKeyClaim;
spec = {
accessModes = [ "ReadOnlyMany" ];
resources.requests.storage = "1Mi";
storageClassName = legacyKeyClaim;
volumeName = legacyKeyClaim;
};
};
};
images = [ setupImage ];
};
in
{
# What the service IS to every hive is `swarm.grafana` in
# ./swarm-grafana-service.nix. What the host running it decides is here:
# which build it runs, where its datasources point, which plugins sit in its
# store path.
# `enable` already lives in ./deploy.nix, which also carries the renames.
#
# Both datasource URLs are wiring, so they live here.
options.services.hyperhive.deploy.grafana = {
package = lib.mkOption {
type = lib.types.package;
default = pkgs.grafana;
defaultText = lib.literalExpression "pkgs.grafana";
description = "Grafana package to run.";
};
datasourceUrl = lib.mkOption {
type = lib.types.str;
default = "https://${hyperhiveCfg.swarm.victoriametrics.domain}";
defaultText = lib.literalExpression ''"https://''${services.hyperhive.swarm.victoriametrics.domain}"'';
description = ''
Where the provisioned datasource points. Defaults to the metrics
store's swarm name, served by the gateway of whichever host runs the
store, so Grafana and the store need not share a host.
The datasource sends the bearer the init container of Grafana's pod
keeps in the swarm secret store, which is what the store's query
routes on that vhost check. Whatever URL this names receives that
bearer.
'';
};
logsDatasourceUrl = lib.mkOption {
type = lib.types.str;
default = "https://${hyperhiveCfg.swarm.victorialogs.domain}";
defaultText = lib.literalExpression ''"https://''${services.hyperhive.swarm.victorialogs.domain}"'';
description = ''
Where the provisioned logs datasource points. Defaults to the log
store's swarm name, served by the gateway of whichever host runs the
store, so Grafana and the store need not share a host.
Provisioned unconditionally, like the metrics datasource — the store
being off is a deployment choice rather than a reason to withhold the
connection, and an operator whose logs live elsewhere sets this.
The datasource sends the same bearer as the metrics one, which the
store's `/select/logsql/` route checks. Whatever URL this names
receives that bearer.
'';
};
plugins = lib.mkOption {
type = lib.types.listOf lib.types.package;
default = [
pkgs.grafanaPlugins.grafana-metricsdrilldown-app
# Reading the swarm's logs needs the datasource that speaks LogsQL.
# Nothing is paired with it to browse them: Explore is that browser.
pkgs.grafanaPlugins.victoriametrics-logs-datasource
];
defaultText = lib.literalExpression ''
[
pkgs.grafanaPlugins.grafana-metricsdrilldown-app
pkgs.grafanaPlugins.victoriametrics-logs-datasource
]'';
example = lib.literalExpression "[ pkgs.grafanaPlugins.grafana-piechart-panel ]";
description = ''
Grafana plugins to install, as packages. Declarative rather than
installed through the UI, which is the only shape that works here:
plugin management is **server-admin** scoped, and on an SSO hive
nobody holds that role — `users.auto_assign_org_role` grants an
*org* role, and the built-in local admin that does hold server
admin cannot log in because the login form is disabled whenever
SSO is configured.
That is a deliberate pair of decisions rather than an oversight,
and this option is the way through it: plugins live in the store
and in git, so they survive a rebuild of the pod and a state reset,
and the pod needs no runtime egress to grafana.com.
⚠️ This list is the ONLY way a plugin reaches this Grafana.
Setting it at all disables upstream's `preinstall` mechanism (see
the `declarativePlugins` comment below), which is what normally
fetches the Drilldown apps on first start — so a plugin left off
this list is absent, not merely un-pinned.
Metrics Drilldown is on by default because this swarm's Grafana
exists to read VictoriaMetrics, and the queryless metrics browser
is the part of that people actually reach for.
Its Logs / Traces / Profiles siblings are deliberately NOT here,
and for two different reasons. Traces and Profiles front Tempo
and Pyroscope, which this swarm does not run — a UI for a backend
that does not answer. Logs Drilldown is the subtler one: this
swarm *does* run a log store, so that argument does not apply
to it, but the app is Loki-only and no configuration here changes
that. Its volume views call `/loki/api/v1/index/volume`, which
VictoriaLogs does not implement and answers "unsupported path
requested". Logs are browsed through Explore instead.
'';
};
};
options.services.hyperhive.deploy.grafana.unit = lib.mkOption {
type = lib.types.raw;
readOnly = true;
internal = true;
default = unit;
description = ''
Grafana's unit, the `serviceConfig`, `environment` and `path` that
./k8s/render.nix renders its pod from.
'';
};
options.services.hyperhive.deploy.grafana.rendered = lib.mkOption {
type = lib.types.raw;
readOnly = true;
internal = true;
default = grafana // {
scripts = {
start = builtins.unsafeDiscardStringContext start.text;
fetch = builtins.unsafeDiscardStringContext fetch.text;
controllerToken = builtins.unsafeDiscardStringContext controllerToken.text;
};
configFile = builtins.unsafeDiscardStringContext (toString configFile);
};
description = ''
What the pod is rendered from, as data: upstream's `services.grafana`
settings and provisioning, the config file, and the text of the scripts
the pod runs. The module-eval cases read it.
'';
};
options.services.hyperhive.deploy.grafana.startPackage = lib.mkOption {
type = lib.types.package;
readOnly = true;
internal = true;
default = start;
description = "The pod's entry point, the `swarm-grafana` script that applies the admin password and starts the server.";
};
options.services.hyperhive.deploy.grafana.pod = lib.mkOption {
type = lib.types.raw;
readOnly = true;
internal = true;
default = pod;
description = ''
What the pod holds besides Grafana: a function of Grafana's container that
./k8s/render.nix calls, giving the init container that fetches the
secrets, the sidecar that keeps the controller's token, and their image.
'';
};
options.services.hyperhive.deploy.grafana.servicePort = lib.mkOption {
type = lib.types.port;
readOnly = true;
internal = true;
default = grafanaPort;
description = "The port the Service publishes.";
};
options.services.hyperhive.deploy.grafana.hostDataDir = lib.mkOption {
type = lib.types.str;
readOnly = true;
internal = true;
default = hostDataDir;
description = ''
Grafana's data directory on the host, which the pod's volume is. A host
without it gets the directory made.
'';
};
config = lib.mkIf deployCfg.grafana.enable {
services.hyperhive.gateway.localNames = [ cfg.domain ];
# 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;
# The pod reaches the secret store through the hive bridge.
services.hyperhive.network.enable = lib.mkDefault true;
assertions = [
{
assertion = haveClientIdentity;
message = ''
services.hyperhive.deploy.grafana.enable requires this host to hold a
swarm-secret-store client identity: set both
services.hyperhive.deploy.bao.grafanaOidcClientCertFile
services.hyperhive.deploy.bao.grafanaOidcClientKeyFile
Grafana's OIDC client secret is minted by authelia and read out of
the store, on every host that runs Grafana — including the host that
runs authelia. That is one delivery route rather than two, and it is
what the store is for: a certificate is the credential placed out of
band, and every other secret comes from the store with it.
⚠️ Grafana's OWN leaf, not deploy.bao.clientCertFile. That one is the
hive's, and its grant reads every agent credential in the swarm and
this hive's own secrets; this role reads the one path Grafana's
client secret lives at. Pointing this option at the hive's leaf would
evaluate, deploy and log in — and undo the split.
On a hive that runs the store, glue-bao-tls.nix supplies both as
defaults and there is nothing to do. Elsewhere the leaf is issued
from that CA out of band and named here — see docs/2-handbook/swarm/credentials.md.
'';
}
];
# Grafana's own login is the credential of the UI and the API, and the
# gateway adds no second check there. `/metrics` answers anyone who
# reaches the port, so the gateway asks authelia whether the caller is the
# swarm collector and then sends the login the pod's `[metrics]` section
# takes (./lib/store-auth.nix). The file is empty until the unit that
# publishes the credential has run (./k8s/store-credentials.nix), and
# Grafana then refuses the scrape.
services.hyperhive.gateway.vhosts."${cfg.domain}" = {
locations."= /metrics" = {
proxyPass = "http://${grafanaVariable}/metrics$is_args$args";
extraConfig = viaGrafana + ''
include ${storeAuth.nginxFile "grafana"};
auth_request /__grafana_metrics_authz;
'';
};
locations."= /__grafana_metrics_authz" = {
proxyPass = "https://${autheliaDomain}/api/authz/auth-request";
recommendedProxySettings = false;
extraConfig = ''
internal;
${gatewayCfg.lib.verifiedProxyTo autheliaDomain}
proxy_pass_request_body off;
proxy_set_header Content-Length "";
proxy_set_header X-Original-Method $request_method;
proxy_set_header X-Original-URL $scheme://$http_host$request_uri;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-Host $http_host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
'';
};
# No URI part: the request's own path and query reach Grafana as the
# caller sent them.
locations."/" = {
proxyPass = "http://${grafanaVariable}";
proxyWebsockets = true;
extraConfig = viaGrafana + ''
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
'';
};
};
# The pod's volume is Grafana's data directory, which the rule makes when it
# is missing. It leaves an existing directory's owner and mode alone: the
# pod's group is given the tree when the pod starts. The directory of the
# earlier key is made the same way, because the volume on it needs the path
# to exist.
systemd.tmpfiles.rules = [
"d ${hostDataDir} - - - -"
"d ${legacyKeyDir} - - - -"
];
};
}