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
+225
View File
@@ -0,0 +1,225 @@
package main
import (
"encoding/csv"
"errors"
"fmt"
"io"
"net"
"net/http"
"sort"
"strconv"
"strings"
"time"
)
// Load balancers (router.loadBalancers) are run by HAProxy; this page shows
// what it says about each backend. The configuration is edited in Advanced.
// LBServer is one backend of a service, as HAProxy sees it.
type LBServer struct {
Name string
Address string
Status string // UP, DOWN, MAINT, NOLB, ... (HAProxy's words)
Check string // what the last check found, e.g. "L7OK/200"
Current int // connections now
Total int // connections since HAProxy started
Since int // seconds in this state
Up bool
}
// LBStatus is one service: the saved configuration and the running state.
type LBStatus struct {
Name string
Port int
Zones string
TLS string
Protocol string
Hosts string
Balance string
Servers []LBServer
Running bool // HAProxy knows the service
Up bool // the service has at least one backend that is up
}
func (s System) haproxySocket() string {
if s.HAProxySocket != "" {
return s.HAProxySocket
}
return "/run/haproxy/haproxy.sock"
}
// haproxyCommand sends one command to HAProxy's socket and returns the answer.
func haproxyCommand(socket, command string) (string, error) {
c, err := net.DialTimeout("unix", socket, 2*time.Second)
if err != nil {
return "", err
}
defer c.Close()
c.SetDeadline(time.Now().Add(3 * time.Second))
if _, err := io.WriteString(c, command+"\n"); err != nil {
return "", err
}
data, err := io.ReadAll(io.LimitReader(c, 4<<20))
return string(data), err
}
// parseServerAddresses reads `show servers state` (a version line, then a
// "# " line naming the columns, then one line per server) into the address
// of each server, keyed "backend/server". (The `addr` column of `show stat`
// is empty in the CSV.)
func parseServerAddresses(data string) map[string]string {
out := map[string]string{}
var col map[string]int
for _, line := range strings.Split(data, "\n") {
f := strings.Fields(line)
if len(f) == 0 {
continue
}
if f[0] == "#" {
col = map[string]int{}
for i, name := range f[1:] {
col[name] = i
}
continue
}
be, sv, addr, port := col["be_name"], col["srv_name"], col["srv_addr"], col["srv_port"]
if col == nil || len(f) <= max(be, sv, addr, port) {
continue
}
out[f[be]+"/"+f[sv]] = f[addr] + ":" + f[port]
}
return out
}
// parseHAProxyStat reads the CSV of `show stat` (its first line names the
// columns) into the servers of each backend, keyed by the proxy name.
func parseHAProxyStat(data string) (map[string][]LBServer, error) {
data = strings.TrimPrefix(strings.TrimSpace(data), "# ")
r := csv.NewReader(strings.NewReader(data))
r.FieldsPerRecord = -1
rows, err := r.ReadAll()
if err != nil {
return nil, err
}
if len(rows) == 0 {
return nil, errors.New("HAProxy answered nothing")
}
col := map[string]int{}
for i, name := range rows[0] {
col[name] = i
}
for _, need := range []string{"pxname", "svname", "status"} {
if _, ok := col[need]; !ok {
return nil, fmt.Errorf("the statistics have no %q column", need)
}
}
get := func(row []string, name string) string {
if i, ok := col[name]; ok && i < len(row) {
return row[i]
}
return ""
}
num := func(row []string, name string) int {
n, _ := strconv.Atoi(get(row, name))
return n
}
out := map[string][]LBServer{}
for _, row := range rows[1:] {
px, sv := get(row, "pxname"), get(row, "svname")
if !strings.HasPrefix(px, "be_") || sv == "" {
continue
}
status := get(row, "status")
srv := LBServer{
Name: sv, Address: get(row, "addr"), Status: status,
Current: num(row, "scur"), Total: num(row, "stot"), Since: num(row, "lastchg"),
Up: strings.HasPrefix(status, "UP") || status == "OPEN",
}
if cs := get(row, "check_status"); cs != "" {
srv.Check = cs
if code := get(row, "check_code"); code != "" {
srv.Check += "/" + code
}
}
out[strings.TrimPrefix(px, "be_")] = append(out[strings.TrimPrefix(px, "be_")], srv)
}
return out, nil
}
// loadBalancers is the saved configuration with HAProxy's state beside it.
func (a *app) loadBalancers(s Settings) ([]LBStatus, string) {
router, _ := s["router"].(map[string]any)
cfg, _ := router["loadBalancers"].(map[string]any)
var out []LBStatus
for name, v := range cfg {
lb, _ := v.(map[string]any)
st := LBStatus{Name: name, TLS: str(lb, "tls"), Protocol: str(lb, "protocol"), Balance: str(lb, "balance"),
Hosts: strings.Join(stringList(lb, "hosts"), ", ")}
if st.TLS == "" {
st.TLS = "terminate"
}
if st.Balance == "" {
st.Balance = "roundrobin"
}
if st.Protocol == "" {
st.Protocol = map[bool]string{true: "tcp", false: "http"}[st.TLS == "passthrough"]
}
listen, _ := lb["listen"].(map[string]any)
if p, ok := listen["port"].(float64); ok {
st.Port = int(p)
}
zones := stringList(listen, "zones")
if len(zones) == 0 {
zones = []string{"wan"}
}
st.Zones = strings.Join(zones, ", ")
out = append(out, st)
}
sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name })
if len(out) == 0 {
return nil, ""
}
raw, err := haproxyCommand(a.sys.haproxySocket(), "show stat")
if err != nil {
return out, "HAProxy is not running: the services are saved but not applied yet, or it failed to start."
}
servers, err := parseHAProxyStat(raw)
if err != nil {
return out, err.Error()
}
state, _ := haproxyCommand(a.sys.haproxySocket(), "show servers state")
addrs := parseServerAddresses(state)
for i := range out {
if sv, ok := servers[out[i].Name]; ok {
out[i].Running = true
for _, x := range sv {
if x.Name == "BACKEND" {
out[i].Up = x.Up
} else if x.Name != "FRONTEND" {
if x.Address == "" {
x.Address = addrs["be_"+out[i].Name+"/"+x.Name]
}
out[i].Servers = append(out[i].Servers, x)
}
}
}
}
return out, ""
}
func (a *app) loadBalancersPage(w http.ResponseWriter, r *http.Request, sess session) {
p := page{Title: "Load balancers", CSRF: sess.csrf, LoggedIn: true, Flash: r.URL.Query().Get("msg"), Live: 10}
s, err := loadSettings(a.sys.settingsPath())
if err != nil {
p.Error = err.Error()
a.render(w, "loadbalancers", p)
return
}
services, note := a.loadBalancers(s)
p.Data = struct {
Services []LBStatus
Note string
}{services, note}
a.render(w, "loadbalancers", p)
}
+140
View File
@@ -0,0 +1,140 @@
package main
import (
"net"
"os"
"path/filepath"
"strings"
"testing"
)
// What `show stat` says for two services (columns cut down to the ones that matter).
const sampleStat = `# pxname,svname,qcur,qmax,scur,smax,slim,stot,bin,bout,dreq,dresp,ereq,econ,eresp,wretr,wredis,status,weight,act,bck,chkfail,chkdown,lastchg,downtime,qlimit,pid,iid,sid,throttle,lbtot,tracked,type,rate,rate_lim,rate_max,check_status,check_code,check_duration,addr
fe_8443,FRONTEND,,,0,5,,12,0,0,0,0,0,,,,,OPEN,,,,,,,,,1,2,0,,,,0,0,0,1,,,,,
be_api,hv1,0,0,2,3,,7,0,0,,0,,0,0,0,0,UP,1,1,0,0,0,300,0,,1,3,1,,7,,2,0,,1,L7OK,200,3,
be_api,hv2,0,0,0,0,,5,0,0,,0,,0,0,0,0,DOWN,1,1,0,3,1,40,40,,1,3,2,,5,,2,0,,1,L7STS,503,2,
be_api,BACKEND,0,0,2,3,,12,0,0,0,0,,0,0,0,0,UP,1,1,0,,0,300,0,,1,3,0,,12,,1,0,,1,,,,
be_raw,hv1,0,0,0,0,,0,0,0,,0,,0,0,0,0,DOWN,1,1,0,5,1,10,10,,1,4,1,,0,,2,0,,0,L4CON,,0,
be_raw,BACKEND,0,0,0,0,,0,0,0,0,0,,0,0,0,0,DOWN,1,1,0,,1,10,10,,1,4,0,,0,,1,0,,0,,,,
`
func TestParseHAProxyStat(t *testing.T) {
got, err := parseHAProxyStat(sampleStat)
if err != nil {
t.Fatal(err)
}
api := got["api"]
if len(api) != 3 || api[0].Name != "hv1" || !api[0].Up || api[0].Address != "" ||
api[0].Check != "L7OK/200" || api[0].Current != 2 || api[0].Total != 7 || api[0].Since != 300 {
t.Fatalf("api: %+v", api)
}
if api[1].Up || api[1].Status != "DOWN" || api[1].Check != "L7STS/503" {
t.Fatalf("a down backend: %+v", api[1])
}
if _, ok := got["8443"]; ok || len(got["raw"]) != 2 {
t.Fatalf("frontends or raw: %+v", got)
}
if _, err := parseHAProxyStat("# a,b\n1,2\n"); err == nil {
t.Error("statistics without the columns were accepted")
}
if _, err := parseHAProxyStat(""); err == nil {
t.Error("nothing was accepted")
}
}
// The addresses are not in the CSV; `show servers state` has them.
const sampleState = `1
# be_id be_name srv_id srv_name srv_addr srv_op_state srv_port
3 be_api 1 hv1 192.168.10.21 2 8443
3 be_api 2 hv2 192.168.10.22 0 8443
4 be_raw 1 hv1 192.168.10.21 0 8443
`
func TestParseServerAddresses(t *testing.T) {
got := parseServerAddresses(sampleState)
if got["be_api/hv2"] != "192.168.10.22:8443" || got["be_raw/hv1"] != "192.168.10.21:8443" || len(got) != 3 {
t.Fatalf("%v", got)
}
if len(parseServerAddresses("")) != 0 || len(parseServerAddresses("1\n3 be_api 1 hv1 x\n")) != 0 {
t.Error("addresses out of nothing")
}
}
// serveStat answers `show stat` (and `show servers state`) on a socket, like HAProxy.
func serveStat(t *testing.T, path, answer string) {
t.Helper()
l, err := net.Listen("unix", path)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { l.Close() })
go func() {
for {
c, err := l.Accept()
if err != nil {
return
}
buf := make([]byte, 64)
n, _ := c.Read(buf)
if strings.HasPrefix(string(buf[:n]), "show servers state") {
c.Write([]byte(sampleState))
} else {
c.Write([]byte(answer))
}
c.Close()
}
}()
}
func TestLoadBalancersPage(t *testing.T) {
a, sys := newTestApp(t)
// (A short path: a unix socket's name is limited.)
sys.HAProxySocket = filepath.Join(os.TempDir(), "lb-test-"+filepath.Base(t.TempDir())+".sock")
a.sys = sys
h := a.routes()
cookie := login(t, h)
menu := do(h, "GET", "/", nil, cookie).Body.String()
if !strings.Contains(menu, `href="/loadbalancers"`) {
t.Fatalf("no menu entry:\n%s", menu)
}
// Nothing configured: the page says how.
body := do(h, "GET", "/loadbalancers", nil, cookie).Body.String()
if !strings.Contains(body, "No load balancer is set up") || !strings.Contains(body, "router.loadBalancers") {
t.Fatalf("empty page:\n%s", body)
}
settings := `{"system":{"hostName":"router","stateVersion":"26.11"},"router":{"loadBalancers":{
"api":{"listen":{"port":8443,"zones":["wan","lan"]},"hosts":["api.example.org"],"backends":["hv1","hv2"]},
"raw":{"listen":{"port":9443},"tls":"passthrough","backends":["hv1"]}}}}`
os.WriteFile(sys.settingsPath(), []byte(settings), 0o600)
// Saved, HAProxy not running: say so, show the configuration.
body = do(h, "GET", "/loadbalancers", nil, cookie).Body.String()
for _, want := range []string{"HAProxy is not running", "<h2>api", "port 8443 in wan, lan", "api.example.org", "<h2>raw", "passed through", "roundrobin"} {
if !strings.Contains(body, want) {
t.Errorf("without HAProxy the page lacks %q:\n%s", want, body)
}
}
if strings.Contains(body, `class="badge`) {
t.Errorf("a status badge without knowing:\n%s", body)
}
// Running: one service up (one backend down), one down.
serveStat(t, sys.HAProxySocket, sampleStat)
body = do(h, "GET", "/loadbalancers", nil, cookie).Body.String()
for _, want := range []string{"192.168.10.21:8443", "L7OK/200", "L7STS/503", "badge ok", "badge bad", "7 in all", "300 s", `data-live="10"`} {
if !strings.Contains(body, want) {
t.Errorf("the page lacks %q:\n%s", want, body)
}
}
if strings.Contains(body, "HAProxy is not running") {
t.Errorf("claims HAProxy is down:\n%s", body)
}
// A service HAProxy does not know yet is "not applied".
os.WriteFile(sys.settingsPath(), []byte(strings.Replace(settings, `"raw"`, `"new"`, 1)), 0o600)
if body = do(h, "GET", "/loadbalancers", nil, cookie).Body.String(); !strings.Contains(body, `badge">not applied`) {
t.Errorf("a new service is not marked:\n%s", body)
}
}
+2 -1
View File
@@ -270,7 +270,7 @@ func newApp(sys System, metrics *Collector, dev bool) *app {
func (a *app) parseTemplates() (map[string]*template.Template, error) {
files := map[string][]string{"overview": {"templates/dashboard.html"}}
pages := map[string]*template.Template{}
for _, page := range []string{"login", "overview", "network", "dhcp", "dns", "wireguard", "firewall", "ddns", "dnsproviders", "certificate", "exporter", "advanced", "update", "tokens", "changes"} {
for _, page := range []string{"login", "overview", "network", "dhcp", "dns", "wireguard", "firewall", "loadbalancers", "ddns", "dnsproviders", "certificate", "exporter", "advanced", "update", "tokens", "changes"} {
t, err := template.New("layout.html").Funcs(a.funcs).
ParseFS(assets, append([]string{"templates/layout.html", "templates/" + page + ".html"}, files[page]...)...)
if err != nil {
@@ -328,6 +328,7 @@ func (a *app) routes() http.Handler {
mux.HandleFunc("POST /dnsproviders", a.auth(a.providersSave))
mux.HandleFunc("GET /certificate", a.auth(a.certificatePage))
mux.HandleFunc("POST /certificate", a.auth(a.certificateSave))
mux.HandleFunc("GET /loadbalancers", a.auth(a.loadBalancersPage))
mux.HandleFunc("GET /prometheus", a.auth(a.exporterPage))
mux.HandleFunc("POST /prometheus", a.auth(a.exporterSave))
mux.HandleFunc("GET /firewall", a.auth(a.firewallPage))
+1
View File
@@ -161,6 +161,7 @@ pre code { background: none; padding: 0; }
.muted { color: var(--muted); }
.bad { color: var(--bad); }
.ok { color: var(--good); }
.badge { font-size: .75em; font-weight: 600; padding: .1em .55em; border: 1px solid currentColor; border-radius: 1em; vertical-align: middle; }
body.bare { padding-left: 0; }
.bare header { position: static; width: auto; flex-direction: row; background: none; padding: 1rem 1.25rem; }
+3 -1
View File
@@ -27,7 +27,9 @@ type System struct {
VersionFile string
// LeasesDNSDir is where leases-dns leaves its status; /run/router-leases-dns if empty.
LeasesDNSDir string
ACMEDir string // where the ACME client keeps the web UI's certificate (fullchain.pem, key.pem), if any
// HAProxySocket is where the load balancers' statistics are; /run/haproxy/haproxy.sock if empty.
HAProxySocket string
ACMEDir string // where the ACME client keeps the web UI's certificate (fullchain.pem, key.pem), if any
}
func (s System) leasesDNSDir() string {
+1
View File
@@ -21,6 +21,7 @@
<a href="/dns"{{if eq .Title "DNS"}} aria-current="page"{{end}}>DNS</a>
<a href="/wireguard"{{if eq .Title "WireGuard"}} aria-current="page"{{end}}>WireGuard</a>
<a href="/firewall"{{if eq .Title "Firewall"}} aria-current="page"{{end}}>Firewall</a>
<a href="/loadbalancers"{{if eq .Title "Load balancers"}} aria-current="page"{{end}}>Load balancers</a>
</div>
<div class="group"><span>Services</span>
<a href="/ddns"{{if eq .Title "Dynamic DNS"}} aria-current="page"{{end}}>Dynamic DNS</a>
@@ -0,0 +1,48 @@
{{define "content"}}
{{with .Data}}
{{if .Note}}<p class="flash">{{.Note}}</p>{{end}}
{{range .Services}}
<section>
<h2>{{.Name}}
{{if not $.Data.Note}}{{if not .Running}}<span class="badge">not applied</span>{{else if .Up}}<span class="badge ok">up</span>{{else}}<span class="badge bad">down</span>{{end}}{{end}}
</h2>
<dl>
<dt>Listens on</dt><dd>port {{.Port}} in {{.Zones}}</dd>
<dt>TLS</dt><dd>{{if eq .TLS "terminate"}}decrypted on the router{{else if eq .TLS "passthrough"}}passed through{{else}}none{{end}}, {{.Protocol}}</dd>
{{if .Hosts}}<dt>Names</dt><dd>{{.Hosts}}</dd>{{end}}
<dt>Balancing</dt><dd>{{.Balance}}</dd>
</dl>
{{if .Servers}}
<table>
<thead><tr><th>Backend</th><th>Address</th><th>State</th><th>Last check</th><th>Connections</th><th>In this state</th></tr></thead>
<tbody>
{{range .Servers}}<tr>
<td>{{.Name}}</td><td>{{.Address}}</td>
<td>{{if .Up}}<span class="badge ok">{{.Status}}</span>{{else}}<span class="badge bad">{{.Status}}</span>{{end}}</td>
<td>{{.Check}}</td><td>{{.Current}} now, {{.Total}} in all</td><td>{{.Since}} s</td>
</tr>{{end}}
</tbody>
</table>
{{else if .Running}}<p class="muted">HAProxy has no backend for it.</p>{{end}}
</section>
{{else}}
<section>
<p>No load balancer is set up. A load balancer spreads the connections to a service over several hosts and leaves out a host
that fails its checks. Add one under <code>router.loadBalancers</code> in <a href="/advanced">Advanced</a>, for example:</p>
<pre class="log">"loadBalancers": {
"api": {
"listen": { "port": 8443, "zones": ["wan", "lan"] },
"tls": "terminate",
"hosts": ["api.example.org"],
"backends": ["hv1", "hv2"],
"backendTls": { "enable": true },
"check": { "path": "/healthz" }
}
}</pre>
<p>The backends are names of DHCP reservations or addresses. With <code>"tls": "passthrough"</code> the backends keep their
certificate and the router only forwards; the client's address then reaches them with <code>"proxyProtocol": true</code>
(if they read it). Saved changes take effect when you apply them.</p>
</section>
{{end}}
{{end}}
{{end}}