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