Watch
0
0
Fork
You've already forked hyperhive
0

require k8s: swarm services with a pod run in the cluster only

This commit is contained in:
atlas 2026-11-26 00:36:09 +01:00 • committed by maia
commit 57d40ae8ea
18 changed files with 1044 additions and 3125 deletions

View file

@ -751,13 +751,12 @@ in
type = lib.types.bool;
default = false;
description = ''
Run the swarm's message queue in a `swarm-nats` container on this
host. A swarm has one queue, so at most one host turns this on —
Run the swarm's message queue as a pod in this host's cluster. A swarm has one queue, so at most one host turns this on —
but *which* host is its own decision, not necessarily the one
running the swarm's other shared services.
Off by default, and off means *absent*: no container is created
and nothing else in the evaluated config changes.
Off by default, and off means *absent*: no pod is rendered and nothing
else in the evaluated config changes.
'';
};
@ -783,8 +782,7 @@ in
default = false;
example = true;
description = ''
Run the review classifier in a `swarm-review-classifier` container on
this host. It answers the swarm UI's review try-outs with `claude` on
Run the review classifier as a pod in this host's cluster. It answers the swarm UI's review try-outs with `claude` on
the Anthropic API key the operator sets in the swarm UI, or writes to the secret store at
`secret/swarm/services/review-classifier/anthropic-api-key`, field
`api_key`.
@ -796,9 +794,6 @@ in
and `reviewClassifierClientKeyFile`, minted on the store's host). The
key is never written for you: until the operator writes it the service
runs and every run fails with "no API key…".
Set {option}`services.hyperhive.deploy.review-classifier.runtime` to
`k8s` to run it as a pod in the host's cluster instead.
'';
};
@ -807,8 +802,7 @@ in
default = false;
example = true;
description = ''
Run the claude login minter in a `swarm-claude-login` container on
this host. It runs `claude auth login` for the agent an operator logs
Run the claude login minter as a pod in this host's cluster. It runs `claude auth login` for the agent an operator logs
in from its card in the swarm UI, and writes the credentials to that
agent's `secret/swarm/agents/<agent>/claude-credentials`, which the
agent's harness installs. Run it on one host: a login in progress
@ -819,9 +813,6 @@ in
host has the minter's store identity (the pair
{option}`services.hyperhive.deploy.bao.claudeLoginClientCertFile`
and `claudeLoginClientKeyFile`, minted on the store's host).
Set {option}`services.hyperhive.deploy.claude-login.runtime` to `k8s`
to run it as a pod in the host's cluster instead.
'';
};
@ -830,15 +821,11 @@ in
default = false;
example = true;
description = ''
Run the notification router in a `swarm-notify-router` container on
this host. It reads the forge events swarm-controller keeps from its
Run the notification router as a pod in this host's cluster. It reads the forge events swarm-controller keeps from its
webhooks and queues todos for the agents they concern: assigned,
unassigned, and cleared when the issue or pull request closes. Run
it on one host: it handles each issue's events in order.
Set {option}`services.hyperhive.deploy.notify-router.runtime` to `k8s`
to run it as a pod in the host's cluster instead.
On by default where
{option}`services.hyperhive.deploy.allSwarmServices` is set and this
host has the router's store identity (the pair
@ -852,15 +839,11 @@ in
default = false;
example = true;
description = ''
Run the speech-to-text service in a `swarm-stt` container on this
host. It transcribes the voice memos agents send, once per memo, with
Run the speech-to-text service as a pod in this host's cluster. It transcribes the voice memos agents send, once per memo, with
whisper.cpp; run it where the inference hardware is. The model is
{option}`services.hyperhive.deploy.stt.settings.modelSize` (default
`small`).
Set {option}`services.hyperhive.deploy.stt.runtime` to `k8s` to run it
as a pod in the host's cluster instead.
On by default where
{option}`services.hyperhive.deploy.allSwarmServices` is set and this
host has the service's store identity (the pair
@ -983,7 +966,10 @@ in
type = lib.types.bool;
default = false;
description = ''
Run the swarm-controller daemon on this host.
Run the swarm-controller daemon as a pod in this host's cluster
({option}`services.hyperhive.deploy.k8s.enable`, on by default where this
is set). It needs {option}`services.hyperhive.swarm.controller.tcp.enable` (on by default):
the gateway reaches the pod over its TCP listener.
Off by default and deliberately not derived from
{option}`services.hyperhive.deploy.hive-controller.enable`: a swarm
@ -991,9 +977,8 @@ in
rather than about whether it runs a hive.
Also serves the swarm UI from this host. The UI is a view onto the
controller's state and reaches it over that daemon's unix socket,
so the host that runs the controller is the only host that can
serve it.
controller's state and reaches it through the pod's Service, so the
host that runs the controller is the only host that can serve it.
'';
};
};

View file

@ -49,17 +49,6 @@ let
# Readers that log in under another unit's principal: reader unit → the
# gate its own module defines it under, and the policy units it waits for.
readersOfOtherPolicy = {
# ./swarm-nats.nix, under the queue responder's leaf. Also after the
# publisher's policy, which denies the publisher the callout seeds' paths:
# until it is written the publisher may create them, and this unit keeps
# a seed it finds there.
swarm-bao-nats-callout-xkey = {
here = deployCfg.nats.enable;
policies = [
"swarm-bao-nats-auth-policy"
"swarm-bao-secret-publisher-policy"
];
};
# ./swarm-grafana.nix, under Grafana's leaf, which may create the admin
# password, the metrics bearer, the datasource key and the controller's
# Grafana token only once that policy is written.

View file

@ -62,8 +62,6 @@ let
swarm-bao-grafana-metrics-bearer = deployCfg.grafana.enable;
swarm-bao-grafana-secret-key = deployCfg.grafana.enable;
swarm-bao-grafana-controller-token = deployCfg.grafana.enable;
# ./swarm-nats.nix
swarm-bao-nats-callout-xkey = deployCfg.nats.enable;
# ./swarm-ci-runner.nix
swarm-bao-ci-runner = deployCfg.ci-runner.enable;
# ./swarm-attic.nix

View file

@ -1,7 +1,6 @@
# Kubernetes manifests for the swarm services this host deploys, rendered by
# ./render.nix from their systemd units, and the per-service switch that moves
# a service between its host unit and the cluster (./runtime.nix). Rendering
# alone changes no unit and applies nothing. docs/4-implementation/k8s/manifests.md
# ./render.nix from their systemd units, and the module that applies them to the
# cluster (./runtime.nix). docs/4-implementation/k8s/manifests.md
# and runtime.md have the design.
{
pkgs,
@ -41,9 +40,7 @@ in
object, and the images their pods run into `system.build.k8sImages`.
The manifests reference their Secrets by name only.
Rendering only: the host's units stay as they are, and nothing
applies the manifests to a cluster. A service with a `runtime` option
is applied when it says `k8s`, on a host with
The manifests are applied on a host with
{option}`services.hyperhive.deploy.k8s.enable`.
'';
};
@ -59,8 +56,8 @@ in
readOnly = true;
internal = true;
description = ''
What ./runtime.nix moves services with: each enabled service's
objects and switch, the namespace object, and the CA ConfigMap's name
What ./runtime.nix applies: each enabled service's
objects, the namespace object, and the CA ConfigMap's name
and host files.
'';
};
@ -71,7 +68,7 @@ in
inherit (rendered)
caConfigMap
caSources
switches
serviceNames
userNamespaces
;
services = withoutContext rendered.services;

View file

