Watch
0
0
Fork
You've already forked hyperhive
0

k8s: deploy.stt.runtime moves the speech-to-text service between its container and the cluster

This commit is contained in:
atlas 2026-11-21 23:12:09 +01:00 • committed by maia
commit 4b4df16e52
4 changed files with 537 additions and 193 deletions

View file

@ -98,6 +98,18 @@ let
hostUnit = "container@swarm-notify-router.service"; hostUnit = "container@swarm-notify-router.service";
}; };
}; };
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;
switch = {
inherit (deployCfg.stt) runtime;
hostUnit = "container@swarm-stt.service";
};
};
swarm-ci-metrics = { swarm-ci-metrics = {
inherit (deployCfg.ci-metrics) enable package; inherit (deployCfg.ci-metrics) enable package;
unit = config.systemd.services.swarm-ci-metrics; unit = config.systemd.services.swarm-ci-metrics;
@ -153,6 +165,43 @@ let
else else
lib.toInt (lib.head m); lib.toInt (lib.head m);
# A unit's `MemoryMax` as a container's memory limit. systemd's K, M, G and T
# are powers of 1024, as Kubernetes' Ki, Mi, Gi and Ti are. `infinity` is no
# limit.
memoryLimitOf =
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 "MemoryMax 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};
# 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 = workload =
name: svc: name: svc:
let let
@ -390,6 +439,19 @@ let
} }
]; ];
# The unit's memory and CPU ceilings are the container's limits. 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`, ...). No `requests` are set, so Kubernetes reserves the
# limits on the node.
limits =
lib.optionalAttrs (sc ? MemoryMax && memoryLimitOf name sc.MemoryMax != null) {
memory = memoryLimitOf name sc.MemoryMax;
}
// lib.optionalAttrs (sc ? CPUQuota) { cpu = cpuLimitOf name sc.CPUQuota; };
container = { container = {
inherit name volumeMounts; inherit name volumeMounts;
image = "${image.imageName}:${image.imageTag}"; image = "${image.imageName}:${image.imageTag}";
@ -406,6 +468,7 @@ let
capabilities.drop = [ "ALL" ]; capabilities.drop = [ "ALL" ];
}; };
} }
// lib.optionalAttrs (limits != { }) { resources = { inherit limits; }; }
// lib.optionalAttrs (lib.tail execWords != [ ]) { args = lib.tail execWords; } // lib.optionalAttrs (lib.tail execWords != [ ]) { args = lib.tail execWords; }
// lib.optionalAttrs (svc.healthEnv != null) { // lib.optionalAttrs (svc.healthEnv != null) {
ports = [ ports = [

View file

@ -411,7 +411,8 @@ let
# is written by `swarm-bao-controller-policy`. Each one's jwt role takes the # is written by `swarm-bao-controller-policy`. Each one's jwt role takes the
# principal's name, policy and token lifetimes, and its ServiceAccount is # principal's name, policy and token lifetimes, and its ServiceAccount is
# named after it (../k8s/render.nix renders the pod under that account). # named after it (../k8s/render.nix renders the pod under that account).
k8sPrincipals = notifyRouterReaders ++ ciMetricsReaders ++ [ { name = controllerPolicyName; } ]; k8sPrincipals =
notifyRouterReaders ++ sttReaders ++ ciMetricsReaders ++ [ { name = controllerPolicyName; } ];
# The jwt role of one principal: the token of exactly its ServiceAccount, for # The jwt role of one principal: the token of exactly its ServiceAccount, for
# this store's audience. Both the subject and the audience are bound, so a # this store's audience. Both the subject and the audience are bound, so a

View file

@ -3,7 +3,9 @@
# where the host has the service's store identity. It answers the voice memos # where the host has the service's store identity. It answers the voice memos
# agents send on `$SWARM.stt.transcribe.<agent>` with whisper.cpp, once per memo # agents send on `$SWARM.stt.transcribe.<agent>` with whisper.cpp, once per memo
# (the cache is keyed by the audio's hash). Run it where the inference hardware # (the cache is keyed by the audio's hash). Run it where the inference hardware
# is. docs/4-implementation/swarm/stt.md has the design. # is. docs/4-implementation/swarm/stt.md has the design. With
# `deploy.stt.runtime = "k8s"` it runs as a pod instead, rendered from the unit
# below (docs/4-implementation/k8s/runtime.md).
# #
# The audio comes from rooms with outside people, so the daemon runs as its own # The audio comes from rooms with outside people, so the daemon runs as its own
# unprivileged user under a tight systemd sandbox (see `serviceConfig` below), # unprivileged user under a tight systemd sandbox (see `serviceConfig` below),
@ -106,6 +108,168 @@ let
url = "https://huggingface.co/ggerganov/whisper.cpp/resolve/main/ggml-${settings.modelSize}.bin"; url = "https://huggingface.co/ggerganov/whisper.cpp/resolve/main/ggml-${settings.modelSize}.bin";
hash = modelHashes.${settings.modelSize}; hash = modelHashes.${settings.modelSize};
}; };
onK8s = cfg.runtime == "k8s";
# The module the container runs: its own NixOS system on the host's bridge,
# or, with the service on the cluster, only the source of the unit the pod is
# rendered from (`deploy.stt.unit`).
containerConfig =
{ lib, ... }:
{
imports = [
../container-modules/swarm-container.nix
../container-modules/swarm-journal-forwarder.nix
caBundleModule
];
services.hyperhive.swarmContainer = {
inherit privateNetwork;
writesOwnResolvConf = false;
};
networking.nameservers = [ networkCfg.bridgeIp ];
networking.interfaces.eth0.useDHCP = true;
users.users.${unit} = {
isSystemUser = true;
group = unit;
};
users.groups.${unit} = { };
# Authenticated as the daemon's own OIDC client, whose secret its
# store identity already reads: one identity for the whole container.
services.hyperhive.swarmJournalForwarder = {
enable = true;
serviceName = "stt";
endpoint = forwarderEndpoint;
inherit clientId;
tokenUrl = "${autheliaCfg.url}/api/oidc/token";
telemetryPort = forwarderTelemetryPort;
otlpMetricsPort = forwarderOtlpPort;
store = {
package = baoDeploy.package;
addr = "https://${baoCfg.domain}:${toString baoCfg.port}";
secretPath = "secret/swarm/services/${clientId}/oidc/client";
clientCertFile = forwarderCredential "stt-bao-cert";
clientKeyFile = forwarderCredential "stt-bao-key";
caFile = if storeFiles ? stt-bao-server-ca then forwarderCredential "stt-bao-server-ca" else null;
};
};
systemd.services.${forwarderUnit}.serviceConfig.LoadCredential = lib.attrNames storeFiles;
systemd.services.${unit} = {
description = "transcribe voice memos";
wantedBy = [ "multi-user.target" ];
wants = [ "network-online.target" ];
after = [ "network-online.target" ];
environment = {
BAO_ADDR = "https://${baoCfg.domain}:${toString baoCfg.port}";
BAO_CLIENT_CERT = credential "stt-bao-cert";
BAO_CLIENT_KEY = credential "stt-bao-key";
SWARM_STT_STATE_DIR = "/var/lib/${unit}";
SWARM_STT_FFMPEG = "${pkgs.ffmpeg-headless}/bin/ffmpeg";
SWARM_STT_WHISPER_CLI = "${pkgs.whisper-cpp}/bin/whisper-cli";
SWARM_STT_MODEL = "${model}";
SWARM_STT_CACHE_TTL_SECS = toString settings.cacheTtlSecs;
SWARM_STT_MAX_WAITING = toString settings.maxWaiting;
SWARM_STT_RUN_TIMEOUT_SECS = toString settings.runTimeoutSecs;
SWARM_STT_MAX_AUDIO_SECS = toString settings.maxAudioSecs;
SWARM_STT_MAX_BYTES = toString settings.maxBytes;
SWARM_STT_NATS_URL = "tls://${natsCfg.domain}:${toString natsCfg.port}";
SWARM_STT_OIDC_TOKEN_ENDPOINT = "${autheliaCfg.url}/api/oidc/token";
SWARM_STT_OIDC_CLIENT_ID = clientId;
OTEL_EXPORTER_OTLP_ENDPOINT = "http://127.0.0.1:${toString forwarderOtlpPort}";
OTEL_EXPORTER_OTLP_PROTOCOL = "http/protobuf";
OTEL_RESOURCE_ATTRIBUTES = "service.name=hyperhive-stt,swarm=${
if hyperhiveCfg.swarm.name == null then "unknown" else hyperhiveCfg.swarm.name
}";
}
// lib.optionalAttrs (storeFiles ? stt-bao-server-ca) {
BAO_CACERT = credential "stt-bao-server-ca";
}
// lib.optionalAttrs caTrust.useSelfSigned {
SWARM_STT_OIDC_CA_FILE = caTrust.bundlePathFor machine;
};
serviceConfig = {
ExecStart = "${cfg.package}/bin/swarm-stt";
User = unit;
Group = unit;
UMask = "0077";
# Bare ids: the system credentials nspawn handed in.
LoadCredential = lib.attrNames storeFiles;
Restart = "on-failure";
RestartSec = "10s";
SyslogIdentifier = unit;
# The sandbox for a service that decodes files strangers sent:
# the only writable path is its state directory, it sees no
# other user's processes or devices, and cannot gain
# privileges. It does NOT limit the network (see the header).
StateDirectory = unit;
StateDirectoryMode = "0700";
NoNewPrivileges = true;
ProtectSystem = "strict";
ProtectHome = true;
PrivateTmp = true;
PrivateDevices = true;
PrivateUsers = true;
ProtectKernelTunables = true;
ProtectKernelModules = true;
ProtectKernelLogs = true;
ProtectControlGroups = true;
ProtectClock = true;
ProtectHostname = true;
ProtectProc = "invisible";
ProcSubset = "pid";
RestrictNamespaces = true;
RestrictRealtime = true;
RestrictSUIDSGID = true;
LockPersonality = true;
MemoryDenyWriteExecute = true;
RestrictAddressFamilies = [
"AF_INET"
"AF_INET6"
"AF_UNIX"
];
SystemCallArchitectures = "native";
SystemCallFilter = [
"@system-service"
"~@privileged"
"~@resources"
];
CapabilityBoundingSet = "";
# A hostile file must not take the host's memory or every core.
MemoryMax = "3G";
CPUQuota = "400%";
TasksMax = 256;
};
};
};
# The container's system, evaluated as `containers.<name>.config` evaluates
# it, for a host that has no such container.
podSystem =
(import "${pkgs.path}/nixos/lib/eval-config.nix" {
modules = [
(
{ options, ... }:
{
config = {
nixpkgs =
if options.nixpkgs ? hostPlatform then
{ inherit (pkgs.stdenv) hostPlatform; }
else
{ localSystem = pkgs.stdenv.hostPlatform; };
boot.isNspawnContainer = true;
networking.hostName = lib.mkDefault machine;
networking.useDHCP = false;
};
}
)
containerConfig
];
system = null;
}).config;
in in
{ {
options.services.hyperhive.swarm.stt.clientId = lib.mkOption { options.services.hyperhive.swarm.stt.clientId = lib.mkOption {
@ -180,192 +344,120 @@ in
}; };
}; };
config = lib.mkIf cfg.enable { options.services.hyperhive.deploy.stt.runtime = lib.mkOption {
assertions = [ type = lib.types.enum [
{ "host"
assertion = haveClientIdentity; "k8s"
message = ''
services.hyperhive.deploy.stt.enable requires the service's
swarm-secret-store client identity: set both
services.hyperhive.deploy.bao.sttClientCertFile
services.hyperhive.deploy.bao.sttClientKeyFile
The service reads its queue client secret with it.
Both default to the pair glue-bao-tls.nix mints when
services.hyperhive.deploy.bao.enable is true (the host that runs the
store). Otherwise copy stt.pem and stt-key.pem
from the store host's /var/lib/swarm-bao-pki/ and name them in those
two options.
'';
}
{
assertion = lib.all oneWord (lib.attrValues storeFiles);
message = ''
The speech-to-text service's store identity paths must not contain
whitespace: nspawn's --load-credential receives them through
nixos-container's unquoted extra flags.
'';
}
]; ];
default = "host";
# The container hangs off the bridge, takes its address from the gateway's description = ''
# DHCP and resolves through its dnsmasq. Where the speech-to-text service runs: `host` in its `swarm-stt`
services.hyperhive.network.enable = lib.mkDefault true; container, or `k8s` as a pod in this host's cluster
services.hyperhive.gateway.enable = lib.mkDefault true; ({option}`services.hyperhive.deploy.k8s.enable`), which the host's
services.hyperhive.gateway.dns.enable = lib.mkDefault true; configuration must enable. The queue spreads requests over the instances
in its group, and the cache is each instance's own, so a switch moves
# nspawn fails to start the container when a credential source is the service: the container goes and its objects are applied, or the
# missing, so where this host mints the leaf the container waits for it. objects are deleted and the container returns. The transcript cache is
systemd.services."container@${machine}" = lib.mkMerge [ in the container's state directory on the host, and in a volume of the
caTrust.containerOrdering cluster in a pod; neither moves with the service, so a transcript is
(rootfsCheck.warnOnly machine) made again after a switch.
{ after = [ "swarm-bao-pki.service" ]; } '';
];
containers.${machine} = {
autoStart = true;
# The transcript cache lives in the container's /var/lib/swarm-stt.
ephemeral = false;
# No `--link-journal=host`: the journal stays in the guest, where the
# container's own forwarder reads it (../container-modules/swarm-journal-forwarder.nix).
extraFlags = lib.mapAttrsToList (id: source: "--load-credential=${id}:${source}") storeFiles;
inherit privateNetwork;
hostBridge = networkCfg.bridgeName;
bindMounts = caTrust.bindMount;
config =
{ lib, ... }:
{
imports = [
../container-modules/swarm-container.nix
../container-modules/swarm-journal-forwarder.nix
caBundleModule
];
services.hyperhive.swarmContainer = {
inherit privateNetwork;
writesOwnResolvConf = false;
};
networking.nameservers = [ networkCfg.bridgeIp ];
networking.interfaces.eth0.useDHCP = true;
users.users.${unit} = {
isSystemUser = true;
group = unit;
};
users.groups.${unit} = { };
# Authenticated as the daemon's own OIDC client, whose secret its
# store identity already reads: one identity for the whole container.
services.hyperhive.swarmJournalForwarder = {
enable = true;
serviceName = "stt";
endpoint = forwarderEndpoint;
inherit clientId;
tokenUrl = "${autheliaCfg.url}/api/oidc/token";
telemetryPort = forwarderTelemetryPort;
otlpMetricsPort = forwarderOtlpPort;
store = {
package = baoDeploy.package;
addr = "https://${baoCfg.domain}:${toString baoCfg.port}";
secretPath = "secret/swarm/services/${clientId}/oidc/client";
clientCertFile = forwarderCredential "stt-bao-cert";
clientKeyFile = forwarderCredential "stt-bao-key";
caFile = if storeFiles ? stt-bao-server-ca then forwarderCredential "stt-bao-server-ca" else null;
};
};
systemd.services.${forwarderUnit}.serviceConfig.LoadCredential = lib.attrNames storeFiles;
systemd.services.${unit} = {
description = "transcribe voice memos";
wantedBy = [ "multi-user.target" ];
wants = [ "network-online.target" ];
after = [ "network-online.target" ];
environment = {
BAO_ADDR = "https://${baoCfg.domain}:${toString baoCfg.port}";
BAO_CLIENT_CERT = credential "stt-bao-cert";
BAO_CLIENT_KEY = credential "stt-bao-key";
SWARM_STT_STATE_DIR = "/var/lib/${unit}";
SWARM_STT_FFMPEG = "${pkgs.ffmpeg-headless}/bin/ffmpeg";
SWARM_STT_WHISPER_CLI = "${pkgs.whisper-cpp}/bin/whisper-cli";
SWARM_STT_MODEL = "${model}";
SWARM_STT_CACHE_TTL_SECS = toString settings.cacheTtlSecs;
SWARM_STT_MAX_WAITING = toString settings.maxWaiting;
SWARM_STT_RUN_TIMEOUT_SECS = toString settings.runTimeoutSecs;
SWARM_STT_MAX_AUDIO_SECS = toString settings.maxAudioSecs;
SWARM_STT_MAX_BYTES = toString settings.maxBytes;
SWARM_STT_NATS_URL = "tls://${natsCfg.domain}:${toString natsCfg.port}";
SWARM_STT_OIDC_TOKEN_ENDPOINT = "${autheliaCfg.url}/api/oidc/token";
SWARM_STT_OIDC_CLIENT_ID = clientId;
OTEL_EXPORTER_OTLP_ENDPOINT = "http://127.0.0.1:${toString forwarderOtlpPort}";
OTEL_EXPORTER_OTLP_PROTOCOL = "http/protobuf";
OTEL_RESOURCE_ATTRIBUTES = "service.name=hyperhive-stt,swarm=${
if hyperhiveCfg.swarm.name == null then "unknown" else hyperhiveCfg.swarm.name
}";
}
// lib.optionalAttrs (storeFiles ? stt-bao-server-ca) {
BAO_CACERT = credential "stt-bao-server-ca";
}
// lib.optionalAttrs caTrust.useSelfSigned {
SWARM_STT_OIDC_CA_FILE = caTrust.bundlePathFor machine;
};
serviceConfig = {
ExecStart = "${cfg.package}/bin/swarm-stt";
User = unit;
Group = unit;
UMask = "0077";
# Bare ids: the system credentials nspawn handed in.
LoadCredential = lib.attrNames storeFiles;
Restart = "on-failure";
RestartSec = "10s";
SyslogIdentifier = unit;
# The sandbox for a service that decodes files strangers sent:
# the only writable path is its state directory, it sees no
# other user's processes or devices, and cannot gain
# privileges. It does NOT limit the network (see the header).
StateDirectory = unit;
StateDirectoryMode = "0700";
NoNewPrivileges = true;
ProtectSystem = "strict";
ProtectHome = true;
PrivateTmp = true;
PrivateDevices = true;
PrivateUsers = true;
ProtectKernelTunables = true;
ProtectKernelModules = true;
ProtectKernelLogs = true;
ProtectControlGroups = true;
ProtectClock = true;
ProtectHostname = true;
ProtectProc = "invisible";
ProcSubset = "pid";
RestrictNamespaces = true;
RestrictRealtime = true;
RestrictSUIDSGID = true;
LockPersonality = true;
MemoryDenyWriteExecute = true;
RestrictAddressFamilies = [
"AF_INET"
"AF_INET6"
"AF_UNIX"
];
SystemCallArchitectures = "native";
SystemCallFilter = [
"@system-service"
"~@privileged"
"~@resources"
];
CapabilityBoundingSet = "";
# A hostile file must not take the host's memory or every core.
MemoryMax = "3G";
CPUQuota = "400%";
TasksMax = 256;
};
};
};
};
}; };
options.services.hyperhive.deploy.stt.unit = lib.mkOption {
type = lib.types.raw;
readOnly = true;
internal = true;
default =
if onK8s then
podSystem.systemd.services.${unit}
else
config.containers.${machine}.config.systemd.services.${unit};
description = ''
The service's evaluated systemd unit, which the cluster's manifests are
rendered from (./k8s/render.nix). It is the unit the
container runs, taken from the container's configuration, or from the
same configuration evaluated alone when the service runs in the cluster
and the host has no container.
'';
};
config = lib.mkMerge [
{
assertions = [
{
assertion = !onK8s || hyperhiveCfg.deploy.k8s.enable;
message = ''
services.hyperhive.deploy.stt.runtime = "k8s" needs the cluster: set
services.hyperhive.deploy.k8s.enable on this host, or leave the
service's runtime at "host".
'';
}
];
}
(lib.mkIf cfg.enable {
assertions = [
{
assertion = haveClientIdentity;
message = ''
services.hyperhive.deploy.stt.enable requires the service's
swarm-secret-store client identity: set both
services.hyperhive.deploy.bao.sttClientCertFile
services.hyperhive.deploy.bao.sttClientKeyFile
The service reads its queue client secret with it.
Both default to the pair glue-bao-tls.nix mints when
services.hyperhive.deploy.bao.enable is true (the host that runs the
store). Otherwise copy stt.pem and stt-key.pem
from the store host's /var/lib/swarm-bao-pki/ and name them in those
two options.
'';
}
{
assertion = lib.all oneWord (lib.attrValues storeFiles);
message = ''
The speech-to-text service's store identity paths must not contain
whitespace: nspawn's --load-credential receives them through
nixos-container's unquoted extra flags.
'';
}
];
# The container hangs off the bridge, and the cluster's pods reach the
# host's services through it.
services.hyperhive.network.enable = lib.mkDefault true;
})
(lib.mkIf (cfg.enable && !onK8s) {
# The container takes its address from the gateway's DHCP and resolves
# through its dnsmasq.
services.hyperhive.gateway.enable = lib.mkDefault true;
services.hyperhive.gateway.dns.enable = lib.mkDefault true;
# nspawn fails to start the container when a credential source is
# missing, so where this host mints the leaf the container waits for it.
systemd.services."container@${machine}" = lib.mkMerge [
caTrust.containerOrdering
(rootfsCheck.warnOnly machine)
{ after = [ "swarm-bao-pki.service" ]; }
];
containers.${machine} = {
autoStart = true;
# The transcript cache lives in the container's /var/lib/swarm-stt.
ephemeral = false;
# No `--link-journal=host`: the journal stays in the guest, where the
# container's own forwarder reads it (../container-modules/swarm-journal-forwarder.nix).
extraFlags = lib.mapAttrsToList (id: source: "--load-credential=${id}:${source}") storeFiles;
inherit privateNetwork;
hostBridge = networkCfg.bridgeName;
bindMounts = caTrust.bindMount;
config = containerConfig;
};
})
];
} }

