Add Prometheus metrics: /metrics, node_exporter and a page for it

The web UI serves the router's own state at /metrics (token needed);
router.metrics.nodeExporter runs node_exporter for the machine's and opens
its port only to the zones named. The Prometheus page edits those settings
and shows the scrape configuration.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-19 11:30:02 +01:00
co-authored by Claude Sonnet 5.5
parent 32bf0d5fde
commit 6e23d183fc
13 changed files with 672 additions and 1 deletions
+8
View File
@@ -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%`). - **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. - **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) ## Not done yet (2026-11-01, after 0.12.0)
Remote access Remote access
+1
View File
@@ -11,6 +11,7 @@
./ddns.nix ./ddns.nix
./acme.nix ./acme.nix
./rollback.nix ./rollback.nix
./metrics.nix
./power.nix ./power.nix
]; ];
} }
+33
View File
@@ -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.";
}
];
};
}
+25
View File
@@ -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 { firewall.zones = mkOption {
type = types.listOf types.str; type = types.listOf types.str;
default = [ ]; default = [ ];
+167
View File
@@ -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.")
}
+86
View File
@@ -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)
}
}
+4 -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) { func (a *app) parseTemplates() (map[string]*template.Template, error) {
files := map[string][]string{"overview": {"templates/dashboard.html"}} files := map[string][]string{"overview": {"templates/dashboard.html"}}
pages := map[string]*template.Template{} 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). t, err := template.New("layout.html").Funcs(a.funcs).
ParseFS(assets, append([]string{"templates/layout.html", "templates/" + page + ".html"}, files[page]...)...) ParseFS(assets, append([]string{"templates/layout.html", "templates/" + page + ".html"}, files[page]...)...)
if err != nil { if err != nil {
@@ -328,6 +328,8 @@ func (a *app) routes() http.Handler {
mux.HandleFunc("POST /dnsproviders", a.auth(a.providersSave)) mux.HandleFunc("POST /dnsproviders", a.auth(a.providersSave))
mux.HandleFunc("GET /certificate", a.auth(a.certificatePage)) mux.HandleFunc("GET /certificate", a.auth(a.certificatePage))
mux.HandleFunc("POST /certificate", a.auth(a.certificateSave)) 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("GET /firewall", a.auth(a.firewallPage))
mux.HandleFunc("POST /firewall", a.auth(a.firewall)) mux.HandleFunc("POST /firewall", a.auth(a.firewall))
mux.HandleFunc("GET /dhcp", a.auth(a.dhcpPage)) 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/channel", a.auth(a.upgradeChannel))
mux.HandleFunc("POST /upgrade/{step}", a.auth(a.upgradeStep)) mux.HandleFunc("POST /upgrade/{step}", a.auth(a.upgradeStep))
mux.HandleFunc("/mcp", a.mcp) mux.HandleFunc("/mcp", a.mcp)
mux.HandleFunc("GET /metrics", a.promMetrics)
a.registerAPI(mux) a.registerAPI(mux)
mux.HandleFunc("GET /tokens", a.auth(a.tokensPage)) mux.HandleFunc("GET /tokens", a.auth(a.tokensPage))
mux.HandleFunc("GET /apireference", a.auth(a.apiReference)) mux.HandleFunc("GET /apireference", a.auth(a.apiReference))
+160
View File
@@ -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()
}
+95
View File
@@ -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")
}
}
+48
View File
@@ -0,0 +1,48 @@
{{define "content"}}
<div class="cols">
{{with .Data}}
{{$e := .Errors}}{{$f := .Form}}
<section>
<h2>The router's state</h2>
<p>The web UI serves the router's own state for Prometheus at <code>https://{{.Host}}/metrics</code>: the uplink and its
pings, pending changes, DHCP leases, WireGuard peers and the certificate's expiry. It needs a token (any access)
from the <a href="/tokens">API access</a> page; nothing is switched on here.</p>
<pre class="log">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}}']</pre>
</section>
<form method="post" action="/prometheus">
<input type="hidden" name="csrf" value="{{$.CSRF}}">
<fieldset>
<legend>The machine (node_exporter)</legend>
<label class="inline"><input type="checkbox" name="enabled" {{if $f.Enabled}}checked{{end}}> Run node_exporter: CPU, memory, disks, network interfaces and systemd units</label>
<label>Port <input name="port" value="{{$f.Port}}" size="6" inputmode="numeric"></label>
{{with index $e "port"}}<p class="field-error">{{.}}</p>{{end}}
<p>Open to these zones (the port is closed to every other zone and to the internet):</p>
{{range .Zones}}<label class="inline"><input type="checkbox" name="zone" value="{{.Name}}" {{if .Checked}}checked{{end}}> {{.Name}}</label>
{{else}}<p class="muted">There is no zone yet: add a LAN or a tunnel first.</p>{{end}}
{{with index $e "zones"}}<p class="field-error">{{.}}</p>{{end}}
<p class="hint">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.</p>
</fieldset>
<button>Save</button>
</form>
{{if $f.Enabled}}
<section>
<h2>Scrape it</h2>
<pre class="log"> - job_name: router-node
static_configs:
- targets: ['{{.Target}}']</pre>
</section>
{{end}}
{{end}}
</div>
{{end}}
+1
View File
@@ -26,6 +26,7 @@
<a href="/ddns"{{if eq .Title "Dynamic DNS"}} aria-current="page"{{end}}>Dynamic DNS</a> <a href="/ddns"{{if eq .Title "Dynamic DNS"}} aria-current="page"{{end}}>Dynamic DNS</a>
<a href="/dnsproviders"{{if eq .Title "DNS providers"}} aria-current="page"{{end}}>DNS providers</a> <a href="/dnsproviders"{{if eq .Title "DNS providers"}} aria-current="page"{{end}}>DNS providers</a>
<a href="/certificate"{{if eq .Title "Certificate"}} aria-current="page"{{end}}>Certificate</a> <a href="/certificate"{{if eq .Title "Certificate"}} aria-current="page"{{end}}>Certificate</a>
<a href="/prometheus"{{if eq .Title "Prometheus"}} aria-current="page"{{end}}>Prometheus</a>
</div> </div>
<div class="group"><span>System</span> <div class="group"><span>System</span>
<a href="/update"{{if eq .Title "Update"}} aria-current="page"{{end}}>Update</a> <a href="/update"{{if eq .Title "Update"}} aria-current="page"{{end}}>Update</a>
+20
View File
@@ -859,6 +859,26 @@ let
}; };
expect = [ "natOnly does not apply to the router itself" ]; 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 = { localNoPorts = {
router = { router = {
lans.main = lan { }; lans.main = lan { };
+24
View File
@@ -13,6 +13,10 @@ let
stateVersion = "26.11"; stateVersion = "26.11";
}; };
router = { router = {
metrics.nodeExporter = {
enable = true;
zones = [ "main" ];
};
wan.interface = "eth1"; wan.interface = "eth1";
lans.main = { lans.main = {
interface = "eth2"; interface = "eth2";
@@ -105,6 +109,26 @@ pkgs.testers.runNixOSTest {
assert "<html" not in curl(f"'{ui}/dashboard?range=7d'") assert "<html" not in curl(f"'{ui}/dashboard?range=7d'")
client.succeed("curl -sfk -o /dev/null https://192.168.10.1/static/dashboard.js") client.succeed("curl -sfk -o /dev/null https://192.168.10.1/static/dashboard.js")
with subtest("Prometheus can scrape the router's state with a token, and the machine's from node_exporter"):
# /metrics of the web UI wants a token of the API access page.
assert client.succeed(f"curl -sk -o /dev/null -w '%{{http_code}}' {ui}/metrics") == "401"
secret = curl(f"-d csrf={csrf('/tokens')} -d name=prometheus -d scope=read {ui}/tokens | grep -o 'rtr_[A-Za-z0-9_-]*' | sed -n 1p").strip()
assert secret.startswith("rtr_"), secret
metrics = client.succeed(f"curl -sk -H 'Authorization: Bearer {secret}' -D /tmp/head {ui}/metrics")
assert "text/plain; version=0.0.4" in client.succeed("cat /tmp/head")
for line in ["# TYPE router_info gauge", "router_settings_unapplied 0", "router_ping_up{target=\"192.168.10.50\"", "router_dhcp_leases{lan=\"main\"} 0", "router_certificate_expiry_timestamp_seconds{source=\"self-signed\"}"]:
assert line in metrics, f"{line!r} missing:\n{metrics}"
# node_exporter: reachable from the LAN zone named in the settings, and on the router itself.
# (Into a file: grep -q would end curl with SIGPIPE, failing the pipe.)
client.wait_until_succeeds("curl -sf -o /tmp/node http://192.168.10.1:9100/metrics && grep -q '^node_systemd_unit_state' /tmp/node", timeout=60)
router.succeed("curl -sf -o /tmp/node http://127.0.0.1:9100/metrics && grep -q '^node_uname_info' /tmp/node")
# Not from the uplink: the rule names the LAN's device only.
rules = router.succeed("nft list chain inet router input")
assert 'iifname "eth2" tcp dport 9100 accept' in rules and 'iifname "eth1" tcp dport 9100' not in rules, rules
# The page for it shows what the settings say.
page = curl(f"{ui}/prometheus")
assert 'name="enabled" checked' in page and 'value="main" checked' in page and "job_name: router-node" in page, page
with subtest("a change saved in the web UI is shown as unapplied and can be discarded"): with subtest("a change saved in the web UI is shown as unapplied and can be discarded"):
router.succeed(f"cp {cfg} /var/lib/router/settings.confirmed.json") router.succeed(f"cp {cfg} /var/lib/router/settings.confirmed.json")
assert "match the confirmed system" in curl(f"{ui}/") assert "match the confirmed system" in curl(f"{ui}/")