@ -5,8 +5,9 @@
#
# The main node holds the images of the services ./render.nix renders and
# shares them with the nodes that join through k3s's embedded registry mirror
# of the images' registry host. No service's objects are applied until its `runtime` is `k8s`
# (./runtime.nix): until then its host unit runs.
# of the images' registry host. Every swarm service this host enables runs on it,
# so enabling one turns the node on, and a host that turns the node off while it
# enables one fails at evaluation (./runtime.nix applies the manifests).
{
config,
lib,
@ -118,9 +119,22 @@ let
'') nodePorts
) addresses;
# The services whose data the module keeps in the cluster: those with a
# `runtime` that is `k8s`. Each puts its state label on this node.
stateful = lib.filterAttrs (_: svc: svc.enable && svc.runtime == "k8s") {
# The swarm services that run in the cluster, by the name of their
# `deploy.<name>.enable` option.
swarmServices = [
"notify-router"
"stt"
"ci-metrics"
"review-classifier"
"claude-login"
"nats"
"swarm-controller"
];
enabledServices = lib.filter (name: deployCfg.${name}.enable) swarmServices;
# The services whose data the module keeps in the cluster. Each puts its state
# label on this node.
stateful = lib.filterAttrs (_: svc: svc.enable) {
inherit (deployCfg) nats ci-metrics;
};
in
@ -129,16 +143,17 @@ in
enable = lib.mkOption {
type = lib.types.bool;
default = false;
defaultText = lib.literalMD "`true` where the host enables a swarm service that runs in the cluster, else `false`";
description = ''
Run a k3s server on this host, the cluster's main node, with the images of the
swarm services that run in the cluster loaded into it, and render
their manifests (`services.hyperhive.k8s.enable`). Set it on the host
that runs the swarm's services, which is the one
`services.hyperhive.deploy.singleHostSwarm` names.
their manifests (`services.hyperhive.k8s.enable`).
The cluster starts with no hyperhive workload: a service keeps
running as its systemd unit unless its `runtime` option is `k8s`.
Its secrets are encrypted at rest, and traefik and metrics-server
Defaults on where this host enables any swarm service that runs in the
cluster: `deploy.notify-router`, `stt`, `ci-metrics`, `review-classifier`,
`claude-login`, `nats` and `swarm-controller`, which
`services.hyperhive.deploy.singleHostSwarm` and `allSwarmServices` turn
on. Setting it to `false` on such a host fails the evaluation. Its secrets are encrypted at rest, and traefik and metrics-server
stay off. Pods and services take their
addresses from {option}`services.hyperhive.deploy.k8s.podCidr` and
{option}`services.hyperhive.deploy.k8s.serviceCidr`. The firewall
@ -241,7 +256,7 @@ in
labels.loadBalancerLabel
] (_: "true")
// lib.mapAttrs' (name: _: lib.nameValuePair (labels.stateLabel name) "true") stateful;
defaultText = lib.literalMD "computed from the services whose `runtime` is `k8s`";
defaultText = lib.literalMD "computed from the enabled services whose data the cluster keeps";
description = ''
The labels this node carries, which the module sets with
`services.k3s.nodeLabel`. The pods and volumes that need a node select
@ -249,17 +264,16 @@ in
none of those pods.
- `hyperhive.darkest.space/state-<service>` for each service whose data the
cluster keeps: `nats` and `ci-metrics`, each when its `runtime` is
`k8s`. A volume's `nodeAffinity` and the pod's `nodeSelector` name it.
cluster keeps: `nats` and `ci-metrics`, each when enabled. A volume's `nodeAffinity` and the pod's `nodeSelector` name it.
- `hyperhive.darkest.space/entry`: the node the hosts' DNS points at.
- `svccontroller.k3s.cattle.io/enablelb`: with it on any node, the
service load balancer binds a published port on the labelled nodes
only, so a joined node does not publish the queue's port.
k3s puts these on the node's object at every start, registered or not.
It never takes one off: a label left from a service that has moved
back to `host` stays and does nothing, and `kubectl label node <name>
<label>-` removes one.
It never takes one off: a label left from a service that is disabled
stays and does nothing, and `kubectl label node <name> <label>-`
removes one.
'';
};
@ -336,6 +350,24 @@ in
};
config = lib.mkMerge [
{
services.hyperhive.deploy.k8s.enable = lib.mkDefault (enabledServices != [ ] && cfg.join == null);
assertions = [
{
assertion = cfg.enable || cfg.join != null || enabledServices == [ ];
message = ''
services.hyperhive.deploy.k8s.enable is false, and this host enables
swarm services that run only in the cluster: ${
lib.concatMapStringsSep ", " (n: "deploy.${n}.enable") enabledServices
}.
Set services.hyperhive.deploy.k8s.enable to true (it is the default
where one is enabled) or disable those services on this host.
'';
}
];
}
(lib.mkIf cfg.enable {
assertions = [
{

View file

@ -43,7 +43,7 @@ let
hiveClientCaKey = "hive-client-ca.pem";
servicesRootKey = "swarm-services-root.pem";
controllerCfg = deployCfg.swarm-controller;
controllerOnCluster = controllerCfg.enable && controllerCfg.runtime == "k8s";
controllerOnCluster = controllerCfg.enable;
controllerTcp = hyperhiveCfg.swarm.controller.tcp;
natsCfg = deployCfg.nats;
labels = import ./labels.nix;
@ -81,11 +81,9 @@ let
];
# The controller's listener leaf: its pod issues the leaf itself, from the
# store, with its ServiceAccount token, as the host's
# `swarm-controller-tls.service` does with its certificate
# (../lib/swarm-controller-tls-issue.nix is the one script). An init
# container writes it before the daemon starts and a second container renews
# it, both into an emptyDir only the pod holds.
# 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
@ -103,8 +101,6 @@ let
${tlsIssue.script {
login = "bao write -field=token auth/${podAuth.mount}/login role=swarm-controller jwt=@${podAuth.tokenFile}";
credential = "ServiceAccount token";
group = null;
createDir = false;
}}
'';
# The host's timer runs the same check daily: the script leaves a leaf
@ -140,9 +136,7 @@ let
# `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.
# `switch` is null for a service that always runs on the host, and for one
# with a `runtime` option names the option's value and the host unit or units
# that run the service when it is `"host"`. `otlp` is where the pod pushes
# `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
@ -179,10 +173,6 @@ let
# (../glue-controller-env.nix, `otel_http_client.rs`).
otlp = "own";
ephemeralState = true;
switch = {
inherit (controllerCfg) runtime;
hostUnit = "swarm-controller.service";
};
};
# 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.
@ -198,10 +188,6 @@ let
etcFiles = [ ];
publicCredentials."bao-ca.pem" = baoServerCaKey;
otlp = "none";
switch = {
inherit (natsCfg) runtime;
hostUnit = "container@swarm-nats.service";
};
};
swarm-notify-router = {
inherit (deployCfg.notify-router) enable package;
@ -211,10 +197,6 @@ let
etcFiles = [ ];
publicCredentials.notify-router-bao-server-ca = baoServerCaKey;
otlp = "hive";
switch = {
inherit (deployCfg.notify-router) runtime;
hostUnit = "container@swarm-notify-router.service";
};
};
swarm-stt = {
inherit (deployCfg.stt) enable package;
@ -237,10 +219,6 @@ let
# Stands in for the unit's `PrivateUsers`: the decoder reads audio that
# strangers sent.
hostUsers = false;
switch = {
inherit (deployCfg.stt) runtime;
hostUnit = "container@swarm-stt.service";
};
};
swarm-review-classifier = {
inherit (deployCfg.review-classifier) enable package;
@ -250,10 +228,6 @@ let
etcFiles = [ ];
publicCredentials.review-classifier-bao-server-ca = baoServerCaKey;
otlp = "hive";
switch = {
inherit (deployCfg.review-classifier) runtime;
hostUnit = "container@swarm-review-classifier.service";
};
};
swarm-claude-login = {
inherit (deployCfg.claude-login) enable package;
@ -263,10 +237,6 @@ let
etcFiles = [ ];
publicCredentials.claude-login-bao-server-ca = baoServerCaKey;
otlp = "hive";
switch = {
inherit (deployCfg.claude-login) runtime;
hostUnit = "container@swarm-claude-login.service";
};
};
swarm-ci-metrics = {
inherit (deployCfg.ci-metrics) enable package;
@ -284,15 +254,6 @@ let
hostDir = deployCfg.ci-metrics.hostStateDir;
};
otlp = "own";
# The timer and the service both: the prune unit holds back either, and a
# service started by hand cannot run beside the CronJob.
switch = {
inherit (deployCfg.ci-metrics) runtime;
hostUnit = [
"swarm-ci-metrics.timer"
"swarm-ci-metrics.service"
];
};
};
};
@ -390,7 +351,7 @@ let
protocol = "TCP";
inherit port;
};
queueOnCluster = natsCfg.enable && natsCfg.runtime == "k8s";
queueOnCluster = natsCfg.enable;
in
{
apiVersion = "networking.k8s.io/v1";
@ -1148,15 +1109,12 @@ in
# for the others to pull from it.
images = lib.unique (lib.concatMap (w: [ w.image ] ++ w.extraImages) (lib.attrValues enabled));
# What ./runtime.nix moves services with. `switches` holds the services that
# have a runtime option and is cheap to read: it names the units that a
# switch adds or removes, so it cannot depend on rendering a unit. `services`
# holds the objects. `caSources` is the host file behind each key of the CA
# ConfigMap, null where there is none.
switches = lib.mapAttrs (_: svc: svc.switch) (
lib.filterAttrs (_: svc: svc.enable && svc.switch != null) services
);
# The services whose pods run in a user namespace. Cheap to read, like `switches`.
# 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
);

View file

@ -1,10 +1,10 @@
# Which of a service's two homes runs it: its host unit, or its objects in the
# cluster. A service with a `runtime` option is on the cluster when the option
# says `"k8s"`, and then only: its host unit or units are gone from the
# configuration, and its manifests are in `services.k3s.manifests`.
# The cluster does not remove what a manifest created once the manifest is
# gone, so a service back on the host has its objects deleted before its host
# unit starts. docs/4-implementation/k8s/runtime.md has the design.
# Applies the swarm services this host enables to its cluster: their manifests go
# into `services.k3s.manifests`, and the CA files the pods trust are published
# to the cluster. Each service's host unit or container is gone from the
# configuration, so the pod is the only copy: `switch-to-configuration` stops
# every unit the new configuration drops, and waits for each stop, before it runs
# the activation that links the manifests in. docs/4-implementation/k8s/runtime.md
# has the design.
{
config,
lib,
@ -16,8 +16,7 @@ let
node = config.services.hyperhive.deploy.k8s;
rendered = cfg.rendered;
onCluster = lib.filterAttrs (_: s: s.runtime == "k8s") rendered.switches;
onHost = lib.filterAttrs (_: s: s.runtime == "host") rendered.switches;
onCluster = rendered.serviceNames;
kubectl = "${pkgs.kubectl}/bin/kubectl";
kubeconfig = "/etc/rancher/k3s/k3s.yaml";
@ -29,19 +28,10 @@ let
'';
apiReady = waitFor 600 "the cluster's API" "${kubectl} get --raw /readyz >/dev/null 2>&1";
# The service load balancer binds a Service's port on the node with a
# `hostPort` in a pod of `kube-system`, which its controller deletes some time
# after the Service. The rule that forwards the port to that pod stays until
# the pod is gone, and would swallow what the host unit then listens on.
lbPodsGone =
name:
waitFor 180 "the load balancer's pods of ${name}"
"[ -z \"\$(${kubectl} --namespace kube-system get pods --selector svccontroller.k3s.cattle.io/svcname=${name},svccontroller.k3s.cattle.io/svcnamespace=${cfg.namespace} --output name)\" ]";
caFiles = lib.filterAttrs (_: path: path != null) rendered.caSources;
# The services on the cluster whose pods run in a user namespace.
userNamespaced = lib.filter (name: onCluster ? ${name}) rendered.userNamespaces;
userNamespaced = lib.filter (name: lib.elem name onCluster) rendered.userNamespaces;
in
{
config = lib.mkIf (node.enable && cfg.enable) (
@ -62,25 +52,25 @@ in
];
})
(lib.mkIf (onCluster != { }) {
(lib.mkIf (onCluster != [ ]) {
# The cluster applies each file of the manifests directory when it
# appears: a service's objects go in when its host unit has stopped,
# appears: a service's objects go in after its old host unit has stopped,
# because `switch-to-configuration` stops every unit the new
# configuration drops before it activates the new configuration, and
# the files are linked in by the activation.
services.k3s.manifests = {
hyperhive-namespace.content = rendered.namespaceObject;
}
// lib.mapAttrs (name: _: {
// lib.genAttrs onCluster (name: {
content = lib.attrValues rendered.services.${name}.objects;
}) onCluster;
});
})
# The pods' CA files are public, so the host publishes them as they are.
# A pod waits in ContainerCreating until this has run. The unit has no
# `RemainAfterExit`, so the path unit below starts it again whenever a
# file changes.
(lib.mkIf (onCluster != { } && caFiles != { }) {
(lib.mkIf (onCluster != [ ] && caFiles != { }) {
systemd.services.hyperhive-k8s-ca-trust = {
description = "publish the hive's CA files to the cluster's pods";
wantedBy = [ "multi-user.target" ];
@ -119,51 +109,6 @@ in
};
})
# A service back on the host first loses its objects. The units that
# start the host copy require this one, so the pod is gone before the
# host copy starts, and a failure here leaves the host copy stopped.
#
# Its marker is the manifest's link in the cluster's manifests
# directory, which nothing else removes: no link, nothing was applied,
# and the unit needs no cluster. The link is renamed first, so the
# cluster cannot apply it again, and the rename is the record of what is
# left to delete. Deleting the AddOn the cluster keeps for the file lets
# a later switch to the cluster apply the same manifest again.
(lib.mkIf (onHost != { }) {
systemd.services = lib.mapAttrs' (
name: s:
lib.nameValuePair "${name}-k8s-prune" {
description = "delete ${name}'s objects from the cluster before its host unit starts";
after = [ "k3s.service" ];
before = lib.toList s.hostUnit;
requiredBy = lib.toList s.hostUnit;
serviceConfig = {
Type = "oneshot";
RemainAfterExit = true;
SyslogIdentifier = "${name}-k8s-prune";
};
environment.KUBECONFIG = kubeconfig;
script = ''
set -euo pipefail
link=${node.manifestDir}/${name}.yaml
pending=$link.pruning
if [ -e "$link" ] || [ -L "$link" ]; then
mv -f "$link" "$pending"
fi
if [ ! -e "$pending" ] && [ ! -L "$pending" ]; then
exit 0
fi
${apiReady}
${kubectl} --namespace ${cfg.namespace} delete deployment,cronjob,serviceaccount,networkpolicy,service \
--selector=app.kubernetes.io/name=${name} \
--cascade=foreground --wait=true --timeout=180s --ignore-not-found
${lbPodsGone name}
${kubectl} --namespace kube-system delete addons.k3s.cattle.io ${name} --ignore-not-found
rm -f "$pending"
'';
}
) onHost;
})
]
);
}

View file

@ -1,15 +1,11 @@
# The script that issues the swarm-controller's TCP listener leaf from the
# store's `pki` mount, and the two places that run it: the host's
# `swarm-controller-tls.service` (../swarm-controller.nix) and the pod's init
# and renewal containers (../k8s/render.nix). One script, so the leaf's checks
# (name, half-life, the role it is issued through) cannot differ between them.
# store's `pki` mount, which the pod's init and renewal containers run
# (../k8s/render.nix). The directory is the pod's `emptyDir`, which exists and
# belongs to another user.
#
# Pure function of the evaluated configuration, NOT a NixOS module. `login`
# is the command that prints a store token on stdout, `credential` names what
# it logs in with (for the error), and `group` is the group the
# key is readable by, or null where the files are already the daemon's own.
# `createDir` is false where the directory exists and belongs to another user,
# as an `emptyDir` does in a pod.
# is the command that prints a store token on stdout, and `credential` names
# what it logs in with (for the error).
{ lib, config }:
let
deployCfg = config.services.hyperhive.deploy;
@ -21,19 +17,11 @@ in
{
login,
credential,
group,
createDir ? true,
}:
let
groupFlag = lib.optionalString (group != null) " -g ${group}";
mkDir = lib.optionalString createDir "install -d -m 0750${groupFlag} \"$d\"";
chgrp = lib.optionalString (group != null) "chgrp ${group} \"$d/key.pem.new\" \"$d/cert.pem.new\"";
in
''
set -euo pipefail
d=${lib.escapeShellArg tcpHost.tlsDir}
name=${lib.escapeShellArg tcpCfg.domain}
${mkDir}
# Missing, past half its window, or naming something other than the
# configured domain.
@ -76,7 +64,6 @@ in
exit 1
fi
done
${chgrp}
chmod 0640 "$d/key.pem.new" "$d/cert.pem.new"
# Key first: the daemon pairs whatever it reads, and a new key beside
# the old certificate is a pair it refuses and retries.

