Load balancers

router.loadBalancers: services on several hosts (HAProxy) with HTTP
checks, TLS terminated on the router or passed through, the client in
X-Forwarded-For or the PROXY protocol, host names that choose a service
on a shared port and are published in the local DNS. A status page lists
the backends.
This commit is contained in:
2026-11-27 20:54:45 +01:00
parent 2aa70630d4
commit 553361f811
16 changed files with 1349 additions and 3 deletions
+142
View File
@@ -0,0 +1,142 @@
{ config, lib, ... }:
let
cfg = config.router;
lbs = cfg.loadBalancers;
names = lib.attrNames lbs;
lans = lib.attrValues cfg.lans;
acme = cfg.acme;
acmeName = if acme.domains == [ ] then "unset" else lib.head acme.domains;
acmePem = "/var/lib/acme/${acmeName}/full.pem";
# Reservation name -> address, across the LANs.
reserved = lib.foldl' (acc: l: acc // lib.mapAttrs (_: r: r.address) l.dhcp.reservations) { } lans;
isAddress = b: builtins.match "[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+" b != null;
addressOf = b: if isAddress b then b else reserved.${b} or null;
backendPort = lb: if lb.backendPort != null then lb.backendPort else lb.listen.port;
usesAcme = lb: lb.tls == "terminate" && lb.certificate == null;
certOf = lb: if lb.certificate != null then toString lb.certificate else acmePem;
# Services by port: one frontend each, the host name chooses the backend.
ports = lib.unique (map (n: lbs.${n}.listen.port) names);
onPort = port: lib.filter (n: lbs.${n}.listen.port == port) names;
hostAcl =
lb: hosts:
let
list = lib.concatMapStringsSep " " (h: lib.toLower h) hosts;
in
if lb.tls == "passthrough" then
"{ req_ssl_sni -i ${list} }"
else if lb.protocol == "http" then
"{ hdr(host),field(1,:) -i ${list} }"
else
"{ ssl_fc_sni -i ${list} }";
frontend =
port:
let
members = onPort port;
first = lbs.${lib.head members};
certs = lib.unique (map (n: certOf lbs.${n}) (lib.filter (n: lbs.${n}.tls == "terminate") members));
withHosts = lib.filter (n: lbs.${n}.hosts != [ ]) members;
without = lib.filter (n: lbs.${n}.hosts == [ ]) members;
http = first.protocol == "http";
# (IPv4 and IPv6 apart: one dual-stack socket shows IPv4 clients as ::ffff:a.b.c.d.)
tlsArgs = lib.optionalString (first.tls == "terminate") (
" ssl ${lib.concatMapStringsSep " " (c: "crt ${c}") certs}${lib.optionalString http " alpn h2,http/1.1"}"
);
in
''
frontend fe_${toString port}
mode ${first.protocol}
bind 0.0.0.0:${toString port}${tlsArgs}
bind :::${toString port} v6only${tlsArgs}
${lib.optionalString (first.tls == "passthrough") ''
tcp-request inspect-delay 5s
tcp-request content accept if { req_ssl_hello_type 1 }
''}${lib.concatMapStrings (n: ''
use_backend be_${n} if ${hostAcl lbs.${n} lbs.${n}.hosts}
'') withHosts}${lib.concatMapStrings (n: ''
default_backend be_${n}
'') without}
'';
server =
lb: n: b:
let
addr = addressOf b;
secure = lb.backendTls.enable;
verify =
if lb.backendTls.verify then
"verify required${lib.optionalString (lb.backendTls.caFile != null) " ca-file ${toString lb.backendTls.caFile}"}"
else
"verify none";
# Passthrough sends the client's bytes as they are: only the checks speak TLS.
traffic = lib.optionalString (secure && lb.tls != "passthrough") " ssl ${verify}";
checks = " check${lib.optionalString secure " check-ssl ${verify}"}${lib.optionalString lb.proxyProtocol " check-send-proxy"}";
proxy = lib.optionalString lb.proxyProtocol " send-proxy-v2";
in
" server ${lib.replaceStrings [ "." ] [ "-" ] b} ${addr}:${toString (backendPort lb)}${checks}${traffic}${proxy}";
backend = n: ''
backend be_${n}
mode ${lbs.${n}.protocol}
balance ${lbs.${n}.balance}
timeout check ${lbs.${n}.check.timeout}
default-server inter ${lbs.${n}.check.interval} fall ${toString lbs.${n}.check.fall} rise ${toString lbs.${n}.check.rise}
${lib.optionalString lbs.${n}.check.useHttp ''
option httpchk
http-check send meth GET uri ${lbs.${n}.check.path} ver HTTP/1.1 hdr Host ${
if lbs.${n}.hosts == [ ] then "localhost" else lib.head lbs.${n}.hosts
}
''}${lib.optionalString (lbs.${n}.protocol == "http") ''
option forwardfor
''}${
# (An unknown backend is an assertion's to report; the text must still be valid.)
lib.concatMapStringsSep "\n" (b: server lbs.${n} n b) (lib.filter (b: addressOf b != null) lbs.${n}.backends)
}
'';
haproxyConfig = ''
defaults
log stdout format raw local0
timeout connect 5s
timeout client 1m
timeout server 1m
timeout check 2s
option redispatch
retries 2
${lib.concatMapStringsSep "\n" frontend ports}
${lib.concatMapStringsSep "\n" backend names}
'';
in
{
config = lib.mkIf (cfg.enable && names != [ ]) {
services.haproxy = {
enable = true;
config = haproxyConfig;
};
# The router's own certificate, for services that decrypt with it.
security.acme.certs = lib.mkIf (acme.enable && lib.any (n: usesAcme lbs.${n}) names) {
${acmeName} = {
group = "haproxy";
reloadServices = [ "haproxy.service" ];
};
};
# A service's names are the router's own for the LANs it listens in.
router.dns.hosts = lib.mkMerge (
map (
n:
let
lb = lbs.${n};
addrs = lib.concatMap (l: lib.optional (lib.elem l.zone lb.listen.zones) l.ipv4.address) lans;
in
lib.mkIf (addrs != [ ]) (lib.genAttrs lb.hosts (_: lib.mkDefault addrs))
) names
);
};
}