diff --git a/SPECS.md b/SPECS.md index 5195fda..c1e0178 100644 --- a/SPECS.md +++ b/SPECS.md @@ -236,6 +236,14 @@ Upgrading nixpkgs (the kernel and every package) on the router, without a new re - **Module options** (for tests): `routerSettings.upgrade.channelsUrl`, `routerSettings.upgrade.nixpkgsRef` (`%rev%`). - **Test** (`apply`): the channel is a small HTTP server on the client that redirects like channels.nixos.org, and the "newer" nixpkgs is the installed one under a `path:` reference with the same `lastModified` and `rev`: a really different nixpkgs cannot be built offline (any version change rebuilds the NixOS tools). Covers check, preview (including the package-list rules), download, an unconfirmed upgrade rolled back with its lock and pin, a confirmed one, and a failing build. +## Metrics for Prometheus (2026-11-19) + +Two sources, so nothing the machine already exports is written twice. + +- **`/metrics` of the web UI** (`promtext.go`): the router's own state in the text format 0.0.4. A token of the API access page is needed (`Authorization: Bearer`, any scope, so Prometheus' `authorization.credentials` works), and the endpoint is reachable wherever the web UI is (the LANs and tunnels with `allowManagement`); the certificate is the web UI's, so a Prometheus job needs `insecure_skip_verify` or the CA. Metrics: `router_info`, `router_uplink_up`/`_reachable`/`_since_timestamp_seconds`, `router_ping_up`/`_rtt_seconds` (per target), `router_reboot_required{reason}`, `router_settings_unapplied`, `router_apply_running`, `router_confirmation_due_seconds`, `router_dhcp_leases{lan}`, `router_wireguard_peer_last_handshake_timestamp_seconds` and `_receive_bytes_total`/`_transmit_bytes_total` (per tunnel and peer, with the peer's name), `router_certificate_expiry_timestamp_seconds`. A value that is not known (NaN) is left out. +- **node_exporter** (`router.metrics.nodeExporter`, `modules/router/metrics.nix`): CPU, memory, disks, interfaces and systemd units. Off by default. It listens on all addresses, but the firewall opens its port (9100) only to the zones in `zones` (one allow rule each, to `local`); `wan` is refused by an assertion. With no zone it can only be read on the router itself. +- Tested in `webui` (token needed, the samples, node_exporter from the LAN and on the router, the rule names the LAN's device only) and `assertions`. The **Prometheus page** (Services → Prometheus, `exporter.go`) edits the exporter's settings (enable, port, zones to open it to; `wan` and the router's own ports are refused) and shows the scrape config for `/metrics` and for node_exporter. Not done: per-LAN traffic of the web UI's own history (node_exporter has the interface counters), and alert rules or a Grafana dashboard. + ## Not done yet (2026-11-01, after 0.12.0) Remote access diff --git a/modules/router/default.nix b/modules/router/default.nix index 47fde4d..1477c99 100644 --- a/modules/router/default.nix +++ b/modules/router/default.nix @@ -11,6 +11,7 @@ ./ddns.nix ./acme.nix ./rollback.nix + ./metrics.nix ./power.nix ]; } diff --git a/modules/router/metrics.nix b/modules/router/metrics.nix new file mode 100644 index 0000000..9d26b51 --- /dev/null +++ b/modules/router/metrics.nix @@ -0,0 +1,33 @@ +# Metrics for Prometheus. The router's own state is /metrics of the web UI +# (pkgs/router-webui/promtext.go); the machine's is node_exporter, which this +# module starts when `router.metrics.nodeExporter.enable` is set and opens to +# the zones named there, and to no one else. +{ config, lib, ... }: +let + cfg = config.router; + m = cfg.metrics.nodeExporter; +in +{ + config = lib.mkIf (cfg.enable && m.enable) { + services.prometheus.exporters.node = { + enable = true; + inherit (m) port; + enabledCollectors = [ "systemd" ]; + }; + + # An allow rule per zone; the unknown ones are refused by the firewall's own check. + router.firewall.rules = map (zone: { + from = zone; + to = "local"; + protocol = "tcp"; + ports = [ m.port ]; + }) m.zones; + + assertions = [ + { + assertion = !(lib.elem "wan" m.zones); + message = "router.metrics.nodeExporter.zones: `wan` is the internet; node_exporter must not be open to it. Scrape it from a LAN or through a WireGuard tunnel."; + } + ]; + }; +} diff --git a/modules/router/options.nix b/modules/router/options.nix index f37d5af..4022616 100644 --- a/modules/router/options.nix +++ b/modules/router/options.nix @@ -452,6 +452,31 @@ in ''; }; + metrics.nodeExporter = { + enable = mkEnableOption "Prometheus node_exporter: the machine's CPU, memory, disks, network interfaces and systemd units"; + port = mkOption { + type = types.port; + default = 9100; + description = "The port node_exporter listens on."; + }; + zones = mkOption { + type = types.listOf types.str; + default = [ ]; + example = [ "main" ]; + description = '' + Zones (a LAN's or tunnel's `zone`, which is the LAN's name unless + set) that may reach node_exporter, with a firewall rule for each. The + port is closed to every other zone and to the internet, so nothing + can scrape it until a zone is named; the router itself can always + reach it on localhost. `wan` is not allowed. + + The router's own state (uplink, pings, WireGuard peers, pending + changes, certificate) is at `/metrics` of the web UI instead, which + needs an API token and is reachable wherever the web UI is. + ''; + }; + }; + firewall.zones = mkOption { type = types.listOf types.str; default = [ ]; diff --git a/pkgs/router-webui/exporter.go b/pkgs/router-webui/exporter.go new file mode 100644 index 0000000..f48bfaf --- /dev/null +++ b/pkgs/router-webui/exporter.go @@ -0,0 +1,167 @@ +package main + +import ( + "errors" + "net" + "net/http" + "slices" + "strconv" + "strings" +) + +// The Prometheus page: node_exporter (router.metrics.nodeExporter) and how to +// scrape the router's own /metrics. The settings are saved like those of any +// page and applied with the rest. + +// ExporterForm is router.metrics.nodeExporter. +type ExporterForm struct { + Enabled bool + Port string + Zones []string +} + +const defaultExporterPort = "9100" + +func (s Settings) exporter() ExporterForm { + router, _ := s["router"].(map[string]any) + m, _ := router["metrics"].(map[string]any) + n, _ := m["nodeExporter"].(map[string]any) + f := ExporterForm{Enabled: boolean(n, false, "enable"), Port: str(n, "port"), Zones: stringList(n, "zones")} + if f.Port == "" { + f.Port = defaultExporterPort + } + return f +} + +// Ports the router itself serves on: node_exporter cannot take them. +var exporterReserved = map[int]string{22: "SSH", 53: "DNS", 67: "DHCP", 68: "DHCP", 80: "the web UI", 443: "the web UI"} + +func (s Settings) applyExporter(f ExporterForm) error { + errs := FormErrors{} + f.Port = strings.TrimSpace(f.Port) + if f.Port == "" { + f.Port = defaultExporterPort + } + port, err := strconv.Atoi(f.Port) + switch { + case err != nil || port < 1 || port > 65535: + errs["port"] = "a port number between 1 and 65535" + case exporterReserved[port] != "": + errs["port"] = "port " + f.Port + " is used by " + exporterReserved[port] + } + known := s.zones() + var zones []any + for _, z := range f.Zones { + if z == "wan" { + errs["zones"] = "wan is the internet: node_exporter must not be open to it. Scrape it from a LAN or through a WireGuard tunnel." + break + } + if !slices.Contains(known, z) { + errs["zones"] = "unknown zone " + z + break + } + zones = append(zones, z) + } + if len(errs) > 0 { + return errs + } + router := obj(s, "router") + if !f.Enabled && len(zones) == 0 && f.Port == defaultExporterPort { + // Nothing to say: leave the settings as they would be without this page. + if m, ok := router["metrics"].(map[string]any); ok { + delete(m, "nodeExporter") + if len(m) == 0 { + delete(router, "metrics") + } + } + return nil + } + n := obj(obj(router, "metrics"), "nodeExporter") + n["enable"] = f.Enabled + if f.Port == defaultExporterPort { + delete(n, "port") + } else { + n["port"] = float64(port) + } + if len(zones) > 0 { + n["zones"] = zones + } else { + delete(n, "zones") + } + return nil +} + +type zoneChoice struct { + Name string + Checked bool +} + +type exporterData struct { + Form ExporterForm + Errors FormErrors + Zones []zoneChoice // the zones that can be chosen + Host string // how the browser reached the router, for the example + Target string // host:port for node_exporter +} + +func (a *app) exporterData(r *http.Request, s Settings, f ExporterForm, errs FormErrors) exporterData { + d := exporterData{Form: f, Errors: errs, Host: r.Host} + host := r.Host + if h, _, err := net.SplitHostPort(r.Host); err == nil { + host = h + } + d.Target = net.JoinHostPort(host, f.Port) + names := s.zones() + for _, z := range f.Zones { // a zone that is chosen stays listed even if it is gone + if !slices.Contains(names, z) { + names = append(names, z) + } + } + for _, z := range names { + d.Zones = append(d.Zones, zoneChoice{Name: z, Checked: slices.Contains(f.Zones, z)}) + } + return d +} + +func (a *app) exporterPage(w http.ResponseWriter, r *http.Request, sess session) { + p := page{Title: "Prometheus", CSRF: sess.csrf, LoggedIn: true, Flash: r.URL.Query().Get("msg")} + s, err := loadSettings(a.sys.settingsPath()) + if err != nil { + p.Error = err.Error() + a.render(w, "exporter", p) + return + } + p.Data = a.exporterData(r, s, s.exporter(), nil) + a.render(w, "exporter", p) +} + +func (a *app) exporterSave(w http.ResponseWriter, r *http.Request, sess session) { + p := page{Title: "Prometheus", CSRF: sess.csrf, LoggedIn: true} + s, err := loadSettings(a.sys.settingsPath()) + if err != nil { + p.Error = err.Error() + a.render(w, "exporter", p) + return + } + if err := r.ParseForm(); err != nil { + p.Error = err.Error() + a.render(w, "exporter", p) + return + } + f := ExporterForm{Enabled: r.PostFormValue("enabled") == "on", Port: r.PostFormValue("port"), Zones: r.PostForm["zone"]} + if err := s.applyExporter(f); err != nil { + var fe FormErrors + errors.As(err, &fe) + p.Error = "Please correct the marked fields." + p.Data = a.exporterData(r, s, f, fe) + w.WriteHeader(http.StatusUnprocessableEntity) + a.render(w, "exporter", p) + return + } + if err := s.save(a.sys.settingsPath()); err != nil { + p.Error = "Saving: " + err.Error() + a.render(w, "exporter", p) + return + } + back(w, r, "Saved. Apply to start or stop node_exporter and to open the port.") +} diff --git a/pkgs/router-webui/exporter_test.go b/pkgs/router-webui/exporter_test.go new file mode 100644 index 0000000..397cf10 --- /dev/null +++ b/pkgs/router-webui/exporter_test.go @@ -0,0 +1,86 @@ +package main + +import ( + "net/http" + "net/url" + "regexp" + "strings" + "testing" +) + +func TestApplyExporter(t *testing.T) { + s := mustParse(t) + if f := s.exporter(); f.Enabled || f.Port != "9100" || len(f.Zones) != 0 { + t.Fatalf("defaults: %+v", f) + } + for _, c := range []struct { + name string + form ExporterForm + bad string // the field that is refused + }{ + {"port 0", ExporterForm{Port: "0"}, "port"}, + {"not a number", ExporterForm{Port: "nine"}, "port"}, + {"the web UI's port", ExporterForm{Enabled: true, Port: "443"}, "port"}, + {"the internet", ExporterForm{Enabled: true, Port: "9100", Zones: []string{"wan"}}, "zones"}, + {"a zone that does not exist", ExporterForm{Enabled: true, Port: "9100", Zones: []string{"nowhere"}}, "zones"}, + } { + err := mustParse(t).applyExporter(c.form) + fe, ok := err.(FormErrors) + if !ok || fe[c.bad] == "" { + t.Errorf("%s: %v", c.name, err) + } + } + + if err := s.applyExporter(ExporterForm{Enabled: true, Port: "9200", Zones: []string{"main", "vpn"}}); err != nil { + t.Fatal(err) + } + f := s.exporter() + if !f.Enabled || f.Port != "9200" || strings.Join(f.Zones, ",") != "main,vpn" { + t.Fatalf("saved: %+v", f) + } + // The default port is not written, and a form that says nothing removes the section. + if err := s.applyExporter(ExporterForm{Enabled: true, Port: "9100", Zones: []string{"main"}}); err != nil { + t.Fatal(err) + } + if n := obj(obj(obj(s, "router"), "metrics"), "nodeExporter"); n["port"] != nil || n["enable"] != true { + t.Fatalf("%v", n) + } + if err := s.applyExporter(ExporterForm{Port: ""}); err != nil { + t.Fatal(err) + } + if _, ok := obj(s, "router")["metrics"]; ok { + t.Fatalf("an empty section is left behind: %v", obj(s, "router")) + } +} + +func TestExporterPage(t *testing.T) { + a, sys := newTestApp(t) + h := a.routes() + cookie := do(h, "POST", "/login", url.Values{"password": {"hunter2hunter2"}}, nil).Result().Cookies()[0] + body := do(h, "GET", "/prometheus", nil, cookie).Body.String() + for _, want := range []string{`value="main"`, `value="vpn"`, `/metrics`, "node_exporter", `href="/prometheus" aria-current="page"`} { + if !strings.Contains(body, want) { + t.Errorf("the page lacks %q:\n%s", want, body) + } + } + if strings.Contains(body, `value="wan"`) { + t.Error("wan is offered") + } + token := regexp.MustCompile(`name="csrf" value="([^"]+)"`).FindStringSubmatch(body)[1] + form := url.Values{"csrf": {token}, "enabled": {"on"}, "port": {"9100"}, "zone": {"nowhere"}} + if rec := do(h, "POST", "/prometheus", form, cookie); rec.Code != http.StatusUnprocessableEntity || !strings.Contains(rec.Body.String(), "unknown zone nowhere") { + t.Fatalf("unknown zone: %d\n%s", rec.Code, rec.Body) + } + form["zone"] = []string{"main", "vpn"} + if rec := do(h, "POST", "/prometheus", form, cookie); rec.Code != http.StatusSeeOther { + t.Fatalf("save: %d\n%s", rec.Code, rec.Body) + } + s, _ := loadSettings(sys.settingsPath()) + if f := s.exporter(); !f.Enabled || strings.Join(f.Zones, ",") != "main,vpn" { + t.Fatalf("not saved: %+v", f) + } + body = do(h, "GET", "/prometheus", nil, cookie).Body.String() + if !strings.Contains(body, `value="main" checked`) || !strings.Contains(body, "router-node") { + t.Fatalf("the saved choice is not shown:\n%s", body) + } +} diff --git a/pkgs/router-webui/main.go b/pkgs/router-webui/main.go index 7fa9dca..aa8ce06 100644 --- a/pkgs/router-webui/main.go +++ b/pkgs/router-webui/main.go @@ -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", "advanced", "update", "upgrade", "tokens", "changes"} { + for _, page := range []string{"login", "overview", "network", "dhcp", "dns", "wireguard", "firewall", "ddns", "dnsproviders", "certificate", "exporter", "advanced", "update", "upgrade", "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,8 @@ 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 /prometheus", a.auth(a.exporterPage)) + mux.HandleFunc("POST /prometheus", a.auth(a.exporterSave)) mux.HandleFunc("GET /firewall", a.auth(a.firewallPage)) mux.HandleFunc("POST /firewall", a.auth(a.firewall)) mux.HandleFunc("GET /dhcp", a.auth(a.dhcpPage)) @@ -344,6 +346,7 @@ func (a *app) routes() http.Handler { mux.HandleFunc("POST /upgrade/channel", a.auth(a.upgradeChannel)) mux.HandleFunc("POST /upgrade/{step}", a.auth(a.upgradeStep)) mux.HandleFunc("/mcp", a.mcp) + mux.HandleFunc("GET /metrics", a.promMetrics) a.registerAPI(mux) mux.HandleFunc("GET /tokens", a.auth(a.tokensPage)) mux.HandleFunc("GET /apireference", a.auth(a.apiReference)) diff --git a/pkgs/router-webui/promtext.go b/pkgs/router-webui/promtext.go new file mode 100644 index 0000000..4516f35 --- /dev/null +++ b/pkgs/router-webui/promtext.go @@ -0,0 +1,160 @@ +package main + +import ( + "io" + "math" + "net/http" + "slices" + "strconv" + "strings" + "time" +) + +// /metrics: the state of the router itself in the Prometheus text format (the +// uplink and its pings, pending changes, WireGuard peers, DHCP leases, the +// certificate). The machine's CPU, memory, disks and interfaces are the job of +// node_exporter (router.metrics.nodeExporter), which Prometheus scrapes beside +// this. A token of the API access page (any scope) is needed: the data says who +// is connected and how. + +func (a *app) promMetrics(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Cache-Control", "no-store") + tok, ok := a.bearer(w, r) + if !ok { + return + } + if !tok.allows(scopeRead) { + http.Error(w, "this token may not read (scope)", http.StatusForbidden) + return + } + w.Header().Set("Content-Type", "text/plain; version=0.0.4; charset=utf-8") + _, _ = io.WriteString(w, a.promText(time.Now())) +} + +// promWriter writes samples, each family's HELP and TYPE once before its first. +type promWriter struct { + b strings.Builder + declared map[string]bool +} + +// sample adds name{labels} value; labels are name, value pairs. NaN and +// infinite values are left out: there is nothing to say. +func (p *promWriter) sample(name, typ, help string, value float64, labels ...string) { + if math.IsNaN(value) || math.IsInf(value, 0) { + return + } + if !p.declared[name] { + if p.declared == nil { + p.declared = map[string]bool{} + } + p.declared[name] = true + p.b.WriteString("# HELP " + name + " " + help + "\n# TYPE " + name + " " + typ + "\n") + } + p.b.WriteString(name) + for i := 0; i+1 < len(labels); i += 2 { + if i == 0 { + p.b.WriteByte('{') + } else { + p.b.WriteByte(',') + } + p.b.WriteString(labels[i] + `="` + promEscape(labels[i+1]) + `"`) + } + if len(labels) > 1 { + p.b.WriteByte('}') + } + p.b.WriteString(" " + strconv.FormatFloat(value, 'g', -1, 64) + "\n") +} + +func promEscape(s string) string { + return strings.NewReplacer(`\`, `\\`, `"`, `\"`, "\n", `\n`).Replace(s) +} + +func promBool(b bool) float64 { + if b { + return 1 + } + return 0 +} + +func unix(t time.Time) float64 { return float64(t.Unix()) } + +func (a *app) promText(now time.Time) string { + var p promWriter + snap := a.metrics.Snapshot() + st := a.sys.Status() + s, _ := loadSettings(a.sys.settingsPath()) + f := s.form() + + p.sample("router_info", "gauge", "The installed nixos-router release and the running kernel.", 1, + "version", a.sys.installedRelease().Version, "kernel", snap.System.Kernel) + + if !snap.Time.IsZero() { + u := snap.Uplink + p.sample("router_uplink_up", "gauge", "1 if the uplink has an IPv4 address and the default route.", promBool(u.Connected), + "device", u.Device, "type", u.Type) + if u.Checked { + p.sample("router_uplink_reachable", "gauge", "1 if a public ping target answered.", promBool(u.Reachable)) + } + if !u.Since.IsZero() { + p.sample("router_uplink_since_timestamp_seconds", "gauge", "When the uplink last changed between up and down.", unix(u.Since)) + } + for _, ping := range snap.Pings { + p.sample("router_ping_up", "gauge", "1 if the ping target answered the last probe.", promBool(ping.OK), + "target", ping.Target, "address", ping.Address) + if ping.OK { + p.sample("router_ping_rtt_seconds", "gauge", "Round-trip time of the last probe.", ping.RTT.Seconds(), + "target", ping.Target, "address", ping.Address) + } + } + p.sample("router_reboot_required", "gauge", "1 if a reboot is due: for a new kernel, or a configuration that starts at the next boot.", promBool(snap.System.KernelNext != ""), "reason", "kernel") + p.sample("router_reboot_required", "gauge", "1 if a reboot is due: for a new kernel, or a configuration that starts at the next boot.", promBool(snap.System.BootPending), "reason", "configuration") + } + + p.sample("router_settings_unapplied", "gauge", "1 if the saved settings differ from the running system.", promBool(st.Unapplied)) + p.sample("router_apply_running", "gauge", "1 while a configuration is being built and applied.", promBool(st.Applying)) + p.sample("router_confirmation_due_seconds", "gauge", "Seconds left to confirm an applied change before the router goes back; 0 if none waits.", st.RollbackIn.Seconds()) + + leases := map[string]int{} + for _, l := range readLeases(a.metrics.leasesPath, f.LANs, now) { + leases[l.LAN]++ + } + for _, l := range f.LANs { + leases[l.Name] += 0 + } + lans := make([]string, 0, len(leases)) + for lan := range leases { + lans = append(lans, lan) + } + slices.Sort(lans) + for _, lan := range lans { + p.sample("router_dhcp_leases", "gauge", "Active DHCPv4 leases per LAN.", float64(leases[lan]), "lan", lan) + } + + if status := wgStatus(); status != nil { + for _, t := range s.tunnels(a.sys) { + names := map[string]string{} + for _, peer := range t.Peers { + names[peer.PublicKey] = peer.Name + } + keys := make([]string, 0) + for key := range status[t.Device()] { + keys = append(keys, key) + } + slices.Sort(keys) + for _, key := range keys { + peer := status[t.Device()][key] + labels := []string{"tunnel", t.Name, "interface", t.Device(), "peer", key, "name", names[key]} + if !peer.Handshake.IsZero() { + p.sample("router_wireguard_peer_last_handshake_timestamp_seconds", "gauge", "When the peer's last handshake completed (absent: never).", unix(peer.Handshake), labels...) + } + p.sample("router_wireguard_peer_receive_bytes_total", "counter", "Bytes received from the peer.", float64(peer.RX), labels...) + p.sample("router_wireguard_peer_transmit_bytes_total", "counter", "Bytes sent to the peer.", float64(peer.TX), labels...) + } + } + } + + if c, ok, source := a.servedCert(); ok { + p.sample("router_certificate_expiry_timestamp_seconds", "gauge", "When the web UI's certificate expires.", unix(c.NotAfter), "source", source) + } + return p.b.String() +} diff --git a/pkgs/router-webui/promtext_test.go b/pkgs/router-webui/promtext_test.go new file mode 100644 index 0000000..eea55e7 --- /dev/null +++ b/pkgs/router-webui/promtext_test.go @@ -0,0 +1,95 @@ +package main + +import ( + "net/http" + "strings" + "testing" + "time" +) + +func TestPromWriter(t *testing.T) { + var p promWriter + p.sample("x_up", "gauge", "Is it up.", 1, "device", `a"b\c`+"\n") + p.sample("x_up", "gauge", "Is it up.", 0, "device", "other") + p.sample("x_plain", "counter", "No labels.", 2.5) + p.sample("x_nan", "gauge", "Left out.", nanValue()) + want := "# HELP x_up Is it up.\n# TYPE x_up gauge\n" + + `x_up{device="a\"b\\c\n"} 1` + "\n" + + `x_up{device="other"} 0` + "\n" + + "# HELP x_plain No labels.\n# TYPE x_plain counter\nx_plain 2.5\n" + if got := p.b.String(); got != want { + t.Fatalf("got:\n%s\nwant:\n%s", got, want) + } +} + +func nanValue() float64 { var z float64; return z / z } + +func TestMetricsEndpoint(t *testing.T) { + a, _ := newTestApp(t) + h := a.routes() + if rec := rest(h, "", "GET", "/metrics", "", nil); rec.Code != http.StatusUnauthorized { + t.Fatalf("no token: %d", rec.Code) + } + _, read, _ := a.tokens.Create("prometheus", "read") + rec := rest(h, read, "GET", "/metrics", "", nil) + if rec.Code != 200 { + t.Fatalf("%d %s", rec.Code, rec.Body) + } + if ct := rec.Header().Get("Content-Type"); !strings.HasPrefix(ct, "text/plain; version=0.0.4") { + t.Fatalf("content type %q", ct) + } + body := rec.Body.String() + for _, want := range []string{ + "# TYPE router_info gauge\nrouter_info{version=", + "router_settings_unapplied 0\n", + "router_apply_running 0\n", + "router_confirmation_due_seconds 0\n", + } { + if !strings.Contains(body, want) { + t.Errorf("no %q in:\n%s", want, body) + } + } + // Every sample line is `name{labels} number` or `name number`. + for _, line := range strings.Split(strings.TrimSpace(body), "\n") { + if strings.HasPrefix(line, "#") { + continue + } + if i := strings.LastIndexByte(line, ' '); i < 1 { + t.Errorf("not a sample: %q", line) + } + } + if rec := rest(h, read, "POST", "/metrics", "", nil); rec.Code != http.StatusMethodNotAllowed { + t.Fatalf("POST: %d", rec.Code) + } +} + +func TestMetricsFromASnapshot(t *testing.T) { + a, _ := newTestApp(t) + now := time.Unix(1_800_000_000, 0) + a.metrics.mu.Lock() + a.metrics.snap = Snapshot{ + Time: now, + Uplink: UplinkStatus{Device: "pppoe-wan", Type: "pppoe", Connected: true, Checked: true, Reachable: true, Since: now.Add(-time.Hour)}, + System: SystemStatus{Kernel: "7.3.4", KernelNext: "7.3.5"}, + Pings: []PingResult{{Target: "gateway", Address: "10.0.0.1", RTT: 8 * time.Millisecond, OK: true}, {Target: "1.1.1.1", Address: "1.1.1.1"}}, + } + a.metrics.mu.Unlock() + body := a.promText(now) + for _, want := range []string{ + `router_uplink_up{device="pppoe-wan",type="pppoe"} 1`, + "router_uplink_reachable 1\n", + "router_uplink_since_timestamp_seconds 1.7999964e+09\n", + `router_ping_up{target="gateway",address="10.0.0.1"} 1`, + `router_ping_rtt_seconds{target="gateway",address="10.0.0.1"} 0.008`, + `router_ping_up{target="1.1.1.1",address="1.1.1.1"} 0`, + `router_reboot_required{reason="kernel"} 1`, + `router_reboot_required{reason="configuration"} 0`, + } { + if !strings.Contains(body, want) { + t.Errorf("no %q in:\n%s", want, body) + } + } + if strings.Contains(body, `router_ping_rtt_seconds{target="1.1.1.1"`) { + t.Error("an RTT for a ping that failed") + } +} diff --git a/pkgs/router-webui/templates/exporter.html b/pkgs/router-webui/templates/exporter.html new file mode 100644 index 0000000..4ca6ec3 --- /dev/null +++ b/pkgs/router-webui/templates/exporter.html @@ -0,0 +1,48 @@ +{{define "content"}} +
+{{with .Data}} +{{$e := .Errors}}{{$f := .Form}} +
+

