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) }