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:
@@ -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.")
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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))
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -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}}
|
||||
@@ -26,6 +26,7 @@
|
||||
<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="/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 class="group"><span>System</span>
|
||||
<a href="/update"{{if eq .Title "Update"}} aria-current="page"{{end}}>Update</a>
|
||||
|
||||
Reference in New Issue
Block a user