View file

@ -49,15 +49,22 @@ let
}; };
withNode = hiveWithController nodeSettings; withNode = hiveWithController nodeSettings;
# The same host with the router in the cluster, so it has no container. A # The same host with the router and the speech-to-text service in the
# second full host, because the claim is about what the configuration # cluster, so it has neither container. A second full host, because the claim
# drops; the other cases of this group read `withNode`. # is about what the configuration drops; the other cases of this group read
# `withNode`.
onCluster = hiveWithController ( onCluster = hiveWithController (
lib.recursiveUpdate nodeSettings { deploy.notify-router.runtime = "k8s"; } lib.recursiveUpdate nodeSettings {
deploy.notify-router.runtime = "k8s";
deploy.stt.runtime = "k8s";
}
); );
# A host that asks for the cluster with no node. # A host that asks for the cluster with no node.
runtimeRefused = hive { deploy.notify-router.runtime = "k8s"; }; runtimeRefused = hive {
deploy.notify-router.runtime = "k8s";
deploy.stt.runtime = "k8s";
};
runtimeRefusals = lib.filter (a: !a.assertion) runtimeRefused.assertions; runtimeRefusals = lib.filter (a: !a.assertion) runtimeRefused.assertions;
# A node every assertion refuses: no rendering, a pod range containing the # A node every assertion refuses: no rendering, a pod range containing the
@ -86,6 +93,7 @@ let
swarm-controller = allLocal.systemd.services.swarm-controller; swarm-controller = allLocal.systemd.services.swarm-controller;
swarm-notify-router = swarm-notify-router =
allLocal.containers.swarm-notify-router.config.systemd.services.swarm-notify-router; allLocal.containers.swarm-notify-router.config.systemd.services.swarm-notify-router;
swarm-stt = allLocal.containers.swarm-stt.config.systemd.services.swarm-stt;
swarm-ci-metrics = allLocal.systemd.services.swarm-ci-metrics; swarm-ci-metrics = allLocal.systemd.services.swarm-ci-metrics;
}; };
@ -137,6 +145,11 @@ let
OTEL_EXPORTER_OTLP_ENDPOINT = collectorEndpoint; OTEL_EXPORTER_OTLP_ENDPOINT = collectorEndpoint;
SWARM_NOTIFY_ROUTER_HEALTH_ADDR = "0.0.0.0:8080"; SWARM_NOTIFY_ROUTER_HEALTH_ADDR = "0.0.0.0:8080";
}; };
swarm-stt = {
OTEL_EXPORTER_OTLP_ENDPOINT = collectorEndpoint;
SWARM_STT_HEALTH_ADDR = "0.0.0.0:8080";
STATE_DIRECTORY = "/var/lib/swarm-stt";
};
swarm-ci-metrics = { swarm-ci-metrics = {
OTEL_EXPORTER_OTLP_ENDPOINT = collectorEndpoint; OTEL_EXPORTER_OTLP_ENDPOINT = collectorEndpoint;
SWARM_CI_METRICS_OTLP_ENDPOINT = collectorEndpoint; SWARM_CI_METRICS_OTLP_ENDPOINT = collectorEndpoint;
@ -159,7 +172,9 @@ let
units.swarm-controller.serviceConfig.LoadCredential units.swarm-controller.serviceConfig.LoadCredential
++ units.swarm-ci-metrics.serviceConfig.LoadCredential ++ units.swarm-ci-metrics.serviceConfig.LoadCredential
) )
++ map (f: lib.last (lib.splitString ":" f)) allLocal.containers.swarm-notify-router.extraFlags; ++ map (f: lib.last (lib.splitString ":" f)) (
allLocal.containers.swarm-notify-router.extraFlags ++ allLocal.containers.swarm-stt.extraFlags
);
credentialIds = lib.concatMap ( credentialIds = lib.concatMap (
u: map (e: lib.head (lib.splitString ":" e)) u.serviceConfig.LoadCredential u: map (e: lib.head (lib.splitString ":" e)) u.serviceConfig.LoadCredential
) (lib.attrValues units); ) (lib.attrValues units);
@ -172,6 +187,8 @@ let
"bao-client-key.pem" "bao-client-key.pem"
"notify-router-bao-cert" "notify-router-bao-cert"
"notify-router-bao-key" "notify-router-bao-key"
"stt-bao-cert"
"stt-bao-key"
]; ];
ciTimer = allLocal.systemd.timers.swarm-ci-metrics.timerConfig; ciTimer = allLocal.systemd.timers.swarm-ci-metrics.timerConfig;
@ -188,6 +205,7 @@ let
routerUnit = c: c.services.hyperhive.deploy.notify-router.unit; routerUnit = c: c.services.hyperhive.deploy.notify-router.unit;
manifestNames = c: lib.sort lib.lessThan (lib.attrNames c.services.k3s.manifests); manifestNames = c: lib.sort lib.lessThan (lib.attrNames c.services.k3s.manifests);
routerPrune = withNode.systemd.services.swarm-notify-router-k8s-prune; routerPrune = withNode.systemd.services.swarm-notify-router-k8s-prune;
sttPrune = withNode.systemd.services.swarm-stt-k8s-prune;
clusterRouterSpec = (render onCluster)."swarm-notify-router/deployment".spec.template.spec; clusterRouterSpec = (render onCluster)."swarm-notify-router/deployment".spec.template.spec;
cases = [ cases = [
{ {
@ -276,17 +294,17 @@ let
} }
{ {
# The images are the ones the manifests run, one per rendered service: # The images are the ones the manifests run, one per rendered service:
# the three workloads are the control that the list is not empty. # the four workloads are the control that the list is not empty.
name = "the node loads the image of every service the manifests run, and k3s's own"; name = "the node loads the image of every service the manifests run, and k3s's own";
ok = ok =
let let
loaded = map toString withNode.services.k3s.images; loaded = map toString withNode.services.k3s.images;
rendered = map toString withNode.system.build.k8sImages; rendered = map toString withNode.system.build.k8sImages;
in in
lib.length rendered == 3 lib.length rendered == 4
&& lib.all (i: lib.elem i loaded) rendered && lib.all (i: lib.elem i loaded) rendered
&& lib.elem (toString withNode.services.k3s.package.airgap-images) loaded && lib.elem (toString withNode.services.k3s.package.airgap-images) loaded
&& lib.length loaded == 4; && lib.length loaded == 5;
} }
{ {
# Nothing the host already runs differs but the store's side of the pods' # Nothing the host already runs differs but the store's side of the pods'
@ -296,7 +314,7 @@ let
# granter's role unit (which enables the login's auth mount) starts the # granter's role unit (which enables the login's auth mount) starts the
# same command, and the manifests are the same derivation as without the # same command, and the manifests are the same derivation as without the
# node. # node.
name = "the node adds only k3s, the jwt unit and the router's prune unit to the all-local host, and changes no container, timer or manifest"; name = "the node adds only k3s, the jwt unit and the prune units of the router and the speech-to-text service to the all-local host, and changes no container, timer or manifest";
ok = ok =
let let
names = a: lib.attrNames a; names = a: lib.attrNames a;
@ -307,10 +325,15 @@ let
&& lib.subtractLists (names withNode.systemd.services) (names allLocal.systemd.services) == [ ] && lib.subtractLists (names withNode.systemd.services) (names allLocal.systemd.services) == [ ]
&& lib.elem "k3s" added && lib.elem "k3s" added
&& lib.all ( && lib.all (
n: lib.hasPrefix "k3s" n || n == "swarm-bao-k8s-jwt-policy" || n == "swarm-notify-router-k8s-prune" n:
lib.hasPrefix "k3s" n
|| n == "swarm-bao-k8s-jwt-policy"
|| n == "swarm-notify-router-k8s-prune"
|| n == "swarm-stt-k8s-prune"
) added ) added
&& lib.elem "swarm-bao-k8s-jwt-policy" added && lib.elem "swarm-bao-k8s-jwt-policy" added
&& lib.elem "swarm-notify-router-k8s-prune" added && lib.elem "swarm-notify-router-k8s-prune" added
&& lib.elem "swarm-stt-k8s-prune" added
&& &&
lib.all lib.all
( (
@ -525,6 +548,7 @@ let
script = s.swarm-bao-k8s-jwt-policy.script; script = s.swarm-bao-k8s-jwt-policy.script;
certScript = { certScript = {
swarm-notify-router = s.swarm-bao-notify-router-policy.script; swarm-notify-router = s.swarm-bao-notify-router-policy.script;
swarm-stt = s.swarm-bao-stt-policy.script;
swarm-ci-metrics = s.swarm-bao-ci-metrics-policy.script; swarm-ci-metrics = s.swarm-bao-ci-metrics-policy.script;
swarm-controller = s.swarm-bao-controller-policy.script; swarm-controller = s.swarm-bao-controller-policy.script;
}; };
@ -540,7 +564,7 @@ let
${ttl} ${ttl}
''; '';
in in
lib.length roles == 3 lib.length roles == 4
&& lib.sort lib.lessThan roles == lib.sort lib.lessThan (lib.attrNames units) && lib.sort lib.lessThan roles == lib.sort lib.lessThan (lib.attrNames units)
&& &&
lib.sort lib.lessThan withNode.services.hyperhive.deploy.bao.k8sPrincipals lib.sort lib.lessThan withNode.services.hyperhive.deploy.bao.k8sPrincipals
@ -677,16 +701,20 @@ let
&& !(allLocal.systemd.services ? hyperhive-k8s-ca-trust); && !(allLocal.systemd.services ? hyperhive-k8s-ca-trust);
} }
{ {
name = "a router in the cluster leaves the host no container and no prune unit, and applies the namespace and its objects"; name = "a router or a speech-to-text service in the cluster leaves the host no container and no prune unit, and applies the namespace and its objects";
ok = ok =
!(onCluster.containers ? swarm-notify-router) !(onCluster.containers ? swarm-notify-router)
&& !(onCluster.systemd.services ? "container@swarm-notify-router") && !(onCluster.systemd.services ? "container@swarm-notify-router")
&& !(onCluster.systemd.services ? swarm-notify-router-k8s-prune) && !(onCluster.systemd.services ? swarm-notify-router-k8s-prune)
&& !(onCluster.containers ? swarm-stt)
&& !(onCluster.systemd.services ? "container@swarm-stt")
&& !(onCluster.systemd.services ? swarm-stt-k8s-prune)
&& &&
manifestNames onCluster == [ manifestNames onCluster == [
"coredns-custom" "coredns-custom"
"hyperhive-namespace" "hyperhive-namespace"
"swarm-notify-router" "swarm-notify-router"
"swarm-stt"
] ]
&& onCluster.services.k3s.manifests.hyperhive-namespace.content.kind == "Namespace" && onCluster.services.k3s.manifests.hyperhive-namespace.content.kind == "Namespace"
&& &&
@ -694,6 +722,12 @@ let
== [ == [
"Deployment" "Deployment"
"ServiceAccount" "ServiceAccount"
]
&&
lib.sort lib.lessThan (map (o: o.kind) onCluster.services.k3s.manifests.swarm-stt.content) == [
"Deployment"
"PersistentVolumeClaim"
"ServiceAccount"
]; ];
} }
{ {
@ -749,9 +783,163 @@ let
&& !(withNode.systemd.paths ? hyperhive-k8s-ca-trust); && !(withNode.systemd.paths ? hyperhive-k8s-ca-trust);
} }
{ {
name = "the router's runtime \"k8s\" needs the node"; # The container's whole unit is compared, sandbox included, so the
# stand-alone evaluation cannot drift from what the host runs.
name = "the speech-to-text service's unit, and so its manifests, are the same whether the container or the stand-alone evaluation supplies it";
ok = ok =
lib.any (a: lib.hasInfix "runtime = \"k8s\" needs the" a.message) runtimeRefusals let
unitOf = c: c.services.hyperhive.deploy.stt.unit;
in
(unitOf withNode).serviceConfig.SystemCallFilter == [
"@system-service"
"~@privileged"
"~@resources"
]
&& (unitOf onCluster).serviceConfig == (unitOf withNode).serviceConfig
&& (unitOf onCluster).environment == (unitOf withNode).environment
&& render onCluster == render withNode;
}
{
# The host-mode container is pinned by value: the module moved into a
# let binding, and nothing about the container it defines may change.
name = "with the speech-to-text service on the host, its container, credential flags and sandbox are as the module defines them";
ok =
let
c = withNode.containers.swarm-stt;
sc = (unitOf withNode).serviceConfig;
unitOf = x: x.services.hyperhive.deploy.stt.unit;
flags = c.extraFlags;
in
c.autoStart
&& !c.ephemeral
&& c.privateNetwork
&& c.hostBridge == withNode.services.hyperhive.network.bridgeName
&& lib.all (f: lib.hasPrefix "--load-credential=stt-bao-" f) flags
&& lib.any (lib.hasPrefix "--load-credential=stt-bao-cert:") flags
&& lib.any (lib.hasPrefix "--load-credential=stt-bao-key:") flags
&& sc.User == "swarm-stt"
&& sc.StateDirectory == "swarm-stt"
&& sc.NoNewPrivileges
&& sc.MemoryDenyWriteExecute
&& sc.PrivateUsers
&& sc.CapabilityBoundingSet == ""
&& sc.MemoryMax == "3G"
&& sc.CPUQuota == "400%"
&& sc.TasksMax == 256
&& withNode.systemd.services ? "container@swarm-stt"
&& sttPrune.before == [ "container@swarm-stt.service" ]
&& sttPrune.requiredBy == [ "container@swarm-stt.service" ]
&& lib.hasInfix "swarm-stt.yaml" sttPrune.script;
}
{
# The unit's ceilings are the pod's limits, and the limits the pod has
# no field for are not rendered. The controller's pod, whose unit sets
# none, is the control that nothing is added to a pod without them.
name = "the speech-to-text pod carries its unit's memory and CPU ceilings as limits and no requests, and a pod whose unit sets none carries none";
ok =
let
unit = units.swarm-stt.serviceConfig;
limits = (container "swarm-stt").resources.limits;
in
unit.MemoryMax == "3G"
&& unit.CPUQuota == "400%"
&& unit.TasksMax == 256
&&
limits == {
memory = "3Gi";
cpu = "4000m";
}
&& !((container "swarm-stt").resources ? requests)
&& !(lib.hasInfix "TasksMax" rendered)
&& !(lib.hasInfix "SystemCallFilter" rendered)
&& lib.all (name: !((container name) ? resources)) [
"swarm-controller"
"swarm-notify-router"
"swarm-ci-metrics"
];
}
{
# Other spellings of a ceiling: bytes, megabytes, a fractional core, no
# memory limit. A setting render cannot read fails the evaluation, the
# unchanged host being the control that the render itself succeeds.
name = "the unit's limits translate by systemd's units, and one render cannot read fails the evaluation";
ok =
let
withLimits =
sc: lib.recursiveUpdate allLocal { services.hyperhive.deploy.stt.unit.serviceConfig = sc; };
containersOf = sc: ((render (withLimits sc))."swarm-stt/deployment".spec.template.spec.containers);
first = sc: lib.head (containersOf sc);
in
renders allLocal
&&
(first {
MemoryMax = "512M";
CPUQuota = "150%";
}).resources.limits == {
memory = "512Mi";
cpu = "1500m";
}
&&
(first { MemoryMax = "1048576"; }).resources.limits == {
memory = "1048576";
cpu = "4000m";
}
&&
(first { MemoryMax = "infinity"; }).resources.limits == {
cpu = "4000m";
}
&& !(renders (withLimits {
MemoryMax = "50%";
}))
&& !(renders (withLimits {
MemoryMax = "3 G";
}))
&& !(renders (withLimits {
CPUQuota = "4";
}));
}
{
name = "the speech-to-text pod has probes on its health listener, keeps its cache in a volume, mounts no Secret, and runs as every pod does";
ok =
let
c = container "swarm-stt";
spec = podSpec "swarm-stt";
pvc = objects."swarm-stt/persistentvolumeclaim";
cred = lib.findFirst (v: v.name == "credentials") null spec.volumes;
in
(lib.head c.ports).containerPort == 8080
&& c.readinessProbe.httpGet.path == "/readyz"
&& c.livenessProbe.httpGet.path == "/healthz"
&& pvc.metadata.name == "swarm-stt-state"
&& pvc.spec.resources.requests.storage == "1Gi"
&& lib.any (m: m.name == "state" && m.mountPath == "/var/lib/swarm-stt") c.volumeMounts
&&
(lib.findFirst (v: v.name == "state") null spec.volumes).persistentVolumeClaim.claimName
== "swarm-stt-state"
# The one credential the pod holds is the store's public CA, from the
# ConfigMap. The controller's pod is the control for the lookup.
&& cred != null
&& !(cred ? secret)
&&
map (s: s.configMap.items) cred.projected.sources == [
[
{
key = "bao-server-ca.pem";
path = "stt-bao-server-ca";
}
]
]
&& lib.any (v: v ? secret) (podSpec "swarm-controller").volumes
&& c.securityContext.readOnlyRootFilesystem
&& c.securityContext.runAsNonRoot
&& c.securityContext.capabilities.drop == [ "ALL" ]
&& spec.securityContext.seccompProfile.type == "RuntimeDefault";
}
{
name = "the router's and the speech-to-text service's runtime \"k8s\" needs the node";
ok =
lib.any (a: lib.hasInfix "notify-router.runtime = \"k8s\" needs the" a.message) runtimeRefusals
&& lib.any (a: lib.hasInfix "stt.runtime = \"k8s\" needs the" a.message) runtimeRefusals
&& lib.all (a: a.assertion) onCluster.assertions; && lib.all (a: a.assertion) onCluster.assertions;
} }
]; ];