View file

@ -3,14 +3,13 @@
# `swarm-nats` container.
#
# The callout issuer and user keys live in the swarm secret store beside the
# callout xkey: `swarm-bao-nats-callout-xkey` in ./swarm-nats.nix creates
# them there, and the server renders their public halves from the store. A
# callout xkey: the queue pod's `callout-config` init container (./swarm-nats.nix)
# creates them there, and the server renders their public halves from the store. A
# definition of a removed option fails evaluation with a message, under its
# `deploy.nats` path and under the `swarm.nats` one older configs use.
#
# The host seed files under /var/lib/swarm-nats-callout are NOT removed here:
# that unit stores each one before it removes it, and a tmpfiles rule could
# run first.
# they may hold the only copy of a key the store lacks.
#
# Self-contained and deletable, like ./host-ca-removed.nix: one file to
# remove when the deprecation window closes.
@ -18,16 +17,15 @@
let
inStore = ''
The queue's callout issuer and user keys live in the swarm secret store:
swarm-bao-nats-callout-xkey creates them there, and the server renders
their public halves from it. Remove this definition. See
the queue pod's callout-config init container creates them there, and the
server renders their public halves from it. Remove this definition. See
docs/2-handbook/swarm/credentials.md.
'';
# The seed-file options name a key an operator may want to keep.
seedFile = name: ''
${inStore}
A seed at /var/lib/swarm-nats-callout/${name} is what that unit stores
when the store holds none, so a key placed there keeps its public half;
otherwise a new key is created.
A seed at /var/lib/swarm-nats-callout/${name} is not read: the store holds the
key, or a new one is created.
'';
removed = name: message: [
(lib.mkRemovedOptionModule [ "services" "hyperhive" "deploy" "nats" name ] message)

View file

@ -7,9 +7,9 @@
# sees and pushes each newly finished run's duration and queue wait to the
# swarm collector, stamped at the run's end. The first pass, with no cursor in
# the state directory, walks every run back to the first. docs/4-implementation/swarm/ci-metrics.md
# has the design. With `deploy.ci-metrics.runtime = "k8s"` the host has neither
# the service nor the timer: the poller is a CronJob in the host's cluster,
# rendered from the unit and timer below (docs/4-implementation/k8s/runtime.md).
# has the design. The poller is a CronJob in the host's cluster, rendered from
# the unit and timer below (docs/4-implementation/k8s/runtime.md); the host runs
# neither.
#
# It reaches the forge, authelia, the store and the collector by name, so
# nothing here asks which host runs any of them. Its one credential on disk is
@ -59,28 +59,21 @@ let
"bao-ca.pem" = baoDeploy.serverCaFile;
};
onK8s = cfg.runtime == "k8s";
# Where the host unit's `StateDirectory` is: `DynamicUser` keeps it under
# `/var/lib/private`, so the pod's volume is the directory the unit uses.
hostStateDir = "/var/lib/private/${unit}";
# `hostUnit`: a host service, so the bundle reads the host CA path and waits
# on `hive-tls-ca.service`. `enable`: `imports` is unconditional, so without
# it a host with the poller off gets the bundle unit and an `ExecStart`-less
# `swarm-ci-metrics` service.
trustBundle =
enable:
caTrust.trustBundle {
inherit pkgs enable;
name = unit;
consumers = [ unit ];
hostUnit = true;
};
# `hostUnit`: the bundle reads the host CA path and waits on
# `hive-tls-ca.service`.
trustBundle = caTrust.trustBundle {
inherit pkgs;
name = unit;
consumers = [ unit ];
hostUnit = true;
};
# The poller's service and timer. The host runs them; with the poller in the
# cluster they are only the source of the CronJob (`deploy.ci-metrics.unit`
# and `.timer`).
# The poller's service and timer, the source of the CronJob
# (`deploy.ci-metrics.unit` and `.timer`).
unitModule = {
systemd.services.${unit} = {
description = "push finished forge CI runs to the swarm metrics store";
@ -133,8 +126,7 @@ let
};
};
# The unit and timer evaluated as a host evaluates them, for a host that
# does not run them.
# The unit and timer evaluated as a host evaluates them.
podSystem =
(import "${pkgs.path}/nixos/lib/eval-config.nix" {
modules = [
@ -153,15 +145,13 @@ let
};
}
)
(trustBundle true)
trustBundle
unitModule
];
system = null;
}).config;
in
{
imports = [ (trustBundle (cfg.enable && !onK8s)) ];
options.services.hyperhive.swarm.ci-metrics.clientId = lib.mkOption {
type = lib.types.str;
readOnly = true;
@ -200,30 +190,6 @@ in
description = "The CI run poller package.";
};
runtime = lib.mkOption {
type = lib.types.enum [
"host"
"k8s"
];
default = "host";
description = ''
Where the CI run poller runs: `host` as the `swarm-ci-metrics` service
and timer, or `k8s` as a CronJob in this host's cluster
({option}`services.hyperhive.deploy.k8s.enable`), which the host's
configuration must enable. A switch moves the poller: the service and
timer go and the CronJob is applied, or the CronJob is deleted and the
service and timer return, so one poller runs at any time. Its cursor is
in the service's state directory on the host, and the cluster's volume
for it is on that directory, so a switch moves the process and not the
cursor. The pod runs on the node with the
`hyperhive.darkest.space/state-ci-metrics` label, which the node
module sets, and starts with no gate.
The poller keeps pushing to the swarm collector's route of its own,
not to the hive collector the cluster's other pods push to.
'';
};
hostStateDir = lib.mkOption {
type = lib.types.str;
readOnly = true;
@ -239,11 +205,10 @@ in
type = lib.types.raw;
readOnly = true;
internal = true;
default = if onK8s then podSystem.systemd.services.${unit} else config.systemd.services.${unit};
default = podSystem.systemd.services.${unit};
description = ''
The poller's evaluated systemd service, which the cluster's CronJob is
rendered from (./k8s/render.nix). It is the service the host runs, or,
with the poller in the cluster, the same service evaluated alone.
rendered from (./k8s/render.nix). The host does not run it.
'';
};
@ -251,7 +216,7 @@ in
type = lib.types.raw;
readOnly = true;
internal = true;
default = if onK8s then podSystem.systemd.timers.${unit} else config.systemd.timers.${unit};
default = podSystem.systemd.timers.${unit};
description = ''
The poller's evaluated systemd timer, which the CronJob's schedule is
rendered from, taken as {option}`unit` is.
@ -260,19 +225,6 @@ in
};
config = lib.mkMerge [
{
assertions = [
{
assertion = !onK8s || hyperhiveCfg.deploy.k8s.enable;
message = ''
services.hyperhive.deploy.ci-metrics.runtime = "k8s" needs the
cluster: set services.hyperhive.deploy.k8s.enable on this host, or
leave the poller's runtime at "host".
'';
}
];
}
(lib.mkIf cfg.enable {
assertions = [
{
@ -297,11 +249,9 @@ in
];
})
(lib.mkIf (cfg.enable && !onK8s) unitModule)
# The pod reaches the store, authelia, the forge and the collector by
# name, which the cluster resolves to the hive bridge.
(lib.mkIf (cfg.enable && onK8s) {
(lib.mkIf cfg.enable {
services.hyperhive.network.enable = lib.mkDefault true;
# The pod's local volume needs its directory to exist before the pod

View file

@ -1,20 +1,16 @@
# The claude login minter, in a `swarm-claude-login` container on the host
# The claude login minter, a pod in the host's cluster on the host
# that sets `deploy.claude-login.enable`, which `deploy.allSwarmServices`
# defaults on where the host has the minter's store identity. An operator logs
# an agent in from its card in the swarm UI: swarm-controller relays the start
# and the pasted code over the queue, and the daemon runs `claude auth login`
# and writes the credentials to that agent's store leaf.
# docs/4-implementation/swarm/claude-login.md has the design.
# With `deploy.claude-login.runtime = "k8s"` it runs as a pod instead, rendered
# from the unit below (docs/4-implementation/k8s/runtime.md).
# docs/4-implementation/swarm/claude-login.md has the design. The pod is rendered
# (./k8s/render.nix) from the unit below (docs/4-implementation/k8s/runtime.md);
# it reaches the swarm services by name and nothing on the host's loopback.
#
# Its own network namespace on the bridge, as ./swarm-review-classifier.nix
# has: it reaches the swarm services by name and nothing on the host's
# loopback.
#
# The container holds one credential, its own store leaf, which nspawn hands in
# as a system credential with no copy on disk. The daemon reads its queue
# client secret with it and writes agents' credentials under it.
# The unit names its store leaf by credential id; the pod logs in to the store
# with its ServiceAccount token instead, reads its queue client secret with it
# and writes agents' credentials under it.
{
pkgs,
lib,
@ -59,8 +55,6 @@ let
# takes the minter's metrics there and pushes them to the swarm collector.
forwarderOtlpPort = 4318;
rootfsCheck = import ./lib/container-rootfs-check.nix { inherit config; };
# The daemon reaches authelia, the store and the queue by name over TLS, and
# in self-signed mode their leaves chain to the hive CA.
caTrust = import ./lib/hive-ca-trust.nix { inherit lib tlsCfg gatewayCfg; };
@ -85,19 +79,13 @@ let
claude-login-bao-key = baoDeploy.claudeLoginClientKeyFile;
claude-login-bao-server-ca = baoDeploy.serverCaFile;
};
# nixos-container expands `extraFlags` unquoted, so a source path must be
# one word.
oneWord = path: builtins.match ".*[[:space:]].*" path == null;
credential = id: "/run/credentials/${unit}.service/${id}";
forwarderCredential = id: "/run/credentials/${forwarderUnit}.service/${id}";
privateNetwork = true;
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.claude-login.unit`).
# The unit the pod is rendered from (`deploy.claude-login.unit`) is
# defined in this module.
containerConfig =
{ pkgs, lib, ... }:
{
@ -183,7 +171,7 @@ let
# Each login's scratch directory, gone with the unit.
PrivateTmp = true;
UMask = "0077";
# Bare ids: the system credentials nspawn handed in.
# Bare ids, which the pod's login replaces.
LoadCredential = lib.attrNames storeFiles;
Restart = "on-failure";
RestartSec = "10s";
@ -192,8 +180,8 @@ let
};
};
# The container's system, evaluated as `containers.<name>.config` evaluates
# it, for a host that has no such container.
# The service's NixOS system, evaluated on its own: its unit is what the pod is
# rendered from.
podSystem =
(import "${pkgs.path}/nixos/lib/eval-config.nix" {
modules = [
@ -236,55 +224,19 @@ in
description = "The claude login minter daemon package.";
};
options.services.hyperhive.deploy.claude-login.runtime = lib.mkOption {
type = lib.types.enum [
"host"
"k8s"
];
default = "host";
description = ''
Where the claude login minter runs: `host` in its `swarm-claude-login`
container, or `k8s` as a pod in this host's cluster
({option}`services.hyperhive.deploy.k8s.enable`), which the host's
configuration must enable. A switch moves the service: the container
goes and its objects are applied, or the objects are deleted and the
container returns. The service keeps no state, so nothing moves with it;
each login's scratch directory is in the pod's `/tmp` volume and goes with the pod.
'';
};
options.services.hyperhive.deploy.claude-login.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};
default = podSystem.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.
rendered from (./k8s/render.nix). It is the unit of the
pod's own configuration, evaluated alone: no container runs it.
'';
};
config = lib.mkMerge [
{
assertions = [
{
assertion = !onK8s || hyperhiveCfg.deploy.k8s.enable;
message = ''
services.hyperhive.deploy.claude-login.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 = [
{
@ -306,49 +258,10 @@ in
options.
'';
}
{
assertion = lib.all oneWord (lib.attrValues storeFiles);
message = ''
The claude login minter'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.
# The cluster's pods reach the host's services through the bridge.
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 daemon keeps no state; each login's scratch directory is under
# PrivateTmp.
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

@ -8,16 +8,16 @@
# reaches the socket by path, and a socket that is never bound to an
# address cannot be reached from off-host by mistake.
#
# `swarm.controller.tcp.enable` adds a TLS listener beside the socket, which the
# gateway then dials instead of the socket. The controller checks nobody per
# The controller serves a TLS listener beside the socket (`swarm.controller.tcp`,
# on by default), which the gateway dials instead of the socket. The controller checks nobody per
# request, so the listener completes a handshake for one identity only: a
# client certificate the swarm's store issued for the gateway, with the
# `clientAuth` usage. ./swarm-ui.nix still declares the vhost on the host that
# runs this daemon, so the gateway stays on that host.
#
# `deploy.swarm-controller.runtime = "k8s"` runs the daemon as a pod in this
# host's cluster instead (./k8s/render.nix renders it from the unit below). The
# unit is then disabled, and the gateway dials the pod's Service by name.
# The daemon runs as a pod in this host's cluster (./k8s/render.nix renders it
# from the unit below). The unit is disabled on the host, and the gateway dials
# the pod's Service by name.
{
pkgs,
lib,
@ -155,14 +155,8 @@ let
tcpCfg = cfg.tcp;
tcpHost = deployCfg.swarm-controller.tcp;
hiveTls = deployCfg.hive-controller.tls;
storeRetry = import ./lib/store-retry.nix { };
tcpOn = deployCfg.swarm-controller.enable && tcpCfg.enable;
# Where the daemon runs: its unit on this host, or a pod in this host's
# cluster, which ./k8s/render.nix renders from the same unit.
onK8s = deployCfg.swarm-controller.runtime == "k8s";
tlsIssue = import ./lib/swarm-controller-tls-issue.nix { inherit lib config; };
# The swarm the host's `swarmctl` talks to: this host's own, through the
# gateway, as the operator's own SSO account (`swarmctl login`). The
# controller socket then serves the gateway alone, which always sets
@ -431,34 +425,44 @@ in
# controller's host serves — three hosts that must agree on one set of
# names, so each reads them from the option every host evaluates alike.
tcp = {
enable = lib.mkEnableOption ''
the controller's TCP listener, TLS with a required client certificate.
Off: the controller serves its unix socket only, which is what the
gateway on the same host reaches it through.
enable = lib.mkOption {
type = lib.types.bool;
default = swarmDomain != null;
defaultText = lib.literalExpression "services.hyperhive.swarm.domain != null";
example = true;
description = ''
The controller's TCP listener, TLS with a required client certificate.
The controller runs as a pod, so the listener is the gateway's only way
to it: the gateway's controller locations dial {option}`domain` over TLS
and present a client leaf, and the controller accepts that one
identity. It defaults on wherever the swarm has a domain, so nothing sets
it, and a host that sets it to `false` while it runs the controller fails
the evaluation. The listener reaches only the gateway: the controller trusts its transport and
checks nobody per request, so a certificate the swarm root signed for
anything else is refused at the handshake.
On: the gateway's controller locations dial {option}`domain` over TLS
and present a client leaf, and the controller accepts that one
identity. The unix socket keeps working beside it. The listener
reaches only the gateway: the controller trusts its transport and
checks nobody per request, so a certificate the swarm root signed for
anything else is refused at the handshake.
Set it identically on every host of the swarm. The store's host
writes the two roles from it, the controller's host issues its server
leaf, and the host fronting the controller issues the gateway's client
leaf, each through an identity it already holds.
'';
Set it identically on every host of the swarm. The store's host
writes the two roles from it, the controller's host issues its server
leaf, and the host fronting the controller issues the gateway's client
leaf, each through an identity it already holds.
'';
};
domain = lib.mkOption {
type = lib.types.nullOr lib.types.str;
default = null;
default = if swarmDomain == null then null else "controller.${swarmDomain}";
defaultText = lib.literalExpression ''"controller.''${services.hyperhive.swarm.domain}"'';
example = "controller.example.org";
description = ''
The name the gateway dials the controller by. It becomes the server
The name the gateway dials the controller by, `controller.<swarm.domain>`
unless set. It becomes the server
certificate's name (the store's `swarm-controller-tls` role issues
for this name alone) and what nginx verifies the controller against.
It must resolve, from the gateway's host, to an address the
controller listens on. Required when {option}`enable` is set.
controller listens on, or, with the controller in the cluster, no
address of its own: the gateway dials the pod's Service and checks the
certificate against this name. Required when {option}`enable` is set,
and with no swarm domain there is nothing to derive it from.
'';
};
@ -618,33 +622,6 @@ in
'';
};
runtime = lib.mkOption {
type = lib.types.enum [
"host"
"k8s"
];
default = "host";
description = ''
Where the controller runs: `host` as the `swarm-controller` systemd
unit, or `k8s` as a pod in this host's cluster
({option}`services.hyperhive.deploy.k8s.enable`), which the host's
configuration must enable. A swarm runs one controller, so a switch
moves it: the unit goes and the pod is applied, or the pod is deleted
and the unit returns.
The pod needs the TCP listener
({option}`services.hyperhive.swarm.controller.tcp.enable`): the host
cannot reach a unix socket inside a pod, so the gateway dials the
listener, which a Service in the cluster publishes at
{option}`tcp.serviceHost`. The pod's state directory is an
`emptyDir`: the operator grant record is in the queue's key-value
store, and what is left in the directory (the forge avatar markers, the
legacy webhook secret the store also holds) is made again at start. A
host's legacy grant file is imported into the store by the first start
of the controller on the host, so run it there once before the switch.
'';
};
unit = lib.mkOption {
type = lib.types.raw;
readOnly = true;
@ -652,8 +629,8 @@ in
default = config.systemd.services.swarm-controller;
description = ''
The controller's evaluated systemd unit, which the cluster's manifests
are rendered from (../host-modules/k8s/render.nix). The host runs it
unless {option}`runtime` is `k8s`, and then the unit is disabled.
are rendered from (../host-modules/k8s/render.nix). The host does not run
it: the unit is disabled.
'';
};
@ -783,14 +760,12 @@ in
default = "0.0.0.0";
example = "10.0.0.5";
description = ''
Address the controller binds when
{option}`services.hyperhive.swarm.controller.tcp.enable` is set. An
The address the controller binds inside the pod. An
IPv6 address is written in brackets. Binding a port opens nothing:
{option}`openFirewall` decides who can reach it, and the TLS
handshake decides who may talk once they do.
With {option}`services.hyperhive.deploy.swarm-controller.runtime` set
to `k8s` this is the bind inside the pod, so it must stay `0.0.0.0`.
This is the bind inside the pod, so it must stay `0.0.0.0`.
'';
};
@ -801,8 +776,7 @@ in
default = "swarm-controller.${config.services.hyperhive.k8s.namespace}.svc.${config.services.hyperhive.deploy.k8s.clusterDomain}";
defaultText = lib.literalExpression ''"swarm-controller.<namespace>.svc.<cluster domain>"'';
description = ''
With {option}`services.hyperhive.deploy.swarm-controller.runtime` set
to `k8s`: the name of the Service in front of the pod's listener,
The name of the Service in front of the pod's listener,
which the gateway dials. The host's resolver answers it through the
cluster's DNS. The gateway verifies the listener's certificate as
{option}`services.hyperhive.swarm.controller.tcp.domain`, not as this
@ -827,10 +801,9 @@ in
readOnly = true;
default = "/var/lib/swarm-controller-tls";
description = ''
Where `swarm-controller-tls.service` writes the server leaf and key
the listener serves: `cert.pem` and `key.pem`, the key readable by
the controller's group alone. The daemon re-reads both when they
change, so a rotation needs no restart.
Where the pod's init container writes the server leaf and key the
listener serves: `cert.pem` and `key.pem`, in an in-memory volume. The
daemon re-reads both when they change, so a rotation needs no restart.
'';
};
@ -941,7 +914,7 @@ in
# The cluster's pods reach the host's services through the bridge, and the
# host's resolver (the hive's dnsmasq, on the bridge) answers the Service's name.
services.hyperhive.network.enable = lib.mkIf onK8s (lib.mkDefault true);
services.hyperhive.network.enable = lib.mkDefault true;
# Through the unit, not `users.users.nginx.extraGroups`: systemd resolves
# a unit's groups at start, and only a changed unit file makes the switch
@ -1005,72 +978,60 @@ in
'';
}
{
assertion = !tcpCfg.enable || (tcpCfg.domain != null && tcpCfg.clientName != null);
assertion = tcpCfg.domain != null && tcpCfg.clientName != null;
message = ''
services.hyperhive.swarm.controller.tcp.enable needs
services.hyperhive.swarm.controller.tcp.domain, the name the gateway
dials the controller by, and services.hyperhive.swarm.domain, which
the gateway's client identity is named under. Set both, or leave the
TCP listener off.
services.hyperhive.deploy.swarm-controller.enable needs
services.hyperhive.swarm.domain: the listener's name
(services.hyperhive.swarm.controller.tcp.domain, `controller.<swarm.domain>`
by default) and the gateway's client identity are named under it. Set it,
or set tcp.domain by hand and the swarm domain the client identity needs.
'';
}
{
assertion = !onK8s || config.services.hyperhive.deploy.k8s.enable;
message = ''
services.hyperhive.deploy.swarm-controller.runtime = "k8s" needs the
cluster: set services.hyperhive.deploy.k8s.enable on this host, or
leave the controller's runtime at "host".
'';
}
{
assertion = !onK8s || tcpHost.listenAddress == "0.0.0.0";
assertion = tcpHost.listenAddress == "0.0.0.0";
message = ''
services.hyperhive.deploy.swarm-controller.tcp.listenAddress is
"${tcpHost.listenAddress}", and with runtime = "k8s" it is the bind
inside the pod, where any address but "0.0.0.0" leaves the listener
"${tcpHost.listenAddress}", and it is the bind inside the pod, where any address but "0.0.0.0" leaves the listener
unbound and the pod NotReady. Leave it at "0.0.0.0".
'';
}
{
assertion = !onK8s || config.services.hyperhive.gateway.dns.enable;
assertion = config.services.hyperhive.gateway.dns.enable;
message = ''
services.hyperhive.deploy.swarm-controller.runtime = "k8s" needs
services.hyperhive.deploy.swarm-controller.enable needs
services.hyperhive.gateway.dns.enable: the gateway dials the pod's
Service by name, and the hive's resolver is what hands the cluster's
domain to its DNS. Set it, or leave the controller's runtime at "host".
domain to its DNS. Set it.
'';
}
{
assertion = !onK8s || tcpCfg.enable;
assertion = tcpCfg.enable;
message = ''
services.hyperhive.deploy.swarm-controller.runtime = "k8s" needs
services.hyperhive.swarm.controller.tcp.enable: the host cannot reach
a unix socket inside a pod, so the gateway dials the pod's TCP
listener. Set it, or leave the controller's runtime at "host".
services.hyperhive.swarm.controller.tcp.enable is false, and
services.hyperhive.deploy.swarm-controller.enable needs it: the host
cannot reach a unix socket inside a pod, so the gateway dials the pod's
TCP listener. Remove the setting, which defaults on with the swarm domain.
'';
}
{
assertion = !tcpCfg.enable || caTrust.useSelfSigned;
assertion = caTrust.useSelfSigned;
message = ''
services.hyperhive.swarm.controller.tcp.enable needs the self-signed
services.hyperhive.deploy.swarm-controller.enable needs the self-signed
gateway mode: the controller trusts the secret store's services root
for client certificates, and only a self-signed gateway host keeps
that root on disk. Leave the TCP listener off where the gateway
serves an operator certificate or ACME.
that root on disk. A gateway that serves an operator certificate or
ACME can't front the controller yet.
'';
}
];
systemd.services.swarm-controller = {
# Disabled with the controller in the cluster, so nothing can start it; the definition stays
# because the pod is rendered from the evaluated unit.
enable = !onK8s;
# Disabled: the daemon runs in the cluster. The definition stays because the
# pod is rendered from the evaluated unit.
enable = false;
description = "hyperhive swarm-level controller daemon";
wantedBy = [ "multi-user.target" ];
# The listener's certificate files must exist when the daemon opens it. A
# start that finds them missing fails and `Restart=` tries again.
after = [ "network.target" ] ++ lib.optional tcpOn "swarm-controller-tls.service";
wants = lib.optional tcpOn "swarm-controller-tls.service";
after = [ "network.target" ];
serviceConfig = {
ExecStart = "${deployCfg.swarm-controller.package}/bin/swarm-controller";
@ -1221,59 +1182,5 @@ in
networking.firewall.allowedTCPPorts = lib.mkIf (tcpOn && tcpHost.openFirewall) [ tcpCfg.port ];
# The listener's server leaf, from the store's `${tcpCfg.serverPkiRole}`
# role under the controller's own store identity — the one it already logs
# in with, whose policy gains this one issue path when the listener is on.
# Same shape as the queue's leaf unit (./swarm-nats.nix,
# `swarm-bao-nats-tls`): the daemon re-reads the files, so rotating needs
# no restart, which for this daemon would drop its job graph.
systemd.services.swarm-controller-tls = lib.mkIf (tcpOn && !onK8s) {
description = "Issue the swarm-controller's TCP listener certificate from the secret store's PKI";
wantedBy = [ "multi-user.target" ];
after = [
"container@${baoCfg.machine}.service"
"swarm-bao-pki.service"
"swarm-bao-controller-policy.service"
];
path = [
deployCfg.bao.package
pkgs.jq
pkgs.openssl
pkgs.coreutils
pkgs.gnugrep
];
# The store is sealed or unreachable for as long as it takes an operator
# to unseal it; see ./lib/store-retry.nix.
inherit (storeRetry) startLimitBurst startLimitIntervalSec;
serviceConfig = storeRetry.serviceConfig // {
Type = "oneshot";
UMask = "0077";
SyslogIdentifier = "swarm-controller-tls";
TimeoutStartSec = "5min";
};
environment = {
BAO_ADDR = "https://${baoCfg.domain}:${toString baoCfg.port}";
BAO_CLIENT_CERT = deployCfg.swarm-controller.baoClientCertFile;
BAO_CLIENT_KEY = deployCfg.swarm-controller.baoClientKeyFile;
}
// lib.optionalAttrs (deployCfg.bao.serverCaFile != null) {
BAO_CACERT = deployCfg.bao.serverCaFile;
};
script = tlsIssue.script {
login = "bao login -method=cert -token-only";
credential = "certificate";
group = "swarm-controller";
};
};
systemd.timers.swarm-controller-tls = lib.mkIf (tcpOn && !onK8s) {
description = "Daily renewal check for the swarm-controller's TCP listener certificate";
wantedBy = [ "timers.target" ];
timerConfig = {
OnCalendar = "daily";
Persistent = true;
};
};
};
}

View file

@ -881,8 +881,7 @@ in
systemd.timers.swarm-bao-grafana-oidc = storeRefreshTimer "re-read Grafana's OIDC client secret from the swarm secret store";
# The admin password: created in the store if it holds none, then copied
# into the container, under Grafana's own leaf. Same shape as
# `swarm-bao-nats-callout-xkey` in ./swarm-nats.nix. The grant is
# into the container, under Grafana's own leaf. The grant is
# `create` without `update`, so the first password stored is the one every
# later run reads, and a race between two runs leaves one value.
#

View file

@ -35,7 +35,6 @@ let
tlsCfg = config.services.hyperhive.deploy.hive-controller.tls;
gatewayCfg = config.services.hyperhive.gateway;
rootfsCheck = import ./lib/container-rootfs-check.nix { inherit config; };
caTrust = import ./lib/hive-ca-trust.nix { inherit lib tlsCfg gatewayCfg; };
# The responder introspects authelia over https BY NAME. Its HTTP client is
@ -60,17 +59,9 @@ let
# host is the only place both filesystems are addressable.
secretDirInContainer = "/var/lib/swarm-nats-auth";
inContainer = name: "${secretDirInContainer}/${name}";
secretDir = "/var/lib/nixos-containers/${machine}${secretDirInContainer}";
hostPath = name: "${secretDir}/${name}";
introspectionUrl = "${toString autheliaUrl}/api/oidc/introspection";
# Host seed files `ensure-callout-keys` stores when the secret store holds
# no seed for that key, and removes once it holds one. Never written here.
importSeedDir = "/var/lib/swarm-nats-callout";
importUserSeed = "${importSeedDir}/callout-user.seed";
importIssuerSeed = "${importSeedDir}/issuer.seed";
# The runtime config directory: wrapper, settings symlink and fragment.
# World-readable is correct (everything in it is public) and it is not in
# the 0700 responder secret dir, which the `nats` user cannot traverse.
@ -82,7 +73,6 @@ let
# eval: the wrapper renders perfectly and the server refuses to start.
runtimeDir = "/var/lib/nats-callout";
runtimeWrapper = "${runtimeDir}/nats.conf";
hostRuntimeDir = "/var/lib/nixos-containers/${machine}${runtimeDir}";
natsFormat = pkgs.formats.json { };
@ -193,7 +183,7 @@ let
};
# The callout's three public keys: where the store keeps each, the file
# `swarm-bao-nats-callout-xkey` leaves it in, the placeholder it fills in
# the pod's `callout-config` init container leaves it in, the placeholder it fills in
# `calloutTemplate`, and the shape `renderConfig` checks it has. The store
# paths are `swarm-nats-auth`'s `xkey::PUBLIC_PATH` and the `public_path` of
# its `nkey::ISSUER` and `nkey::USER`, readable by the `swarm-nats-auth` role
@ -260,7 +250,7 @@ let
${lib.concatMapStrings (k: ''
if [ ! -s "$d/${k.file}" ]; then
echo "${runtimeDir}/${k.file} is missing: swarm-bao-nats-callout-xkey on the host fetches it from the secret store, and the queue does not start without it" >&2
echo "${runtimeDir}/${k.file} is missing: the pod's callout-config init container fetches it from the secret store, and the queue does not start without it" >&2
exit 1
fi
${k.var}="$(cat "$d/${k.file}")"
@ -300,7 +290,6 @@ let
tlsCertPath = "${tlsDir}/cert.pem";
tlsKeyPath = "${tlsDir}/key.pem";
tlsKeyCredential = "tls-key";
tlsKeyCredentialPath = "/run/credentials/nats.service/${tlsKeyCredential}";
# The gateway's copy of that leaf, for the `/metrics` vhost below: the key
# here is 0640 root:nginx, so nginx reads it while the queue's own stays
@ -327,10 +316,6 @@ let
};
authCredential = id: "/run/credentials/swarm-nats-auth.service/${id}";
atomicWriteSecret = import ./lib/atomic-write-secret.nix { };
refreshConsumer = import ./lib/refresh-consumer.nix { };
storeRetry = import ./lib/store-retry.nix { };
# The script that issues the queue's leaf, which the host unit below and the
# pod's init container both run.
tlsIssue = import ./lib/swarm-nats-tls-issue.nix { inherit lib config; };
@ -352,10 +337,6 @@ let
"";
};
# Where the queue runs: in its container on this host, or as a pod in this
# host's cluster, which ./k8s/render.nix renders from the units below.
onK8s = deployCfg.nats.runtime == "k8s";
# The Service in front of the pod's exporter, and the name the host's resolver
# answers for it through the cluster's DNS.
metricsService = "${machine}-metrics";
@ -383,17 +364,8 @@ let
# the bridge firewall does not open this port.
privateNetwork = false;
# After the host restarts or starts the server in the container: the
# responder is cleared of a failed state and started. `start`, not
# `restart`: a running responder was already restarted with the server
# (`Requires=`) and so has loaded the current keys; a stopped one has not.
rearmResponder = ''
systemctl --machine=${lib.escapeShellArg machine} reset-failed swarm-nats-auth.service
systemctl --machine=${lib.escapeShellArg machine} start --no-block swarm-nats-auth.service'';
# The module the queue's container runs: its own NixOS system sharing the host's
# network namespace, or, with the queue in the cluster, only the source of the
# units the pod is rendered from (`deploy.nats.unit`, `deploy.nats.pod`).
# The queue's NixOS system: the source of the units the pod is rendered from
# (`deploy.nats.unit`, `deploy.nats.pod`).
containerConfig =
{ ... }@container:
{
@ -505,7 +477,7 @@ let
cert_file = tlsCertPath;
# The pod has no credential directory: its leaf and key are
# files of one volume.
key_file = if onK8s then tlsKeyPath else tlsKeyCredentialPath;
key_file = tlsKeyPath;
timeout = 2;
};
};
@ -752,8 +724,7 @@ let
environment.systemPackages = [ pkgs.nats-server ];
};
# The container's system, evaluated as `containers.<name>.config` evaluates
# it, for a host whose queue runs in the cluster and so has no such container.
# The queue's system, evaluated on its own: the host has no container for it.
podSystem =
(import "${pkgs.path}/nixos/lib/eval-config.nix" {
modules = [
@ -777,9 +748,8 @@ let
system = null;
}).config;
# The system the units below are read from: the container's, or the same
# configuration evaluated alone.
natsSystem = if onK8s then podSystem else config.containers.${machine}.config;
# The system the units below are read from.
natsSystem = podSystem;
# The JetStream store's directory inside the container and in the pod, and the
# container's copy of it on the host.
@ -831,8 +801,7 @@ let
'';
# The responder's own role creates the keys the store holds none of and
# reads their public halves, as `swarm-bao-nats-callout-xkey` does on the
# host. `renderConfig` is the host's script, which fails while a half is
# reads their public halves. `renderConfig` fails while a half is
# missing.
keys = pkgs.writeShellScriptBin "swarm-nats-callout-config" ''
export PATH=${lib.makeBinPath (tools ++ [ deployCfg.nats.authPackage ])}
@ -1207,8 +1176,7 @@ in
{option}`services.hyperhive.swarm.nats.domain` proxies it, behind
the swarm collector's authelia check.
With the queue in the cluster this is the exporter container's port in
the pod, which the Service `swarm-nats-metrics` publishes on the same
This is the exporter container's port in the pod, which the Service `swarm-nats-metrics` publishes on the same
number and only the node reaches.
⚠️ This and {option}`services.hyperhive.deploy.nats.monitorPort` are two
@ -1295,8 +1263,7 @@ in
description = ''
Client certificate the auth-callout responder presents to the swarm's
secret store to read the callout keys, its own OIDC client secret and
agent queue credentials, and that `swarm-bao-nats-callout-xkey`
presents to read the callout keys' public halves. Its subject must be
agent queue credentials. Its subject must be
{option}`services.hyperhive.deploy.bao.natsAuthCommonName`.
Required when `deploy.nats.enable` is set; unset fails at eval.
@ -1305,9 +1272,7 @@ in
({option}`services.hyperhive.deploy.bao.enable`); on any other queue
host it is a file the operator places. Never derived from
{option}`services.hyperhive.deploy.bao.clientCertFile`, which is the
hive's own reader. Set to a file that does
not exist, `swarm-nats-auth-secrets` and `swarm-bao-nats-callout-xkey`
fail, and the queue's server does not start without the xkey.
hive's own reader.
A path, never a value.
'';
@ -1342,36 +1307,21 @@ in
Point `nats.<swarm domain>` in the operator's upstream DNS at the
address the other hives reach.
With {option}`services.hyperhive.deploy.nats.runtime` set to `k8s` the
pod's published port has the same reach: a rule in the firewall's raw
The pod's published port has the same reach: a rule in the firewall's raw
table drops it from every interface but the host's loopback, the bridge
and the pods' unless this is set.
'';
};
runtime = lib.mkOption {
type = lib.types.enum [
"host"
"k8s"
];
default = "host";
system = lib.mkOption {
type = lib.types.raw;
readOnly = true;
internal = true;
default = natsSystem;
description = ''
Where the queue runs: `host` in its `swarm-nats` container, or `k8s` as
a pod in this host's cluster
({option}`services.hyperhive.deploy.k8s.enable`), which the host's
configuration must enable. One switch covers the server and its auth
callout: the pod holds both, so the server never runs without the
responder that admits its clients. A swarm runs one queue, so a switch
moves it: the container goes and the pod is applied, or the pod is
deleted and the container returns.
The pod's JetStream store is the container's own directory on the host,
mounted into the pod as a static local volume, so a switch moves the
process and not the bytes: streams, consumers and key-value buckets are
the same files on both sides. The container's unit hands the directory
back to the server's user at each start, and the pod's group gets read
and write access from the pod's `fsGroup`. At most one server holds the
directory, since a switch stops the one before it starts the other.
The queue's evaluated NixOS system, which the pod's units and server
settings are read from: the server, its settings and the responder. The
host runs none of it.
'';
};
@ -1382,10 +1332,8 @@ in
default = natsSystem.systemd.services.swarm-nats-auth;
description = ''
The responder's evaluated systemd unit, which the pod's main container
is rendered from (../host-modules/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 queue runs in the cluster
and the host has no container.
is rendered from (../host-modules/k8s/render.nix). It is the unit of
{option}`system`, which no container runs.
'';
};
@ -1404,18 +1352,6 @@ in
};
config = lib.mkMerge [
{
assertions = [
{
assertion = !onK8s || deployCfg.k8s.enable;
message = ''
services.hyperhive.deploy.nats.runtime = "k8s" needs the cluster: set
services.hyperhive.deploy.k8s.enable on this host, or leave the
queue's runtime at "host".
'';
}
];
}
(lib.mkIf deployCfg.nats.enable {
# The auth responder introspects authelia by name, and the gateway serves
# the exporter's `/metrics` below.
@ -1452,24 +1388,17 @@ in
# Authelia's rules for it admit the collector's client and deny
# every other subject (`metricsRules` in ./swarm-authelia.nix).
"= /metrics" = {
# In the cluster the exporter is behind a Service, which the host's
# resolver answers through the cluster's DNS. The upstream is a
# variable, so nginx asks the resolver per request: a name in the
# `proxy_pass` gets one lookup when the configuration loads, which
# fails the load while the cluster is down.
proxyPass =
if onK8s then
"http://\$swarm_nats_metrics_upstream/metrics"
else
"http://127.0.0.1:${toString deployCfg.nats.metricsPort}/metrics";
extraConfig =
lib.optionalString onK8s ''
resolver ${networkCfg.bridgeIp} valid=10s ipv6=off;
set $swarm_nats_metrics_upstream ${metricsHost}:${toString deployCfg.nats.metricsPort};
''
+ ''
auth_request /__nats_metrics_authz;
'';
# The exporter is behind a Service, which the host's resolver
# answers through the cluster's DNS. The upstream is a variable, so
# nginx asks the resolver per request: a name in the `proxy_pass`
# gets one lookup when the configuration loads, which fails the
# load while the cluster is down.
proxyPass = "http://\$swarm_nats_metrics_upstream/metrics";
extraConfig = ''
resolver ${networkCfg.bridgeIp} valid=10s ipv6=off;
set $swarm_nats_metrics_upstream ${metricsHost}:${toString deployCfg.nats.metricsPort};
auth_request /__nats_metrics_authz;
'';
};
# The subrequest, same shape as the forge's `= /__forge_metrics_authz`
@ -1545,24 +1474,23 @@ in
{
# The rules that keep the pod's ports as closed as the container's are
# iptables rules.
assertion = !onK8s || !config.networking.nftables.enable;
assertion = !config.networking.nftables.enable;
message = ''
services.hyperhive.deploy.nats.runtime = "k8s" writes iptables rules
that give the pod's ports the reach the container's have, and
services.hyperhive.deploy.nats.enable writes iptables rules that
keep the queue pod's ports as closed as the old container's were, and
networking.nftables.enable replaces iptables. Leave nftables off on
this host, or leave the queue's runtime at "host".
this host.
'';
}
{
# The gateway's `/metrics` location dials the exporter's Service by
# name, which only the hive's resolver answers.
assertion = !onK8s || config.services.hyperhive.gateway.dns.enable;
assertion = config.services.hyperhive.gateway.dns.enable;
message = ''
services.hyperhive.deploy.nats.runtime = "k8s" needs
services.hyperhive.deploy.nats.enable needs
services.hyperhive.gateway.dns.enable: the gateway dials the pod's
metrics Service by name, and the hive's resolver is what hands the
cluster's domain to its DNS. Set it, or leave the queue's runtime at
"host".
cluster's domain to its DNS. Set it.
'';
}
{
@ -1635,20 +1563,20 @@ in
# An agent reaches it by name, which dnsmasq answers with the bridge IP.
services.hyperhive.network.exposeHostPorts = [ cfg.port ];
# The server binds every address (the container shares the host netns and
# sets no listen host), so reachability is the firewall alone.
# The pod's port is published on every address of the node, so
# reachability is the firewall alone.
networking.firewall.allowedTCPPorts = lib.mkIf deployCfg.nats.openFirewall [ cfg.port ];
services.hyperhive.network.enable = lib.mkIf onK8s (lib.mkDefault true);
services.hyperhive.network.enable = lib.mkDefault true;
# An agent dials the queue at the bridge's address, and the load
# balancer's `hostPort` forwards that to the cluster, which the egress
# forward chain would refuse.
services.hyperhive.deploy.hive-controller.egress.publishedPorts = lib.mkIf onK8s [ cfg.port ];
services.hyperhive.deploy.hive-controller.egress.publishedPorts = [ cfg.port ];
# The load balancer's `hostPort` is a DNAT rule, which the INPUT rules above
# never see: ./lib/swarm-nats-raw-rules.nix gives it the container's reach.
networking.firewall.extraCommands = lib.mkIf onK8s (
networking.firewall.extraCommands = (
import ./lib/swarm-nats-raw-rules.nix { inherit lib; } {
chain = "nixos-fw-nats";
clientPort = cfg.port;
@ -1660,220 +1588,30 @@ in
openClient = deployCfg.nats.openFirewall;
}
);
networking.firewall.extraStopCommands = lib.mkIf onK8s ''
networking.firewall.extraStopCommands = ''
iptables -t raw -D PREROUTING -j nixos-fw-nats 2>/dev/null || true
iptables -t raw -F nixos-fw-nats 2>/dev/null || true
iptables -t raw -X nixos-fw-nats 2>/dev/null || true
'';
# The bind source has to exist before the container starts, leaf or not:
# nixos-container refuses to start over a missing one, which would take
# the whole queue down rather than only its TLS.
#
# The pod's local volume needs its directory to exist before the pod
# starts, which on a host that never ran the container nothing else makes.
systemd.tmpfiles.rules = [
"d ${tlsDir} 0755 root root -"
]
++ lib.optional onK8s "d ${hostStoreDir} 0700 root root -";
containers.swarm-nats = lib.mkIf (!onK8s) {
autoStart = true;
ephemeral = false;
# No `--link-journal=host`: the journal stays in the guest, where the
# container's own forwarder reads it (../container-modules/swarm-journal-forwarder.nix).
inherit privateNetwork;
# The public trust bundle (empty when the gateway is not self-signed)
# and the queue's own TLS leaf, both read-only.
bindMounts = caTrust.bindMount // {
${tlsDir} = {
hostPath = tlsDir;
isReadOnly = true;
};
};
config = containerConfig;
};
# Order the container after the host CA generator, so the bind source
# exists before nspawn sets the mount up. Without it a late CA fails the
# container start outright rather than degrading.
systemd.services."container@${machine}" = lib.mkIf (!onK8s) (
lib.mkMerge [
caTrust.containerOrdering
(rootfsCheck.warnOnly machine)
]
);
# Deliver the responder's store identity into the container before it
# starts. A copy rather than a `bindMounts` entry: nixos-container refuses
# to start when a bind source is missing, so one absent file would take
# down the **whole container including the queue**, not merely the
# responder.
systemd.services.swarm-nats-auth-secrets = {
# The pod logs in with its ServiceAccount token and holds no copy of the
# store identity.
enable = !onK8s;
description = "deliver the swarm queue responder's credentials";
before = [ "container@swarm-nats.service" ];
wantedBy = [ "container@swarm-nats.service" ];
# Where the store's PKI is minted on this host, the responder's leaf is
# one of its files, and the minting unit runs before every copy. Ordering
# alone is not enough: the queue's container, which pulls this unit in,
# starts from `machines.target`, outside the transaction that runs the
# minting unit from `multi-user.target`. Ignored elsewhere, where the unit
# does not exist.
after = [ "swarm-bao-pki.service" ];
wants = [ "swarm-bao-pki.service" ];
serviceConfig = {
Type = "oneshot";
RemainAfterExit = true;
SyslogIdentifier = "swarm-nats-auth-secrets";
};
path = [ pkgs.coreutils ];
script = ''
set -euo pipefail
install -d -m 0700 ${lib.escapeShellArg secretDir}
''
+ lib.concatStrings (
lib.mapAttrsToList (id: source: ''
install -m 0400 ${lib.escapeShellArg source} ${lib.escapeShellArg (hostPath id)}
'') authStoreFiles
);
};
# The callout's three public keys, from the store into the files
# `renderConfig` reads at every server start. `ensure-callout-keys` first
# creates each pair the store holds none of; it needs no queue, so on a
# first boot the keys exist before the server that requires them, and
# nothing here waits on the responder, which itself waits on the server.
#
# An issuer or user seed file left on this host is what `ensure-callout-keys`
# stores for that key when the store holds none, so the key keeps its
# public half. It removes the file once a read of the store returns a seed,
# in this run and never before: a removal that ran ahead of the import,
# with the store sealed, would leave the next run to mint a new key.
#
# Before the container and wanted by it, the shape `swarm-bao-nats-tls`
# has: a store that comes up later fails this run, the server refuses to
# start without the files (or starts with the ones last fetched), and the
# retry that lands them starts or restarts the server. Under the
# responder's own leaf, the one principal that may create the keys' paths.
systemd.services.swarm-bao-nats-callout-xkey = {
# The pod's init container creates the keys and fetches their public
# halves itself.
enable = !onK8s;
description = "create the swarm queue's callout keys if absent and fetch their public halves for the server";
# Ordered after the store where it runs here
# (./glue-bao-readers-store-order.nix); elsewhere the timeout below
# bounds the attempt.
before = [ "container@${machine}.service" ];
# On a host with the cluster node, also after the prune that deletes the
# queue's pod on a switch back. The prune waits for the pod to end, and
# `ensure-callout-keys` must not run beside a pod still terminating: its
# responder is a second one against the same store. The prune names
# this unit nowhere, so the order has no cycle.
after = lib.optional deployCfg.k8s.enable "${machine}-k8s-prune.service";
wantedBy = [
"multi-user.target"
"container@${machine}.service"
];
path = [
deployCfg.nats.authPackage
baoDeploy.package
pkgs.coreutils
pkgs.systemd
];
inherit (storeRetry) startLimitBurst startLimitIntervalSec;
serviceConfig = storeRetry.serviceConfig // {
Type = "oneshot";
RemainAfterExit = true;
SyslogIdentifier = "swarm-bao-nats-callout-xkey";
TimeoutStartSec = 30;
};
environment = {
BAO_ADDR = "https://${baoCfg.domain}:${toString baoCfg.port}";
BAO_CLIENT_CERT = deployCfg.nats.authBaoClientCertFile;
BAO_CLIENT_KEY = deployCfg.nats.authBaoClientKeyFile;
}
// lib.optionalAttrs (baoDeploy.serverCaFile != null) {
BAO_CACERT = baoDeploy.serverCaFile;
};
script = ''
set -euo pipefail
${atomicWriteSecret}
${refreshConsumer}
swarm-nats-auth ensure-callout-keys --store-cert-role ${lib.escapeShellArg authCertRole} \
--import-issuer-seed-file ${lib.escapeShellArg importIssuerSeed} \
--import-user-seed-file ${lib.escapeShellArg importUserSeed}
if [ -d ${lib.escapeShellArg importSeedDir} ]; then
rmdir --ignore-fail-on-non-empty ${lib.escapeShellArg importSeedDir}
fi
err="$(mktemp)"
trap 'rm -f "$err"' EXIT
if ! BAO_TOKEN="$(bao login -method=cert -token-only 2>"$err")"; then
echo "could not log in to swarm-bao with the queue responder's certificate; leaving the callout key files as they are." >&2
cat "$err" >&2
exit 1
fi
export BAO_TOKEN
install -d -m 0755 ${lib.escapeShellArg hostRuntimeDir}
''
+ lib.concatMapStrings (
k:
let
file = "${hostRuntimeDir}/${k.file}";
in
''
if ! key="$(bao kv get -field=value ${lib.escapeShellArg k.storePath} 2>"$err")"; then
echo "swarm-bao did not return ${k.storePath}." >&2
cat "$err" >&2
exit 1
fi
if [ -z "$key" ]; then
echo "swarm-bao returned an empty ${k.storePath}." >&2
exit 1
fi
if secret_differs ${lib.escapeShellArg file} "$key"; then
atomic_write_secret 0444 "" ${lib.escapeShellArg file} "$key"
fi
''
) calloutPublicKeys
# `renderConfig` reads the files as the server starts, and only then.
+ lib.concatMapStrings (k: ''
refresh_consumer ${lib.escapeShellArg machine} nats.service ${lib.escapeShellArg "${hostRuntimeDir}/${k.file}"}
'') calloutPublicKeys
+ ''
if systemctl is-active --quiet ${lib.escapeShellArg "container@${machine}.service"}; then
${rearmResponder}
fi
'';
};
"d ${hostStoreDir} 0700 root root -"
];
# The queue's TLS leaf, issued by the secret store's `pki/roles/swarm-nats`
# under this host's `swarm-nats` identity. Same shape as ./hive-tls.nix's
# `swarm-services-cert`, whose comments carry the reasoning for the login,
# the single `issue` call split with `jq`, and the unseal-sized retry.
#
# Before the container, so a normal boot starts the server with its leaf.
# A store that comes up later fails this run; the retry lands the leaf and
# restarts the server, which until then refuses to start (TLS required,
# and its key credential is missing).
#
# With the queue in the cluster this leaf is the gateway's `/metrics` vhost
# alone: the pod issues the one its server presents, and nothing here
# restarts a server.
# This leaf is the gateway's `/metrics` vhost alone: the pod issues the one
# its server presents, and nothing here restarts a server. A store that
# comes up later fails this run; the retry lands the leaf.
systemd.services.swarm-bao-nats-tls = {
description = "Issue the swarm queue's TLS leaf from the secret store's PKI";
wantedBy = [
"multi-user.target"
]
++ lib.optional (!onK8s) "container@${machine}.service";
before = lib.optional (!onK8s) "container@${machine}.service";
wantedBy = [ "multi-user.target" ];
# Both absent where the store runs elsewhere, and ignored there; see
# `swarm-services-cert`. The ordering after this leaf's policy unit is
# ./glue-bao-readers-policy-order.nix's, because it holds only where the
@ -1900,9 +1638,6 @@ in
SyslogIdentifier = "swarm-bao-nats-tls";
Restart = "on-failure";
RestartSec = 30;
# An attempt that rotates the leaf waits on a blocking restart of the
# server in its container: up to 150s to stop (nixpkgs' nats module)
# and 90s to start.
TimeoutStartSec = "5min";
};
environment = {
@ -1924,17 +1659,6 @@ in
# The gateway's `/metrics` vhost serves a copy of this leaf.
systemctl start swarm-nats-gateway-cert.service''}
# Renewal, or the late-store retry. On a normal boot the container is
# not up yet and starts the server with this leaf itself. A restart,
# not a reload: the key arrives by `LoadCredential`, which systemd
# resolves at start only. `reset-failed` because a server that found
# no key may have hit its start limit.
if systemctl is-active --quiet ${lib.escapeShellArg "container@${machine}.service"}; then
echo "queue leaf rotated — restarting the server in ${machine}"
systemctl --machine=${lib.escapeShellArg machine} reset-failed nats.service
systemctl --machine=${lib.escapeShellArg machine} restart nats.service
${rearmResponder}
fi
'';
};

View file

@ -1,22 +1,17 @@
# The swarm notification router, in a `swarm-notify-router` container on the
# The swarm notification router, a pod in the host's cluster on the
# host that sets `deploy.notify-router.enable`, which `deploy.allSwarmServices`
# defaults on where the host has the router's store identity. It reads the
# forge events swarm-controller keeps from its webhooks and queues todo ops on
# each agent's subject of `ROUTER_TODOS`, which the agent's harness applies.
# docs/4-implementation/swarm/notify-router.md has the design.
#
# With `deploy.notify-router.runtime = "k8s"` the host has no container: the
# router runs as a pod in the host's cluster, which ../host-modules/k8s renders
# from the unit this file defines. docs/4-implementation/k8s/runtime.md has
# the switch.
# The pod is rendered (./k8s/render.nix) from the unit this file defines;
# docs/4-implementation/k8s/runtime.md has the design. It reaches the swarm
# services by name and nothing on the host's loopback. It talks only to the
# queue, the store and authelia, so it can run on any host.
#
# Its own network namespace on the bridge, as ./swarm-claude-login.nix has: it
# reaches the swarm services by name and nothing on the host's loopback. It
# talks only to the queue, the store and authelia, so it can run on any host.
#
# The container holds one credential, its own store leaf, which nspawn hands in
# as a system credential with no copy on disk. The daemon reads its queue
# client secret with it.
# The unit names its store leaf by credential id; the pod logs in to the store
# with its ServiceAccount token instead, and reads its queue client secret with it.
{
pkgs,
lib,
@ -52,8 +47,6 @@ let
# takes the router's metrics there and pushes them to the swarm collector.
forwarderOtlpPort = 4318;
rootfsCheck = import ./lib/container-rootfs-check.nix { inherit config; };
# The daemon reaches authelia, the store and the queue by name over TLS, and
# in self-signed mode their leaves chain to the hive CA.
caTrust = import ./lib/hive-ca-trust.nix { inherit lib tlsCfg gatewayCfg; };
@ -77,19 +70,13 @@ let
notify-router-bao-key = baoDeploy.notifyRouterClientKeyFile;
notify-router-bao-server-ca = baoDeploy.serverCaFile;
};
# nixos-container expands `extraFlags` unquoted, so a source path must be
# one word.
oneWord = path: builtins.match ".*[[:space:]].*" path == null;
credential = id: "/run/credentials/${unit}.service/${id}";
forwarderCredential = id: "/run/credentials/${forwarderUnit}.service/${id}";
privateNetwork = true;
onK8s = cfg.runtime == "k8s";
# The module the container runs: its own NixOS system on the host's bridge,
# or, with the router on the cluster, only the source of the unit the pod is
# rendered from (`deploy.notify-router.unit`).
# The unit the pod is rendered from (`deploy.notify-router.unit`) is
# defined in this module.
containerConfig =
{ lib, ... }:
{
@ -166,7 +153,7 @@ let
User = unit;
Group = unit;
UMask = "0077";
# Bare ids: the system credentials nspawn handed in.
# Bare ids, which the pod's login replaces.
LoadCredential = lib.attrNames storeFiles;
Restart = "on-failure";
RestartSec = "10s";
@ -175,8 +162,8 @@ let
};
};
# The container's system, evaluated as `containers.<name>.config` evaluates
# it, for a host that has no such container.
# The service's NixOS system, evaluated on its own: its unit is what the pod is
# rendered from.
podSystem =
(import "${pkgs.path}/nixos/lib/eval-config.nix" {
modules = [
@ -219,55 +206,19 @@ in
description = "The notification router daemon package.";
};
options.services.hyperhive.deploy.notify-router.runtime = lib.mkOption {
type = lib.types.enum [
"host"
"k8s"
];
default = "host";
description = ''
Where the notification router runs: `host` in its `swarm-notify-router`
container, or `k8s` as a pod in this host's cluster
({option}`services.hyperhive.deploy.k8s.enable`), which the host's
configuration must enable. The router runs once per swarm, so a switch
moves it: the container goes and its objects are applied, or the objects
are deleted and the container returns. The router keeps nothing on the
host: its consumer and state bucket live in the queue.
'';
};
options.services.hyperhive.deploy.notify-router.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};
default = podSystem.systemd.services.${unit};
description = ''
The router's evaluated systemd unit, which the cluster's manifests are
rendered from (../host-modules/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 router runs in the cluster
and the host has no container.
rendered from (../host-modules/k8s/render.nix). It is the unit of the
pod's own configuration, evaluated alone: no container runs it.
'';
};
config = lib.mkMerge [
{
assertions = [
{
assertion = !onK8s || hyperhiveCfg.deploy.k8s.enable;
message = ''
services.hyperhive.deploy.notify-router.runtime = "k8s" needs the
cluster: set services.hyperhive.deploy.k8s.enable on this host, or
leave the router's runtime at "host".
'';
}
];
}
(lib.mkIf cfg.enable {
assertions = [
{
@ -288,49 +239,10 @@ in
two options.
'';
}
{
assertion = lib.all oneWord (lib.attrValues storeFiles);
message = ''
The notification router'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.
# The cluster's pods reach the host's services through the bridge.
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 daemon keeps its state in the queue: its consumer's position and
# its per-issue snapshots.
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

@ -1,21 +1,19 @@
# The review classifier, in a `swarm-review-classifier` container on the host
# The review classifier, a pod in the host's cluster on the host
# that sets `deploy.review-classifier.enable`, which `deploy.allSwarmServices`
# defaults on where the host has the classifier's store identity. It answers the
# swarm UI's review try-outs: swarm-controller sends a PR and the operator's classifications over
# the queue, and the daemon runs `claude`, or `opencode` on the ACP runtime,
# once per classification and replies.
# docs/4-implementation/swarm/review-classifier.md has the design.
# With `deploy.review-classifier.runtime = "k8s"` it runs as a pod instead,
# rendered from the unit below (docs/4-implementation/k8s/runtime.md).
# docs/4-implementation/swarm/review-classifier.md has the design. The pod is
# rendered (./k8s/render.nix) from the unit below
# (docs/4-implementation/k8s/runtime.md).
#
# ⚠️ Its own network namespace on the bridge, as ./swarm-ci-runner.nix has: a
# PR's diff and commit messages are model input, so the container reaches the
# ⚠️ A PR's diff and commit messages are model input, so the pod reaches the
# swarm services by name and nothing on the host's loopback.
#
# The container holds one credential, its own store leaf, which nspawn hands in
# as a system credential with no copy on disk. The daemon reads everything else
# from the store with it: its queue client secret at start and the run's
# runtime's key on every run.
# The unit names its store leaf by credential id; the pod logs in to the store
# with its ServiceAccount token instead. The daemon reads its queue client secret
# at start and the run's runtime's key on every run with it.
{
pkgs,
lib,
@ -59,8 +57,6 @@ let
# The standard OTLP/HTTP port, on the container's loopback.
forwarderOtlpPort = 4318;
rootfsCheck = import ./lib/container-rootfs-check.nix { inherit config; };
# The daemon reaches authelia, the store and the queue by name over TLS, and
# in self-signed mode their leaves chain to the hive CA.
caTrust = import ./lib/hive-ca-trust.nix { inherit lib tlsCfg gatewayCfg; };
@ -78,19 +74,13 @@ let
haveClientIdentity =
baoDeploy.reviewClassifierClientCertFile != null && baoDeploy.reviewClassifierClientKeyFile != null;
# Credential id → host source. nspawn reads each source as root when the
# container starts and hands it in as a system credential, held in memory;
# the daemon's unit alone loads them. No copy lands on disk, as for an
# agent's own leaf (`nix/agent-modules/bao.nix`). Ids carry no dot, the
# spelling `--load-credential` is safe with.
# Credential id → host source. The unit names the credentials by id, and the
# pod takes the id from the unit.
storeFiles = lib.filterAttrs (_: source: source != null) {
review-classifier-bao-cert = baoDeploy.reviewClassifierClientCertFile;
review-classifier-bao-key = baoDeploy.reviewClassifierClientKeyFile;
review-classifier-bao-server-ca = baoDeploy.serverCaFile;
};
# nixos-container expands `extraFlags` unquoted, so a source path must be
# one word.
oneWord = path: builtins.match ".*[[:space:]].*" path == null;
credential = id: "/run/credentials/${unit}.service/${id}";
forwarderCredential = id: "/run/credentials/${forwarderUnit}.service/${id}";
@ -113,11 +103,8 @@ let
privateNetwork = true;
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.review-classifier.unit`).
# The unit the pod is rendered from (`deploy.review-classifier.unit`) is
# defined in this module.
containerConfig =
{ pkgs, lib, ... }:
{
@ -192,7 +179,7 @@ let
DynamicUser = true;
# Each classification's scratch directory, gone with the unit.
PrivateTmp = true;
# Bare ids: the system credentials nspawn handed in.
# Bare ids, which the pod's login replaces.
LoadCredential = lib.attrNames storeFiles;
Restart = "on-failure";
RestartSec = "10s";
@ -201,8 +188,8 @@ let
};
};
# The container's system, evaluated as `containers.<name>.config` evaluates
# it, for a host that has no such container.
# The service's NixOS system, evaluated on its own: its unit is what the pod is
# rendered from.
podSystem =
(import "${pkgs.path}/nixos/lib/eval-config.nix" {
modules = [
@ -245,55 +232,19 @@ in
description = "The review classifier daemon package.";
};
options.services.hyperhive.deploy.review-classifier.runtime = lib.mkOption {
type = lib.types.enum [
"host"
"k8s"
];
default = "host";
description = ''
Where the review classifier runs: `host` in its `swarm-review-classifier`
container, or `k8s` as a pod in this host's cluster
({option}`services.hyperhive.deploy.k8s.enable`), which the host's
configuration must enable. A switch moves the service: the container
goes and its objects are applied, or the objects are deleted and the
container returns. The service keeps no state, so nothing moves with it;
each classification's scratch directory is in the pod's `/tmp` volume and goes with the pod.
'';
};
options.services.hyperhive.deploy.review-classifier.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};
default = podSystem.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.
rendered from (./k8s/render.nix). It is the unit of the
pod's own configuration, evaluated alone: no container runs it.
'';
};
config = lib.mkMerge [
{
assertions = [
{
assertion = !onK8s || hyperhiveCfg.deploy.k8s.enable;
message = ''
services.hyperhive.deploy.review-classifier.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 = [
{
@ -314,55 +265,10 @@ in
and name them in those two options.
'';
}
{
assertion = lib.all oneWord (lib.attrValues storeFiles);
message = ''
The review classifier'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.
# The cluster's pods reach the host's services through the bridge.
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 pulls the
# minting unit in and waits for it. Ordering alone is not enough: the
# container starts from `machines.target`, outside the transaction that
# runs the minting unit from `multi-user.target`. Ignored elsewhere, where
# the unit does not exist.
systemd.services."container@${machine}" = lib.mkMerge [
caTrust.containerOrdering
(rootfsCheck.warnOnly machine)
{
after = [ "swarm-bao-pki.service" ];
wants = [ "swarm-bao-pki.service" ];
}
];
containers.${machine} = {
autoStart = true;
# The daemon keeps no state; its scratch directories are under PrivateTmp.
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

@ -1,33 +1,23 @@
# The swarm's speech-to-text service, in a `swarm-stt` container on the host
# The swarm's speech-to-text service, a pod in the host's cluster on the host
# that sets `deploy.stt.enable`, which `deploy.allSwarmServices` defaults on
# 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
# (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. With
# `deploy.stt.runtime = "k8s"` it runs as a pod instead, rendered from the unit
# below (docs/4-implementation/k8s/runtime.md).
# is. docs/4-implementation/swarm/stt.md has the design. The pod is 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
# unprivileged user under a tight systemd sandbox (see `serviceConfig` below),
# with a memory and CPU ceiling, and a state directory as its only writable
# path.
# path. The pod's NetworkPolicy lets it reach cluster DNS, the store, the
# identity provider, the queue and the hive collector, and admits no ingress
# (./k8s/render.nix).
#
# Its own network namespace on the bridge, as ./swarm-claude-login.nix has: it
# reaches the swarm services by name and nothing on the host's loopback. It
# needs only the queue, the store and authelia, so it can run on any host.
#
# ⚠️ Nothing here limits what it may reach: the container's egress is whatever
# the bridge and the host's NAT allow. `ffmpeg` and `whisper-cli` run as
# children of the daemon, in the same network namespace and user, and can read
# the unit's credentials (the store leaf, the queue client secret). A decoder
# exploit on a hostile file could read them and send them out. The sandbox
# below narrows what such an exploit can do on the host; the network side
# waits on the strict-egress series covering service containers, or on running
# the decode in a child with no network and no credentials.
#
# The container holds one credential, its own store leaf, which nspawn hands in
# as a system credential with no copy on disk. The daemon reads its queue
# client secret with it.
# The daemon holds one credential, its own store leaf, and reads its queue
# client secret with it. `ffmpeg` and `whisper-cli` run as children of the
# daemon, under the same user, and can read it: a decoder exploit on a hostile
# file could read it and use it against the hosts the policy allows. Running the
# decode in a child with no network and no credentials would close that.
{
pkgs,
lib,
@ -63,8 +53,6 @@ let
# takes the service's metrics there and pushes them to the swarm collector.
forwarderOtlpPort = 4318;
rootfsCheck = import ./lib/container-rootfs-check.nix { inherit config; };
# The daemon reaches authelia, the store and the queue by name over TLS, and
# in self-signed mode their leaves chain to the hive CA.
caTrust = import ./lib/hive-ca-trust.nix { inherit lib tlsCfg gatewayCfg; };
@ -87,9 +75,6 @@ let
stt-bao-key = baoDeploy.sttClientKeyFile;
stt-bao-server-ca = baoDeploy.serverCaFile;
};
# nixos-container expands `extraFlags` unquoted, so a source path must be
# one word.
oneWord = path: builtins.match ".*[[:space:]].*" path == null;
credential = id: "/run/credentials/${unit}.service/${id}";
forwarderCredential = id: "/run/credentials/${forwarderUnit}.service/${id}";
@ -109,11 +94,8 @@ let
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`).
# The unit the pod is rendered from (`deploy.stt.unit`) is
# defined in this module.
containerConfig =
{ lib, ... }:
{
@ -195,7 +177,7 @@ let
User = unit;
Group = unit;
UMask = "0077";
# Bare ids: the system credentials nspawn handed in.
# Bare ids, which the pod's login replaces.
LoadCredential = lib.attrNames storeFiles;
Restart = "on-failure";
RestartSec = "10s";
@ -246,8 +228,8 @@ let
};
};
# The container's system, evaluated as `containers.<name>.config` evaluates
# it, for a host that has no such container.
# The service's NixOS system, evaluated on its own: its unit is what the pod is
# rendered from.
podSystem =
(import "${pkgs.path}/nixos/lib/eval-config.nix" {
modules = [
@ -344,58 +326,19 @@ in
};
};
options.services.hyperhive.deploy.stt.runtime = lib.mkOption {
type = lib.types.enum [
"host"
"k8s"
];
default = "host";
description = ''
Where the speech-to-text service runs: `host` in its `swarm-stt`
container, or `k8s` as a pod in this host's cluster
({option}`services.hyperhive.deploy.k8s.enable`), which the host's
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
the service: the container goes and its objects are applied, or the
objects are deleted and the container returns. The transcript cache is
in the container's state directory on the host, and in an `emptyDir` of the
pod; neither moves with the service, so a transcript is
made again after a switch.
'';
};
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};
default = podSystem.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.
rendered from (./k8s/render.nix). It is the unit of the
pod's own configuration, evaluated alone: no container runs it.
'';
};
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 = [
{
@ -416,48 +359,10 @@ in
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.
# The cluster's pods reach the host's services through the bridge.
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

@ -98,40 +98,27 @@ let
serverName = if matrixCfg.serverName != null then matrixCfg.serverName else apex;
servesMatrixDiscovery = matrixCfg.gatewayHost != null && serverName == apex;
# How the gateway reaches the controller. Its unix socket by default. With
# the controller's TCP listener on, over TLS by the listener's name, with
# How the gateway reaches the controller: over TLS by the listener's name, with
# the gateway's client leaf — the listener refuses a handshake without it
# (./swarm-controller.nix). `controllerDial` is empty on the socket, so the
# two locations below render exactly what they rendered before the
# listener existed.
# (./swarm-controller.nix, which asserts the listener is on).
# `toString` below so an unset `domain` reaches the assertion that names it
# instead of failing evaluation first.
controllerTcp = swarmCfg.controller.tcp;
# In the cluster the listener is behind a Service, which the host's resolver
# The listener is behind a Service in the cluster, which the host's resolver
# answers through the cluster's DNS. The upstream is a variable, so nginx asks
# the resolver per request: a name in the `proxy_pass` is looked up when the
# configuration loads, which fails the load while the cluster is not up and
# keeps the address of a Service that has since been recreated. The name the
# certificate is verified as stays `tcp.domain` (`controllerDial`), so the
# Service needs no certificate name of its own.
controllerOnCluster = deployCfg.swarm-controller.runtime == "k8s";
controllerUpstream =
if controllerTcp.enable then
if controllerOnCluster then
"https://$swarm_controller_upstream"
else
"https://${toString controllerTcp.domain}:${toString controllerTcp.port}"
else
"http://unix:${deployCfg.swarm-controller.socketPath}:";
controllerUpstream = "https://$swarm_controller_upstream";
# `proxy_http_version` and `Connection` because `recommendedProxySettings`,
# which sets them, is off on a location that pins its own `Host`: without
# them nginx speaks HTTP/1.0 to the upstream, which ends the SSE streams'
# keep-alive.
controllerDial = lib.optionalString controllerTcp.enable ''
${lib.optionalString controllerOnCluster ''
resolver ${config.services.hyperhive.network.bridgeIp} valid=10s ipv6=off;
set $swarm_controller_upstream ${deployCfg.swarm-controller.tcp.serviceHost}:${toString controllerTcp.port};
''}
controllerDial = ''
resolver ${config.services.hyperhive.network.bridgeIp} valid=10s ipv6=off;
set $swarm_controller_upstream ${deployCfg.swarm-controller.tcp.serviceHost}:${toString controllerTcp.port};
${gatewayCfg.lib.verifiedProxyToWithClientCert (toString controllerTcp.domain) {
certificate = deployCfg.swarm-controller.tcp.gatewayClientCertFile;
key = deployCfg.swarm-controller.tcp.gatewayClientKeyFile;
@ -139,7 +126,7 @@ let
proxy_http_version 1.1;
proxy_set_header Connection "";
'';
controllerDialAttrs = lib.optionalAttrs controllerTcp.enable {
controllerDialAttrs = {
# nixpkgs appends its own `Host $host` after `extraConfig`, which would
# override the pinned one — see the comment on verifiedProxyTo in
# hive-gateway/vhost-lib.nix.
@ -149,7 +136,7 @@ in
{
# No `enable` of its own: the UI is on wherever
# `services.hyperhive.deploy.swarm-controller.enable` is, because it reaches
# that daemon over its unix socket, or over its TCP listener when that is on.
# that daemon over its TCP listener.
# There is no `domain` option: the UI answers on the swarm apex, which the
# swarm already declares once.
@ -400,7 +387,7 @@ in
// {
proxyPass = controllerUpstream;
}
// lib.optionalAttrs controllerTcp.enable {
// {
extraConfig = controllerDial;
};
# Swagger UI: same "nginx hosts the themed dist straight from