The router's state

+

The web UI serves the router's own state for Prometheus at https://{{.Host}}/metrics: the uplink and its + pings, pending changes, DHCP leases, WireGuard peers and the certificate's expiry. It needs a token (any access) + from the API access page; nothing is switched on here.

+
scrape_configs:
+  - job_name: router
+    scheme: https
+    tls_config:
+      insecure_skip_verify: true   # or ca_file, if the certificate is not self-signed
+    authorization:
+      credentials: rtr_…
+    static_configs:
+      - targets: ['{{.Host}}']
+
+ +
+ +
+ The machine (node_exporter) + + + {{with index $e "port"}}

{{.}}

{{end}} +

Open to these zones (the port is closed to every other zone and to the internet):

+ {{range .Zones}} + {{else}}

There is no zone yet: add a LAN or a tunnel first.

{{end}} + {{with index $e "zones"}}

{{.}}

{{end}} +

With no zone chosen, node_exporter runs but only the router itself can read it. It listens on every address; + the firewall is what keeps others out. Saving does not change the router: apply the settings afterwards.

+
+ +
+ +{{if $f.Enabled}} +
+

Scrape it

+
  - job_name: router-node
+    static_configs:
+      - targets: ['{{.Target}}']
+
+{{end}} +{{end}} +
+{{end}} diff --git a/pkgs/router-webui/templates/layout.html b/pkgs/router-webui/templates/layout.html index cee4b96..628ae09 100644 --- a/pkgs/router-webui/templates/layout.html +++ b/pkgs/router-webui/templates/layout.html @@ -26,6 +26,7 @@ Dynamic DNS DNS providers Certificate + Prometheus
System Update diff --git a/tests/assertions.nix b/tests/assertions.nix index 07b1e11..c0b0a1a 100644 --- a/tests/assertions.nix +++ b/tests/assertions.nix @@ -859,6 +859,26 @@ let }; expect = [ "natOnly does not apply to the router itself" ]; }; + exporterOnWan = { + router = { + lans.main = lan { }; + metrics.nodeExporter = { + enable = true; + zones = [ "wan" ]; + }; + }; + expect = [ "node_exporter must not be open to it" ]; + }; + exporterUnknownZone = { + router = { + lans.main = lan { }; + metrics.nodeExporter = { + enable = true; + zones = [ "nowhere" ]; + }; + }; + expect = [ "unknown source zone `nowhere`" ]; + }; localNoPorts = { router = { lans.main = lan { }; diff --git a/tests/webui.nix b/tests/webui.nix index cd61b9c..a7f6c56 100644 --- a/tests/webui.nix +++ b/tests/webui.nix @@ -13,6 +13,10 @@ let stateVersion = "26.11"; }; router = { + metrics.nodeExporter = { + enable = true; + zones = [ "main" ]; + }; wan.interface = "eth1"; lans.main = { interface = "eth2"; @@ -105,6 +109,26 @@ pkgs.testers.runNixOSTest { assert "