The Deployment swarm-grafana replaces the swarm-grafana container: one replica on a static local volume that is the container's data directory, an init container that fetches the OIDC client secret and creates the administrator password, the datasources' bearer and the encryption key in the secret store, and a sidecar that keeps the controller's Viewer token. The datasources reach the stores through the gateway with that bearer, and Grafana's /metrics asks for the stores' kind of credential, which the vhost sends. The five host units, the journal forwarder, its client glue and the unix-socket directory go with the container.
1316 lines
48 KiB
Nix
1316 lines
48 KiB
Nix
# The Kubernetes objects that run each in-cluster swarm service this host
|
|
# deploys, read from that service's systemd unit as this host renders it.
|
|
# Imported by ./default.nix, which writes the objects out as YAML. Returns
|
|
# `objects`, the `images` the pods run, and what ./runtime.nix moves services
|
|
# with.
|
|
#
|
|
# The pod takes the unit's environment, credential ids, state and runtime
|
|
# directories, and timer. Every file the unit names is mounted at the path the
|
|
# unit names it by, so the environment carries over as it is and a change to a
|
|
# unit shows up in its manifest. The one change is the store login: a service
|
|
# the store has a jwt role for (`deploy.bao.k8sPrincipals`) runs under a
|
|
# ServiceAccount of its name, with a projected token for the store's audience
|
|
# in place of its client certificate and key.
|
|
#
|
|
# Secrets are referenced by name and credential id only. The output lands in
|
|
# the world-readable nix store, so it never holds a credential's host path or
|
|
# contents. A credential that is a public CA file comes from the CA ConfigMap,
|
|
# not a Secret.
|
|
{
|
|
lib,
|
|
pkgs,
|
|
config,
|
|
}:
|
|
let
|
|
hyperhiveCfg = config.services.hyperhive;
|
|
deployCfg = hyperhiveCfg.deploy;
|
|
k8sCfg = hyperhiveCfg.k8s;
|
|
baoDeployCfg = deployCfg.bao;
|
|
podAuth = import ../lib/bao-pod-auth.nix;
|
|
caTrust = import ../lib/hive-ca-trust.nix {
|
|
inherit lib;
|
|
tlsCfg = deployCfg.hive-controller.tls;
|
|
gatewayCfg = hyperhiveCfg.gateway;
|
|
};
|
|
|
|
# The ConfigMap that holds the public CA files the pods trust, and its keys.
|
|
# A CA certificate is public, so it travels as a ConfigMap, never a Secret.
|
|
# The file behind each key lives on the host: `caSources` names it, and
|
|
# ./runtime.nix publishes the ConfigMap from those files.
|
|
caConfigMap = "hyperhive-ca-trust";
|
|
trustBundleKey = "trust-bundle.pem";
|
|
baoServerCaKey = "bao-server-ca.pem";
|
|
hiveClientCaKey = "hive-client-ca.pem";
|
|
servicesRootKey = "swarm-services-root.pem";
|
|
controllerCfg = deployCfg.swarm-controller;
|
|
controllerOnCluster = controllerCfg.enable;
|
|
controllerTcp = hyperhiveCfg.swarm.controller.tcp;
|
|
natsCfg = deployCfg.nats;
|
|
labels = import ./labels.nix;
|
|
servicesRootPath = "${deployCfg.hive-controller.tls.stateDir}/${servicesRootKey}";
|
|
caSources = {
|
|
${trustBundleKey} = if caTrust.useSelfSigned then caTrust.caHostPath else null;
|
|
${baoServerCaKey} = baoDeployCfg.serverCaFile;
|
|
# What the controller's pod needs of the hive: the root its listener
|
|
# trusts the gateway's client leaf by, and the authority it writes into
|
|
# each hive's store role. Both are public.
|
|
${servicesRootKey} = if controllerOnCluster && controllerTcp.enable then servicesRootPath else null;
|
|
${hiveClientCaKey} = if controllerOnCluster then controllerCfg.hiveClientCaFile else null;
|
|
};
|
|
|
|
# `serviceUser` is the user every image runs its daemon as. Mounted files are
|
|
# group-owned by its group through `fsGroup`.
|
|
inherit (import ../../images { inherit pkgs lib; })
|
|
mkServiceImage
|
|
serviceUser
|
|
wgetOnly
|
|
loopbackProbe
|
|
;
|
|
|
|
# `DRAIN` in swarm-secret-client/src/shutdown.rs: how long a daemon keeps
|
|
# finishing in-flight work after SIGTERM before it exits on its own. The
|
|
# kubelet's SIGKILL comes after the grace period, so the grace period is
|
|
# longer.
|
|
drainSeconds = 10;
|
|
terminationGracePeriodSeconds = drainSeconds + 5;
|
|
|
|
healthPort = 8080;
|
|
|
|
# What NixOS puts on every unit's `path`.
|
|
nixosDefaultPath = [
|
|
"coreutils"
|
|
"findutils"
|
|
"gnugrep"
|
|
"gnused"
|
|
"systemd"
|
|
];
|
|
|
|
# The controller's listener leaf: its pod issues the leaf itself, from the
|
|
# store, with its ServiceAccount token (../lib/swarm-controller-tls-issue.nix is
|
|
# the script). An init container writes it before the daemon starts and a
|
|
# second container renews it, both into an emptyDir only the pod holds.
|
|
tlsIssue = import ../lib/swarm-controller-tls-issue.nix { inherit lib config; };
|
|
leafTools = [
|
|
baoDeployCfg.package
|
|
pkgs.jq
|
|
pkgs.openssl
|
|
pkgs.coreutils
|
|
pkgs.gnugrep
|
|
];
|
|
leafIssueBin = "swarm-controller-tls-issue";
|
|
leafRenewBin = "swarm-controller-tls-renew";
|
|
leafImagePackage =
|
|
let
|
|
issue = pkgs.writeShellScriptBin leafIssueBin ''
|
|
export PATH=${lib.makeBinPath leafTools}
|
|
${tlsIssue.script {
|
|
login = "bao write -field=token auth/${podAuth.mount}/login role=swarm-controller jwt=@${podAuth.tokenFile}";
|
|
credential = "ServiceAccount token";
|
|
}}
|
|
'';
|
|
# The host's timer runs the same check daily: the script leaves a leaf
|
|
# that is within the first half of its window alone. A failed run (the
|
|
# store sealed or unreachable) is tried again sooner.
|
|
renew = pkgs.writeShellScriptBin leafRenewBin ''
|
|
export PATH=${lib.makeBinPath [ pkgs.coreutils ]}
|
|
while true; do
|
|
if ${issue}/bin/${leafIssueBin}; then
|
|
sleep 86400
|
|
else
|
|
sleep 600
|
|
fi
|
|
done
|
|
'';
|
|
in
|
|
pkgs.symlinkJoin {
|
|
name = "swarm-controller-tls";
|
|
paths = [
|
|
issue
|
|
renew
|
|
];
|
|
};
|
|
|
|
# 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 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 (with `startupFailureThreshold`, a startup probe of that many
|
|
# ten-second tries first), 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
|
|
# `"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).
|
|
# `daemon` is the unit's binary and systemd name where the service's own name
|
|
# differs, `baoRole` the store role the daemon logs in with, and `pod`, where
|
|
# a pod holds more than the daemon, a function of the daemon's container
|
|
# (its environment, mounts and security context) giving the rest: further
|
|
# containers, init containers, volumes, host aliases, pod settings, objects and
|
|
# and images. An `otlp` of `"none"` is a daemon that pushes no telemetry of its
|
|
# own.
|
|
# `egress`, where a service has it, names the host services (`hostPorts`) its
|
|
# pod may reach: it gets a NetworkPolicy that allows those and cluster DNS and
|
|
# admits no ingress. `hostUsers = false` runs the pod in a user namespace of
|
|
# its own, so its ids map to unprivileged ones on the node.
|
|
services = {
|
|
swarm-controller = {
|
|
inherit (controllerCfg) enable package unit;
|
|
kind = "Deployment";
|
|
healthEnv = "SWARM_CONTROLLER_HEALTH_ADDR";
|
|
etcFiles = [ "hyperhive/swarm-controller.json" ];
|
|
publicCredentials = {
|
|
"bao-ca.pem" = baoServerCaKey;
|
|
"hive-client-ca.pem" = hiveClientCaKey;
|
|
};
|
|
publicFiles = lib.optionalAttrs controllerTcp.enable { ${servicesRootPath} = servicesRootKey; };
|
|
# The TCP listener, behind a Service the gateway on the host dials by
|
|
# name.
|
|
listener = lib.optionalAttrs controllerTcp.enable {
|
|
port = controllerTcp.port;
|
|
tlsDir = controllerCfg.tcp.tlsDir;
|
|
};
|
|
# The unit pushes to the swarm collector's route and mints its own bearer
|
|
# (../glue-controller-env.nix, `otel_http_client.rs`).
|
|
otlp = "own";
|
|
ephemeralState = true;
|
|
};
|
|
# The queue and its auth-callout responder are one pod: the responder is the
|
|
# daemon below, and the server (with its exporter) is `pod`'s.
|
|
swarm-nats = {
|
|
inherit (natsCfg) enable;
|
|
inherit (natsCfg) pod;
|
|
package = natsCfg.authPackage;
|
|
daemon = "swarm-nats-auth";
|
|
baoRole = "swarm-nats-auth";
|
|
unit = natsCfg.unit;
|
|
kind = "Deployment";
|
|
healthEnv = "SWARM_NATS_AUTH_HEALTH_ADDR";
|
|
etcFiles = [ ];
|
|
publicCredentials."bao-ca.pem" = baoServerCaKey;
|
|
otlp = "none";
|
|
};
|
|
swarm-notify-router = {
|
|
inherit (deployCfg.notify-router) enable package;
|
|
unit = deployCfg.notify-router.unit;
|
|
kind = "Deployment";
|
|
healthEnv = "SWARM_NOTIFY_ROUTER_HEALTH_ADDR";
|
|
etcFiles = [ ];
|
|
publicCredentials.notify-router-bao-server-ca = baoServerCaKey;
|
|
otlp = "hive";
|
|
};
|
|
swarm-stt = {
|
|
inherit (deployCfg.stt) enable package;
|
|
unit = deployCfg.stt.unit;
|
|
kind = "Deployment";
|
|
healthEnv = "SWARM_STT_HEALTH_ADDR";
|
|
etcFiles = [ ];
|
|
publicCredentials.stt-bao-server-ca = baoServerCaKey;
|
|
# The audio it decodes comes from strangers. It reaches the store, the
|
|
# identity provider and the queue it logs in to and answers on, and
|
|
# pushes telemetry to the hive collector.
|
|
egress = [
|
|
"store"
|
|
"identity"
|
|
"queue"
|
|
"collector"
|
|
];
|
|
otlp = "hive";
|
|
ephemeralState = true;
|
|
# Stands in for the unit's `PrivateUsers`: the decoder reads audio that
|
|
# strangers sent.
|
|
hostUsers = false;
|
|
};
|
|
swarm-review-classifier = {
|
|
inherit (deployCfg.review-classifier) enable package;
|
|
unit = deployCfg.review-classifier.unit;
|
|
kind = "Deployment";
|
|
healthEnv = "SWARM_REVIEW_CLASSIFIER_HEALTH_ADDR";
|
|
etcFiles = [ ];
|
|
publicCredentials.review-classifier-bao-server-ca = baoServerCaKey;
|
|
otlp = "hive";
|
|
};
|
|
swarm-claude-login = {
|
|
inherit (deployCfg.claude-login) enable package;
|
|
unit = deployCfg.claude-login.unit;
|
|
kind = "Deployment";
|
|
healthEnv = "SWARM_CLAUDE_LOGIN_HEALTH_ADDR";
|
|
etcFiles = [ ];
|
|
publicCredentials.claude-login-bao-server-ca = baoServerCaKey;
|
|
otlp = "hive";
|
|
};
|
|
swarm-ci-metrics = {
|
|
inherit (deployCfg.ci-metrics) enable package;
|
|
unit = deployCfg.ci-metrics.unit;
|
|
timer = deployCfg.ci-metrics.timer;
|
|
kind = "CronJob";
|
|
healthEnv = null;
|
|
etcFiles = [ ];
|
|
publicCredentials."bao-ca.pem" = baoServerCaKey;
|
|
# A static local volume on the unit's own state directory, in place of the
|
|
# default class: it binds only on the node with the service's state label
|
|
# (./labels.nix).
|
|
localState = {
|
|
service = "ci-metrics";
|
|
hostDir = deployCfg.ci-metrics.hostStateDir;
|
|
};
|
|
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";
|
|
};
|
|
# The metrics store: the VictoriaMetrics daemon alone, on a static local
|
|
# volume on the store's data directory. It holds no store
|
|
# identity and pushes no telemetry; its own `/metrics` is scraped through
|
|
# the gateway. It opens its storage before it serves HTTP, so the pod has a
|
|
# startup probe that outlasts a large store's open.
|
|
swarm-victoriametrics = {
|
|
inherit (deployCfg.victoriametrics) enable package unit;
|
|
daemon = "victoria-metrics";
|
|
kind = "Deployment";
|
|
healthEnv = null;
|
|
probe = {
|
|
path = "/health";
|
|
startupFailureThreshold = 60;
|
|
};
|
|
etcFiles = [ ];
|
|
publicCredentials = { };
|
|
listener.port = deployCfg.victoriametrics.servicePort;
|
|
localState = {
|
|
service = "victoriametrics";
|
|
hostDir = deployCfg.victoriametrics.hostDataDir;
|
|
};
|
|
fsGroupChangePolicy = "OnRootMismatch";
|
|
otlp = "none";
|
|
};
|
|
# The two `auth_request` responders of the metrics store's gateway vhost,
|
|
# which log in to the secret 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`; the first is the `swarm-logs-auth` binary on the metrics
|
|
# surface.
|
|
swarm-metrics-auth = {
|
|
inherit (deployCfg.victoriametrics) enable;
|
|
package = deployCfg.victoriametrics.agentAuthPackage;
|
|
daemon = "swarm-logs-auth";
|
|
unit = deployCfg.victoriametrics.authUnit;
|
|
inherit (deployCfg.victoriametrics) pod;
|
|
kind = "Deployment";
|
|
healthEnv = "SWARM_LOGS_AUTH_HEALTH_ADDR";
|
|
etcFiles = [ ];
|
|
publicCredentials."bao-ca.pem" = baoServerCaKey;
|
|
listener.port = deployCfg.victoriametrics.authServicePort;
|
|
egress = [ "store" ];
|
|
otlp = "none";
|
|
};
|
|
# Grafana: the swarm's metrics UI, on a static local volume that is its
|
|
# data directory. Its configuration, provisioning and plugins are in the
|
|
# image; an init container fetches its secrets and a sidecar keeps the
|
|
# controller's token (`pod`). It logs in to nothing itself and pushes no
|
|
# telemetry. The UI and the API take Grafana's own login; its `/metrics`
|
|
# takes the listener credential.
|
|
swarm-grafana = {
|
|
inherit (deployCfg.grafana) enable unit pod;
|
|
package = deployCfg.grafana.startPackage;
|
|
kind = "Deployment";
|
|
healthEnv = null;
|
|
probe = {
|
|
path = "/api/health";
|
|
startupFailureThreshold = 30;
|
|
};
|
|
etcFiles = [ ];
|
|
publicCredentials."bao-ca.pem" = baoServerCaKey;
|
|
listener.port = deployCfg.grafana.servicePort;
|
|
# The secret store, and the gateway's 443: authelia's token and userinfo
|
|
# routes and both datasources.
|
|
egress = [
|
|
"store"
|
|
"identity"
|
|
];
|
|
baoRole = "swarm-grafana-oidc";
|
|
localState = {
|
|
service = "grafana";
|
|
hostDir = deployCfg.grafana.hostDataDir;
|
|
};
|
|
fsGroupChangePolicy = "OnRootMismatch";
|
|
otlp = "none";
|
|
};
|
|
};
|
|
|
|
# Where a pod pushes telemetry. A `"hive"` service pushes to the hive
|
|
# collector, by the name the node's CoreDNS answers with the bridge address
|
|
# (./host-services.nix): a unit's own endpoint is a loopback forwarder or a
|
|
# gateway route that needs a token, and a pod has neither. An `"own"` service
|
|
# keeps its unit's endpoint, a swarm route it logs in to by itself.
|
|
# `otlpEndpointVars` are the variables a unit may name its endpoint in; the
|
|
# first is the standard one and is always set for a `"hive"` service.
|
|
otelCfg = hyperhiveCfg.otel;
|
|
collectorEndpoint = "http://${otelCfg.collector.host}:${toString hyperhiveCfg.swarm.hiveOtel.collectorPort}";
|
|
otlpEndpointVars = [
|
|
"OTEL_EXPORTER_OTLP_ENDPOINT"
|
|
"SWARM_CI_METRICS_OTLP_ENDPOINT"
|
|
];
|
|
podOtlpEnv =
|
|
svc: unitEnv:
|
|
lib.optionalAttrs (svc.otlp == "hive" && otelCfg.collector.enable) (
|
|
lib.genAttrs (lib.filter (
|
|
n: n == "OTEL_EXPORTER_OTLP_ENDPOINT" || unitEnv ? ${n}
|
|
) otlpEndpointVars) (_: collectorEndpoint)
|
|
);
|
|
|
|
fail = name: msg: throw "services.hyperhive.k8s: ${name}: ${msg}";
|
|
|
|
# The names an object set carries that start with `hive-`, the prefix the
|
|
# forge and matrix services had as per-hive containers. Their workloads, and
|
|
# so their pods, must not bring it into the cluster. Read from the object
|
|
# keys, each object's name and its app label.
|
|
legacyPrefixed =
|
|
objs:
|
|
lib.filter (lib.hasPrefix "hive-") (
|
|
lib.attrNames objs
|
|
++ lib.concatMap (
|
|
o:
|
|
[ o.metadata.name ]
|
|
++ lib.optional (
|
|
o.metadata.labels."app.kubernetes.io/name" or null != null
|
|
) o.metadata.labels."app.kubernetes.io/name"
|
|
) (lib.attrValues objs)
|
|
);
|
|
|
|
# A unit's `ExecStart` as argv, split as systemd splits it: on spaces, with
|
|
# single quotes grouping a word (`lib.escapeShellArg` writes them) and `$$`
|
|
# standing for `$`. A pod's arguments are not expanded by a shell.
|
|
splitExec =
|
|
name: line:
|
|
let
|
|
quotes = w: lib.length (lib.splitString "'" w) - 1;
|
|
step =
|
|
st: w:
|
|
let
|
|
text = if st.open == null then w else "${st.open} ${w}";
|
|
in
|
|
if lib.mod (quotes text) 2 == 1 then
|
|
st // { open = text; }
|
|
else
|
|
{
|
|
open = null;
|
|
words = st.words ++ [ text ];
|
|
};
|
|
split = lib.foldl' step {
|
|
open = null;
|
|
words = [ ];
|
|
} (lib.filter (w: w != "") (lib.splitString " " line));
|
|
unquote =
|
|
w:
|
|
if lib.hasInfix "'\\''" w then
|
|
fail name "ExecStart has an argument with a single quote in it"
|
|
else
|
|
builtins.replaceStrings [ "'" "$$" ] [ "" "$" ] w;
|
|
in
|
|
if split.open != null then
|
|
fail name "ExecStart has an unterminated quote"
|
|
else
|
|
map unquote split.words;
|
|
|
|
labelsFor = name: {
|
|
"app.kubernetes.io/name" = name;
|
|
"app.kubernetes.io/part-of" = "hyperhive";
|
|
};
|
|
|
|
metaFor = name: {
|
|
inherit name;
|
|
inherit (k8sCfg) namespace;
|
|
labels = labelsFor name;
|
|
};
|
|
|
|
# The host services a pod's `egress` names, each the TCP port it is reached
|
|
# on at the bridge's address (./host-services.nix). The node trusts the pod
|
|
# network's interfaces, so a NetworkPolicy is the only thing that limits
|
|
# which of the host's ports a pod reaches. The identity provider is the
|
|
# gateway's vhost: `swarm.authelia.url` names no port.
|
|
hostPorts = {
|
|
store = baoDeployCfg.podListenerPort;
|
|
identity = 443;
|
|
queue = hyperhiveCfg.swarm.nats.port;
|
|
collector = hyperhiveCfg.swarm.hiveOtel.collectorPort;
|
|
};
|
|
|
|
# What the policy of a pod that reaches `reaches` allows: the cluster's DNS,
|
|
# those host ports, and the pods of the queue's load balancer where the queue
|
|
# runs in the cluster, because the `hostPort` they bind is forwarded to them
|
|
# before the policy sees the packet. The policy selects every pod of the
|
|
# service for ingress too and allows none, so only the node's own traffic
|
|
# (which the policy engine always admits) reaches it.
|
|
networkPolicyOf =
|
|
name: reaches:
|
|
let
|
|
tcp = port: {
|
|
protocol = "TCP";
|
|
inherit port;
|
|
};
|
|
queueOnCluster = natsCfg.enable;
|
|
in
|
|
{
|
|
apiVersion = "networking.k8s.io/v1";
|
|
kind = "NetworkPolicy";
|
|
metadata = metaFor name;
|
|
spec = {
|
|
podSelector.matchLabels = labelsFor name;
|
|
policyTypes = [
|
|
"Ingress"
|
|
"Egress"
|
|
];
|
|
egress = [
|
|
{
|
|
to = [
|
|
{
|
|
namespaceSelector.matchLabels."kubernetes.io/metadata.name" = "kube-system";
|
|
podSelector.matchLabels.k8s-app = "kube-dns";
|
|
}
|
|
];
|
|
ports = [
|
|
{
|
|
protocol = "UDP";
|
|
port = 53;
|
|
}
|
|
(tcp 53)
|
|
];
|
|
}
|
|
{
|
|
to = [ { ipBlock.cidr = "${hyperhiveCfg.network.bridgeIp}/32"; } ];
|
|
ports = map (r: tcp hostPorts.${r}) reaches;
|
|
}
|
|
]
|
|
++ lib.optional (queueOnCluster && lib.elem "queue" reaches) {
|
|
to = [
|
|
{
|
|
namespaceSelector.matchLabels."kubernetes.io/metadata.name" = "kube-system";
|
|
podSelector.matchLabels = {
|
|
"svccontroller.k3s.cattle.io/svcname" = "swarm-nats";
|
|
"svccontroller.k3s.cattle.io/svcnamespace" = k8sCfg.namespace;
|
|
};
|
|
}
|
|
];
|
|
ports = [ (tcp hostPorts.queue) ];
|
|
};
|
|
};
|
|
};
|
|
|
|
# The listener's Service, and the policy that lets only the node reach it. The
|
|
# cluster's policy engine (kube-router) admits traffic whose source is a local
|
|
# address of the node to any pod (`--src-type LOCAL`, the rule it labels "from
|
|
# local node"), and a policy that selects the pod for ingress and allows
|
|
# nothing refuses every other source. The gateway on the host dials the
|
|
# Service's name, so its connection reaches the pod from the node; a pod of
|
|
# the cluster does not.
|
|
listenerObjects = name: listener: {
|
|
"${name}/service" = {
|
|
apiVersion = "v1";
|
|
kind = "Service";
|
|
metadata = metaFor name;
|
|
spec = {
|
|
type = "ClusterIP";
|
|
selector = labelsFor name;
|
|
ports = [
|
|
{
|
|
name = "api";
|
|
protocol = "TCP";
|
|
port = listener.port;
|
|
targetPort = "api";
|
|
}
|
|
];
|
|
};
|
|
};
|
|
"${name}/networkpolicy" = {
|
|
apiVersion = "networking.k8s.io/v1";
|
|
kind = "NetworkPolicy";
|
|
metadata = metaFor name;
|
|
spec = {
|
|
podSelector.matchLabels = labelsFor name;
|
|
policyTypes = [ "Ingress" ];
|
|
};
|
|
};
|
|
};
|
|
|
|
# systemd duration "<n>min", the only form these units use.
|
|
minutesOf =
|
|
name: what: value:
|
|
let
|
|
m = builtins.match "([0-9]+)min" value;
|
|
in
|
|
if m == null then
|
|
fail name "${what} is \"${value}\"; only \"<n>min\" translates"
|
|
else
|
|
lib.toInt (lib.head m);
|
|
|
|
# A unit's memory setting `what` as a Kubernetes quantity. systemd's K, M, G
|
|
# and T are powers of 1024, as Kubernetes' Ki, Mi, Gi and Ti are. `infinity`
|
|
# is `null`, which a limit reads as no limit and a request refuses.
|
|
memoryOf =
|
|
what: name: value:
|
|
let
|
|
v = toString value;
|
|
m = builtins.match "([0-9]+)([KMGT]?)" v;
|
|
in
|
|
if v == "infinity" then
|
|
null
|
|
else if m == null then
|
|
fail name "${what} is \"${v}\"; only a byte count, optionally with the suffix K, M, G or T, translates"
|
|
else
|
|
lib.head m
|
|
+ {
|
|
"" = "";
|
|
K = "Ki";
|
|
M = "Mi";
|
|
G = "Gi";
|
|
T = "Ti";
|
|
}
|
|
.${lib.last m};
|
|
|
|
memoryLimitOf = memoryOf "MemoryMax";
|
|
|
|
# A unit's `MemoryMin`, else its `MemoryLow`, as a container's memory
|
|
# request: the memory systemd keeps for the unit. A unit that sets neither
|
|
# reserves none, which is `0`.
|
|
memoryRequestOf =
|
|
name: sc:
|
|
let
|
|
what = if sc ? MemoryMin then "MemoryMin" else "MemoryLow";
|
|
v = memoryOf what name sc.${what};
|
|
in
|
|
if !(sc ? MemoryMin || sc ? MemoryLow) then
|
|
"0"
|
|
else if v == null then
|
|
fail name "${what} is \"infinity\"; only a byte count, optionally with the suffix K, M, G or T, translates"
|
|
else
|
|
v;
|
|
|
|
# A unit's `CPUQuota`, a percent of one core, as a container's cpu limit in
|
|
# millicores.
|
|
cpuLimitOf =
|
|
name: value:
|
|
let
|
|
v = toString value;
|
|
m = builtins.match "([0-9]+)%" v;
|
|
in
|
|
if m == null then
|
|
fail name "CPUQuota is \"${v}\"; only \"<n>%\" translates"
|
|
else
|
|
"${toString (lib.toInt (lib.head m) * 10)}m";
|
|
|
|
workload =
|
|
name: svc:
|
|
let
|
|
inherit (svc) unit;
|
|
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;
|
|
|
|
credDir = "/run/credentials/${daemon}.service";
|
|
# `LoadCredential` entries are `id:source` on the host and a bare `id`
|
|
# inside a container. Only the id is rendered.
|
|
unitCredIds = map (e: lib.head (lib.splitString ":" e)) (lib.toList (sc.LoadCredential or [ ]));
|
|
|
|
runtimeDir = if sc ? RuntimeDirectory then "/run/${sc.RuntimeDirectory}" else null;
|
|
stateDir = if sc ? StateDirectory then "/var/lib/${sc.StateDirectory}" else null;
|
|
ephemeral = svc.ephemeralState or false;
|
|
localState = svc.localState or null;
|
|
stateClaim = if localState != null then "${name}-store" else "${name}-state";
|
|
|
|
# PATH holds only NixOS's default tools (checked below), which the image
|
|
# does not carry. `%d` is systemd's specifier for the credential
|
|
# directory.
|
|
unitEnv = lib.mapAttrs (_: v: builtins.replaceStrings [ "%d" ] [ credDir ] (toString v)) (
|
|
lib.filterAttrs (n: v: v != null && n != "PATH") unit.environment
|
|
);
|
|
|
|
# A service the store knows by a jwt role as well as by its certificate
|
|
# logs in with its pod's ServiceAccount token: the pod holds no client
|
|
# certificate. It reaches the store on the listener that asks for none
|
|
# (`deploy.bao.podListenerPort`), by the name every reader dials.
|
|
baoLogin = lib.elem baoRole baoDeployCfg.k8sPrincipals && unitEnv ? BAO_CLIENT_CERT;
|
|
baoClientCredIds =
|
|
map
|
|
(
|
|
var:
|
|
let
|
|
v = unitEnv.${var} or "";
|
|
in
|
|
if under credDir v then
|
|
lib.removePrefix "${credDir}/" v
|
|
else
|
|
fail name "${var} is not a credential of the unit, which the pod's login drops"
|
|
)
|
|
[
|
|
"BAO_CLIENT_CERT"
|
|
"BAO_CLIENT_KEY"
|
|
];
|
|
credIds = if baoLogin then lib.subtractLists baoClientCredIds unitCredIds else unitCredIds;
|
|
baoEnv = {
|
|
BAO_ADDR = "https://${hyperhiveCfg.swarm.bao.domain}:${toString baoDeployCfg.podListenerPort}";
|
|
BAO_AUTH = "jwt";
|
|
BAO_JWT_FILE = podAuth.tokenFile;
|
|
BAO_JWT_ROLE = baoRole;
|
|
BAO_JWT_MOUNT = podAuth.mount;
|
|
};
|
|
|
|
# Trust bundles (../lib/hive-ca-trust.nix, ../hive-tls.nix): system roots
|
|
# plus the hive CA, assembled at runtime, so the cluster holds the one
|
|
# bundle as a ConfigMap and each path the unit names mounts it.
|
|
caFiles = lib.unique (
|
|
lib.filter (v: lib.hasPrefix "/" v && baseNameOf v == trustBundleKey) (lib.attrValues unitEnv)
|
|
);
|
|
|
|
env =
|
|
(
|
|
if baoLogin then
|
|
removeAttrs unitEnv [
|
|
"BAO_CLIENT_CERT"
|
|
"BAO_CLIENT_KEY"
|
|
]
|
|
// baoEnv
|
|
else
|
|
unitEnv
|
|
)
|
|
// podOtlpEnv svc unitEnv
|
|
// lib.optionalAttrs (runtimeDir != null) { RUNTIME_DIRECTORY = runtimeDir; }
|
|
// lib.optionalAttrs (stateDir != null) { STATE_DIRECTORY = stateDir; }
|
|
// lib.optionalAttrs (svc.healthEnv != null) {
|
|
${svc.healthEnv} = "127.0.0.1:${toString healthPort}";
|
|
};
|
|
|
|
mountRoots = [
|
|
credDir
|
|
"/nix/store"
|
|
]
|
|
++ caFiles
|
|
++ lib.optional baoLogin podAuth.tokenDir
|
|
++ lib.optional (runtimeDir != null) runtimeDir
|
|
++ lib.optional (stateDir != null) stateDir
|
|
++ lib.attrNames publicFiles
|
|
++ 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;
|
|
missingCreds = lib.filterAttrs (
|
|
_: v: under credDir v && !(lib.elem (lib.removePrefix "${credDir}/" v) credIds)
|
|
) env;
|
|
|
|
# Store paths the environment names go into the image by way of a file
|
|
# that lists them, so the pod finds every path the unit finds.
|
|
storeValues = lib.filter (v: lib.hasInfix "/nix/store/" v) (lib.attrValues env);
|
|
image = mkServiceImage {
|
|
inherit name;
|
|
inherit (svc) package;
|
|
bin = daemon;
|
|
extraContents =
|
|
lib.optional (storeValues != [ ]) (
|
|
pkgs.writeTextDir "share/hyperhive/${name}.env-refs" (lib.concatLines storeValues)
|
|
)
|
|
++ lib.optional (svc.healthEnv != null) wgetOnly;
|
|
};
|
|
|
|
# A systemd `%d` in an argument is the credential directory, as in the
|
|
# environment.
|
|
execWords = map (builtins.replaceStrings [ "%d" ] [ credDir ]) (
|
|
splitExec name (toString sc.ExecStart)
|
|
);
|
|
entrypoint = "${svc.package}/bin/${daemon}";
|
|
|
|
# The credentials that are public CA files come from the CA ConfigMap, the
|
|
# rest from the service's Secret. A volume holding both is a projected
|
|
# one, which merges them into the one directory the unit's credentials
|
|
# are in.
|
|
publicIds = lib.filter (id: svc.publicCredentials ? ${id}) credIds;
|
|
secretIds = lib.subtractLists publicIds credIds;
|
|
# 0440: the pod's group reads them, as `LoadCredential` lets the unit's
|
|
# user read them.
|
|
credentialsMode = 288;
|
|
credentialItems = map (id: {
|
|
key = id;
|
|
path = id;
|
|
});
|
|
credentialsVolume =
|
|
if publicIds == [ ] then
|
|
{
|
|
name = "credentials";
|
|
secret = {
|
|
secretName = "${name}-credentials";
|
|
defaultMode = credentialsMode;
|
|
items = credentialItems credIds;
|
|
};
|
|
}
|
|
else
|
|
{
|
|
name = "credentials";
|
|
projected = {
|
|
defaultMode = credentialsMode;
|
|
sources =
|
|
lib.optional (secretIds != [ ]) {
|
|
secret = {
|
|
name = "${name}-credentials";
|
|
items = credentialItems secretIds;
|
|
};
|
|
}
|
|
++ [
|
|
{
|
|
configMap = {
|
|
name = caConfigMap;
|
|
items = map (id: {
|
|
key = svc.publicCredentials.${id};
|
|
path = id;
|
|
}) publicIds;
|
|
};
|
|
}
|
|
];
|
|
};
|
|
};
|
|
|
|
volumes =
|
|
lib.optional (credIds != [ ]) credentialsVolume
|
|
++ lib.optional baoLogin {
|
|
name = "bao-token";
|
|
projected = {
|
|
# 0440, as the credentials: the pod's group reads the token.
|
|
defaultMode = 288;
|
|
sources = [
|
|
{
|
|
serviceAccountToken = {
|
|
audience = podAuth.audience;
|
|
# The shortest the API server grants. The kubelet refreshes
|
|
# the file before it expires, and a login reads it afresh.
|
|
expirationSeconds = 600;
|
|
path = "token";
|
|
};
|
|
}
|
|
];
|
|
};
|
|
}
|
|
++ lib.optional (!(caFiles == [ ] && publicFiles == { })) {
|
|
name = "ca-trust";
|
|
configMap.name = caConfigMap;
|
|
}
|
|
++ lib.optional listenerTls {
|
|
name = "tls";
|
|
# In memory: the leaf's key never reaches the node's disk.
|
|
emptyDir.medium = "Memory";
|
|
}
|
|
++ lib.optional (runtimeDir != null) {
|
|
name = "runtime";
|
|
# In memory, as the `/run` it stands for is: what a service keeps there
|
|
# never reaches the node's disk.
|
|
emptyDir.medium = "Memory";
|
|
}
|
|
++ lib.optional (stateDir != null) (
|
|
{
|
|
name = "state";
|
|
}
|
|
// (if ephemeral then { emptyDir = { }; } else { persistentVolumeClaim.claimName = stateClaim; })
|
|
)
|
|
++ lib.optional (svc.etcFiles != [ ]) {
|
|
name = "etc";
|
|
configMap.name = "${name}-etc";
|
|
}
|
|
++ [
|
|
{
|
|
name = "tmp";
|
|
emptyDir = { };
|
|
}
|
|
];
|
|
|
|
etcKey = f: builtins.replaceStrings [ "/" ] [ "_" ] f;
|
|
tlsMount = {
|
|
name = "tls";
|
|
mountPath = listener.tlsDir;
|
|
};
|
|
|
|
volumeMounts =
|
|
lib.optional (credIds != [ ]) {
|
|
name = "credentials";
|
|
mountPath = credDir;
|
|
readOnly = true;
|
|
}
|
|
++ lib.optional baoLogin {
|
|
name = "bao-token";
|
|
mountPath = podAuth.tokenDir;
|
|
readOnly = true;
|
|
}
|
|
++ map (f: {
|
|
name = "ca-trust";
|
|
mountPath = f;
|
|
subPath = trustBundleKey;
|
|
readOnly = true;
|
|
}) caFiles
|
|
++ map (path: {
|
|
name = "ca-trust";
|
|
mountPath = path;
|
|
subPath = publicFiles.${path};
|
|
readOnly = true;
|
|
}) (lib.attrNames publicFiles)
|
|
++ lib.optional listenerTls tlsMount
|
|
++ lib.optional (runtimeDir != null) {
|
|
name = "runtime";
|
|
mountPath = runtimeDir;
|
|
}
|
|
++ lib.optional (stateDir != null) {
|
|
name = "state";
|
|
mountPath = stateDir;
|
|
}
|
|
++ map (f: {
|
|
name = "etc";
|
|
mountPath = "/etc/${f}";
|
|
subPath = etcKey f;
|
|
readOnly = true;
|
|
}) svc.etcFiles
|
|
++ [
|
|
{
|
|
name = "tmp";
|
|
mountPath = "/tmp";
|
|
}
|
|
];
|
|
|
|
# The unit's memory and CPU ceilings are the container's limits. They are
|
|
# caps, not reservations, so the requests are explicit: Kubernetes sets
|
|
# an unset request to the limit, and the pod would reserve the whole cap
|
|
# on the node. The memory request is what the unit asks systemd to keep
|
|
# (`MemoryMin`, else `MemoryLow`), and the cpu request is `0`, since
|
|
# `CPUQuota` reserves nothing. The pod is then Burstable. The unit's other
|
|
# resource settings have no pod field and stay on the host: `TasksMax`
|
|
# has no counterpart (the node's kubelet sets the pids limit), and the pod
|
|
# keeps the one security shape every pod has, in place of the sandbox
|
|
# settings (`MemoryDenyWriteExecute`, `SystemCallFilter`, `PrivateUsers`,
|
|
# ...).
|
|
limits =
|
|
lib.optionalAttrs (sc ? MemoryMax && memoryLimitOf name sc.MemoryMax != null) {
|
|
memory = memoryLimitOf name sc.MemoryMax;
|
|
}
|
|
// lib.optionalAttrs (sc ? CPUQuota) { cpu = cpuLimitOf name sc.CPUQuota; };
|
|
requests = {
|
|
memory = memoryRequestOf name sc;
|
|
cpu = "0";
|
|
};
|
|
|
|
# The listener's Service targets this port by its name. The health
|
|
# listener is not a port: it binds to the pod's loopback.
|
|
ports = lib.optional (listener != { }) {
|
|
name = "api";
|
|
containerPort = listener.port;
|
|
};
|
|
|
|
container = {
|
|
inherit name volumeMounts;
|
|
image = "${image.imageName}:${image.imageTag}";
|
|
# A node without the image pulls it from a peer that holds it
|
|
# (the mirror in ./node.nix); the name's host resolves nowhere else.
|
|
imagePullPolicy = "IfNotPresent";
|
|
env = lib.mapAttrsToList (n: v: {
|
|
name = n;
|
|
value = v;
|
|
}) env;
|
|
securityContext = {
|
|
allowPrivilegeEscalation = false;
|
|
readOnlyRootFilesystem = true;
|
|
runAsNonRoot = true;
|
|
capabilities.drop = [ "ALL" ];
|
|
};
|
|
}
|
|
// lib.optionalAttrs (limits != { } || sc ? MemoryMin || sc ? MemoryLow) {
|
|
resources = {
|
|
inherit requests;
|
|
}
|
|
// lib.optionalAttrs (limits != { }) { inherit limits; };
|
|
}
|
|
// 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;
|
|
};
|
|
}
|
|
# The liveness and readiness probes wait for this one to succeed once.
|
|
// lib.optionalAttrs (svc.probe.startupFailureThreshold or null != null) {
|
|
startupProbe = {
|
|
httpGet = {
|
|
inherit (svc.probe) path;
|
|
port = "api";
|
|
};
|
|
periodSeconds = 10;
|
|
failureThreshold = svc.probe.startupFailureThreshold;
|
|
};
|
|
}
|
|
// lib.optionalAttrs (svc.healthEnv != null) {
|
|
livenessProbe = loopbackProbe healthPort "/healthz";
|
|
readinessProbe = loopbackProbe healthPort "/readyz";
|
|
};
|
|
|
|
# The listener's leaf: issued before the daemon starts, renewed beside it.
|
|
# Both log in as the pod's account, so they hold the token volume the
|
|
# daemon's login uses, and the store's CA from the credentials volume.
|
|
leafImage = mkServiceImage {
|
|
name = "${name}-tls";
|
|
package = leafImagePackage;
|
|
bin = leafIssueBin;
|
|
};
|
|
# What the service adds to the daemon's pod.
|
|
extra = {
|
|
containers = [ ];
|
|
initContainers = [ ];
|
|
volumes = [ ];
|
|
hostAliases = [ ];
|
|
podSpec = { };
|
|
objects = { };
|
|
images = [ ];
|
|
}
|
|
// lib.optionalAttrs (svc ? pod) (
|
|
svc.pod {
|
|
inherit env volumeMounts metaFor;
|
|
inherit (container) securityContext;
|
|
}
|
|
);
|
|
|
|
leafContainer = {
|
|
name = "tls-issue";
|
|
image = "${leafImage.imageName}:${leafImage.imageTag}";
|
|
imagePullPolicy = "IfNotPresent";
|
|
env =
|
|
lib.mapAttrsToList
|
|
(n: v: {
|
|
name = n;
|
|
value = v;
|
|
})
|
|
(
|
|
lib.filterAttrs (
|
|
n: _:
|
|
lib.elem n [
|
|
"BAO_ADDR"
|
|
"BAO_CACERT"
|
|
]
|
|
) env
|
|
// {
|
|
HOME = "/tmp";
|
|
}
|
|
);
|
|
volumeMounts = lib.filter (
|
|
m:
|
|
lib.elem m.name [
|
|
"credentials"
|
|
"bao-token"
|
|
"tls"
|
|
"tmp"
|
|
]
|
|
) volumeMounts;
|
|
inherit (container) securityContext;
|
|
};
|
|
|
|
podSpec = {
|
|
inherit terminationGracePeriodSeconds;
|
|
volumes = volumes ++ extra.volumes;
|
|
containers = [
|
|
container
|
|
]
|
|
++ lib.optional listenerTls (
|
|
leafContainer
|
|
// {
|
|
name = "tls-renew";
|
|
command = [ "/bin/${leafRenewBin}" ];
|
|
}
|
|
)
|
|
++ extra.containers;
|
|
# The API token is never mounted; a pod that logs in to the store gets
|
|
# a token of its own, projected for the store's audience.
|
|
automountServiceAccountToken = false;
|
|
enableServiceLinks = false;
|
|
securityContext = {
|
|
runAsUser = serviceUser.uid;
|
|
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 (listenerTls || extra.initContainers != [ ]) {
|
|
initContainers = lib.optional listenerTls leafContainer ++ extra.initContainers;
|
|
}
|
|
// lib.optionalAttrs (extra.hostAliases != [ ]) { inherit (extra) hostAliases; }
|
|
// extra.podSpec;
|
|
|
|
# What the `-etc` ConfigMap holds. A file mounted from it by `subPath`
|
|
# never sees a later change, so the pod template carries a hash of the
|
|
# content: a changed file changes the template, and the Deployment rolls.
|
|
etcData = lib.listToAttrs (
|
|
map (
|
|
f:
|
|
let
|
|
e = config.environment.etc.${f};
|
|
in
|
|
lib.nameValuePair (etcKey f) (
|
|
if e.text != null then e.text else fail name "/etc/${f} has no `text` to put in a ConfigMap"
|
|
)
|
|
) svc.etcFiles
|
|
);
|
|
|
|
podTemplate = restartPolicy: {
|
|
metadata = {
|
|
labels = labelsFor name;
|
|
}
|
|
// lib.optionalAttrs (svc.etcFiles != [ ]) {
|
|
annotations."checksum/etc" = builtins.hashString "sha256" (builtins.toJSON etcData);
|
|
};
|
|
spec = podSpec // {
|
|
inherit restartPolicy;
|
|
};
|
|
};
|
|
|
|
main =
|
|
if svc.kind == "Deployment" then
|
|
{
|
|
apiVersion = "apps/v1";
|
|
kind = "Deployment";
|
|
metadata = metaFor name;
|
|
spec = {
|
|
replicas = 1;
|
|
# One instance per swarm, as one unit per swarm runs today: the
|
|
# old pod is gone before the new one starts.
|
|
strategy.type = "Recreate";
|
|
selector.matchLabels = labelsFor name;
|
|
template = podTemplate "Always";
|
|
};
|
|
}
|
|
else
|
|
let
|
|
every = minutesOf name "the timer's OnUnitInactiveSec" svc.timer.timerConfig.OnUnitInactiveSec;
|
|
in
|
|
{
|
|
apiVersion = "batch/v1";
|
|
kind = "CronJob";
|
|
metadata = metaFor name;
|
|
spec = {
|
|
schedule = "*/${toString every} * * * *";
|
|
# The timer counts from the end of the last run, so runs never
|
|
# overlap.
|
|
concurrencyPolicy = "Forbid";
|
|
jobTemplate.spec = {
|
|
# A failed oneshot waits for the next timer run.
|
|
backoffLimit = 0;
|
|
activeDeadlineSeconds = 60 * minutesOf name "TimeoutStartSec" sc.TimeoutStartSec;
|
|
template = podTemplate "Never";
|
|
};
|
|
};
|
|
};
|
|
|
|
objects = {
|
|
"${name}/${lib.toLower svc.kind}" = main;
|
|
}
|
|
// extra.objects
|
|
// lib.optionalAttrs (svc ? egress) {
|
|
"${name}/networkpolicy" = networkPolicyOf name svc.egress;
|
|
}
|
|
// 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" = {
|
|
apiVersion = "v1";
|
|
kind = "ServiceAccount";
|
|
metadata = metaFor name;
|
|
automountServiceAccountToken = false;
|
|
};
|
|
}
|
|
// lib.optionalAttrs (stateDir != null && !ephemeral) {
|
|
"${name}/persistentvolumeclaim" = {
|
|
apiVersion = "v1";
|
|
kind = "PersistentVolumeClaim";
|
|
metadata = metaFor stateClaim;
|
|
spec = {
|
|
accessModes = [ "ReadWriteOnce" ];
|
|
resources.requests.storage = "1Gi";
|
|
}
|
|
// lib.optionalAttrs (localState != null) {
|
|
storageClassName = stateClaim;
|
|
volumeName = stateClaim;
|
|
};
|
|
};
|
|
}
|
|
// lib.optionalAttrs (stateDir != null && !ephemeral && localState != null) {
|
|
"${name}/persistentvolume" = {
|
|
apiVersion = "v1";
|
|
kind = "PersistentVolume";
|
|
# Cluster-scoped: no namespace.
|
|
metadata = removeAttrs (metaFor stateClaim) [ "namespace" ];
|
|
spec = {
|
|
capacity.storage = "1Gi";
|
|
accessModes = [ "ReadWriteOnce" ];
|
|
persistentVolumeReclaimPolicy = "Retain";
|
|
storageClassName = stateClaim;
|
|
local.path = localState.hostDir;
|
|
nodeAffinity = labels.stateAffinity localState.service;
|
|
};
|
|
};
|
|
}
|
|
// lib.optionalAttrs (svc.etcFiles != [ ]) {
|
|
"${name}/configmap" = {
|
|
apiVersion = "v1";
|
|
kind = "ConfigMap";
|
|
metadata = metaFor "${name}-etc";
|
|
data = etcData;
|
|
};
|
|
};
|
|
in
|
|
if legacyPrefixed objects != [ ] then
|
|
fail name "names ${lib.concatStringsSep ", " (lib.unique (legacyPrefixed objects))}, which start with the legacy `hive-` prefix"
|
|
else if !(lib.all (p: lib.elem (lib.getName p) nixosDefaultPath) unit.path) then
|
|
fail name "the unit puts packages on PATH, which the image does not carry"
|
|
else if svc.otlp == "own" && !(lib.any (n: unitEnv ? ${n}) otlpEndpointVars) then
|
|
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 lib.head execWords != entrypoint then
|
|
fail name "ExecStart is not ${entrypoint} with plain arguments"
|
|
else if lib.any (w: lib.hasInfix "\"" w) execWords then
|
|
fail name "ExecStart has double-quoted arguments, which the split on spaces would break"
|
|
else if unmounted != { } then
|
|
fail name "the pod mounts nothing at the path ${lib.concatStringsSep ", " (lib.attrNames unmounted)} names"
|
|
else if missingCreds != { } then
|
|
fail name "${lib.concatStringsSep ", " (lib.attrNames missingCreds)} names a credential the unit does not load"
|
|
else
|
|
{
|
|
inherit objects image;
|
|
# What the pod's other containers run.
|
|
extraImages = lib.optional listenerTls leafImage ++ extra.images;
|
|
};
|
|
|
|
enabled = lib.mapAttrs workload (lib.filterAttrs (_: svc: svc.enable) services);
|
|
in
|
|
{
|
|
objects = {
|
|
"namespace" = {
|
|
apiVersion = "v1";
|
|
kind = "Namespace";
|
|
metadata = {
|
|
name = k8sCfg.namespace;
|
|
labels = {
|
|
"app.kubernetes.io/part-of" = "hyperhive";
|
|
# The API server refuses a pod that breaks Pod Security `restricted` (a
|
|
# host port, root, a kept capability, ...), and warns on and audits a
|
|
# workload whose pods would. The level is the cluster's own version.
|
|
"pod-security.kubernetes.io/enforce" = "restricted";
|
|
"pod-security.kubernetes.io/warn" = "restricted";
|
|
"pod-security.kubernetes.io/audit" = "restricted";
|
|
};
|
|
};
|
|
};
|
|
}
|
|
# Every pod of the namespace is selected for ingress and no rule admits
|
|
# anyone, so a pod is reachable from the node alone until a policy of its own
|
|
# admits more. The cluster's policy engine takes the union of the policies
|
|
# that select a pod and always admits the node's own addresses, so the
|
|
# host's gateway still reaches every pod. A port a pod
|
|
# opens later is closed to the other pods and to the hive bridge without a
|
|
# line here.
|
|
// {
|
|
"default-deny-ingress/networkpolicy" = {
|
|
apiVersion = "networking.k8s.io/v1";
|
|
kind = "NetworkPolicy";
|
|
metadata = {
|
|
name = "default-deny-ingress";
|
|
inherit (k8sCfg) namespace;
|
|
labels."app.kubernetes.io/part-of" = "hyperhive";
|
|
};
|
|
spec = {
|
|
podSelector = { };
|
|
policyTypes = [ "Ingress" ];
|
|
};
|
|
};
|
|
}
|
|
// lib.concatMapAttrs (_: w: w.objects) enabled;
|
|
|
|
# The image each enabled service's pod runs: what the main node imports,
|
|
# for the others to pull from it.
|
|
images = lib.unique (lib.concatMap (w: [ w.image ] ++ w.extraImages) (lib.attrValues enabled));
|
|
|
|
# What ./runtime.nix applies. `serviceNames` and `userNamespaces` are cheap to
|
|
# read: they force no unit, which ./runtime.nix's own units depend on.
|
|
# `services` holds the objects. `caSources` is the host file behind each key of
|
|
# the CA ConfigMap, null where there is none.
|
|
serviceNames = lib.attrNames (lib.filterAttrs (_: svc: svc.enable) services);
|
|
|
|
userNamespaces = lib.attrNames (
|
|
lib.filterAttrs (_: svc: svc.enable && svc ? hostUsers && !svc.hostUsers) services
|
|
);
|
|
services = lib.mapAttrs (_: w: { inherit (w) objects; }) enabled;
|
|
inherit caConfigMap caSources legacyPrefixed;
|
|
}
|