From c653ae420665df2642c90d39e4d7b6ee7bc59679 Mon Sep 17 00:00:00 2001 From: Nils Stinnesbeck Date: Thu, 19 Nov 2026 10:56:43 +0100 Subject: [PATCH] metrics: Prometheus endpoint on its own --metrics listener; the pod exposes it inside the cluster only Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01AeFqV96dVeBX94inzcgZKw --- SPECS.md | 2 +- cmd/allmende/run.go | 24 ++++++++++ docs/PROTOCOL.md | 5 ++ internal/api/api_test.go | 3 +- internal/api/metrics.go | 93 ++++++++++++++++++++++++++++++++++++ internal/api/metrics_test.go | 58 ++++++++++++++++++++++ internal/p2p/guard.go | 18 +++++++ internal/p2p/ipgate.go | 11 ++++- internal/p2p/node.go | 3 ++ internal/p2p/stats.go | 33 +++++++++++++ internal/p2p/stats_test.go | 44 +++++++++++++++++ k8s/README.md | 8 ++++ k8s/base/statefulset.yaml | 7 +++ 13 files changed, 306 insertions(+), 3 deletions(-) create mode 100644 internal/api/metrics.go create mode 100644 internal/api/metrics_test.go create mode 100644 internal/p2p/stats.go create mode 100644 internal/p2p/stats_test.go diff --git a/SPECS.md b/SPECS.md index 2254710..bd50f8e 100644 --- a/SPECS.md +++ b/SPECS.md @@ -256,7 +256,7 @@ make image # build and push the container image (clean tree only) | `internal/store` | SQLite: listings, messages, inbox, reports, tips; conflict rules; hide rule | | `internal/p2p` | libp2p node, topics, validators, sync, discovery; `guard.go` (per-peer limits and bans), `ipgate.go` (connections per IP) | | `internal/inbox` | the owner's conversations, replies, block | -| `internal/api` | HTTP API (public reads, relay, admin); `ratelimit.go` (per-client limit, trusted proxies) | +| `internal/api` | HTTP API (public reads, relay, admin); `ratelimit.go` (per-client limit, trusted proxies); `metrics.go` (Prometheus text on the separate `--metrics` listener) | | `internal/places`, `internal/jcs`, `internal/pow` | place names, canonical JSON, hashcash (`pow.Mine`, the fast miner) | | `cmd/allmende-sim`, `cmd/allmende-load`, `cmd/allmende-conns` | network simulator; load and mining-time tool; holds many connections to one node to measure its memory | | `web/` | TypeScript UI (embedded), tests, build; `web/static/places.tsv` is generated | diff --git a/cmd/allmende/run.go b/cmd/allmende/run.go index c5c4b9f..acac8bc 100644 --- a/cmd/allmende/run.go +++ b/cmd/allmende/run.go @@ -53,6 +53,8 @@ func cmdRun(args []string) error { "address others should dial, when this node sits behind a router or in a container, e.g. /dns4/node.example.org/tcp/4001; repeatable") fs.Var(&listen, "listen", "libp2p listen multiaddr; repeatable (default: all interfaces, random ports)") httpAddr := fs.String("http", "127.0.0.1:8080", "address for the HTTP API") + metricsAddr := fs.String("metrics", "", + "serve metrics for Prometheus on this address, e.g. 127.0.0.1:9090 (off by default; it shows the node's internals and has no login, so keep it off the public network)") noLoginLink := fs.Bool("no-login-link", false, "do not print the owner sign-in link (it holds the admin token); use where the terminal is a log, e.g. in a container") noMDNS := fs.Bool("no-mdns", false, "do not look for peers on the local network") @@ -223,6 +225,28 @@ func cmdRun(args []string) error { } }() + if *metricsAddr != "" { + mln, err := net.Listen("tcp", *metricsAddr) + if err != nil { + return fmt.Errorf("--metrics: %w", err) + } + msrv := &http.Server{ + Handler: api.MetricsHandler(node, st, version, time.Now()), + ReadHeaderTimeout: 5 * time.Second, + WriteTimeout: 10 * time.Second, + } + go func() { + if err := msrv.Serve(mln); err != nil && !errors.Is(err, http.ErrServerClosed) { + log.Error("metrics server", "err", err) + } + }() + defer msrv.Close() + log.Info("metrics", "addr", mln.Addr().String()) + if host, _, _ := net.SplitHostPort(mln.Addr().String()); host != "127.0.0.1" && host != "::1" { + log.Warn("the metrics are reachable from other machines and have no login; keep this port off the public network") + } + } + log.Info("node running", "version", version, "peer_id", node.ID().String(), "identity", dev.Cert.Author[:12]+"…", "regions", []string(regions), "http", ln.Addr().String()) diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.md index 8621fb5..11f81e8 100644 --- a/docs/PROTOCOL.md +++ b/docs/PROTOCOL.md @@ -555,6 +555,11 @@ first, then through a relay; none for loopback and private ones) and prints when the built-in bootstrap name is down. The web UI shows the same under "Invite someone" (`#/invite`, in the menu once the owner has signed in). +`run --metrics ADDR` serves Prometheus metrics on a listener of its own (off by +default; no login, so not on a public address): peers, peers per followed +region, listings held, gossip dropped or rejected, peers banned, sync requests +and connections refused, Go memory (`internal/api/metrics.go`). + `run` also takes `--no-default-bootstrap`, `--no-dht` and `--no-mdns`, and keeps the peers it has met in `peers.json` next to its keys. diff --git a/internal/api/api_test.go b/internal/api/api_test.go index 078fb04..3d4d32c 100644 --- a/internal/api/api_test.go +++ b/internal/api/api_test.go @@ -28,6 +28,7 @@ const ( type fixture struct { srv *httptest.Server s *store.Store + node *p2p.Node dev *identity.Device phrase string // the recovery phrase of the identity behind dev } @@ -67,7 +68,7 @@ func newFixture(t *testing.T, tok string, tweak ...func(*Config)) *fixture { } srv := httptest.NewServer(New(cfg)) t.Cleanup(func() { srv.Close(); node.Close(); s.Close() }) - return &fixture{srv: srv, s: s, dev: dev, phrase: phrase} + return &fixture{srv: srv, s: s, node: node, dev: dev, phrase: phrase} } func (f *fixture) do(t *testing.T, method, path, body string, auth bool) (int, []byte) { diff --git a/internal/api/metrics.go b/internal/api/metrics.go new file mode 100644 index 0000000..41b9ffb --- /dev/null +++ b/internal/api/metrics.go @@ -0,0 +1,93 @@ +package api + +import ( + "fmt" + "net/http" + "runtime" + "sort" + "strings" + "time" + + "git.stinnesbeck.com/nils/allmende/internal/p2p" + "git.stinnesbeck.com/nils/allmende/internal/store" +) + +// MetricsHandler serves the node's counters in the Prometheus text format. It +// has no authentication and shows the node's internals, so it belongs on a +// listener of its own that only the operator can reach (`--metrics`), never on +// the public HTTP API. +func MetricsHandler(node *p2p.Node, st *store.Store, version string, started time.Time) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet && r.Method != http.MethodHead { + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + return + } + var b strings.Builder + write := func(name, typ, help string, samples ...sample) { + fmt.Fprintf(&b, "# HELP %s %s\n# TYPE %s %s\n", name, help, name, typ) + for _, s := range samples { + if s.labels == "" { + fmt.Fprintf(&b, "%s %v\n", name, s.value) + } else { + fmt.Fprintf(&b, "%s{%s} %v\n", name, s.labels, s.value) + } + } + } + + s := node.Stats() + write("allmende_build_info", "gauge", "The version of this node.", + sample{label("version", version), 1}) + write("allmende_start_time_seconds", "gauge", "When the node started, in unix seconds.", + sample{"", started.Unix()}) + write("allmende_peers", "gauge", "Connected peers.", sample{"", s.Peers}) + + regions := make([]string, 0, len(s.RegionPeers)) + for r := range s.RegionPeers { + regions = append(regions, r) + } + sort.Strings(regions) + var rp []sample + for _, r := range regions { + rp = append(rp, sample{label("region", r), s.RegionPeers[r]}) + } + write("allmende_region_peers", "gauge", "Peers known to follow each region this node follows.", rp...) + + if n, err := st.Count(r.Context()); err == nil { + write("allmende_listings", "gauge", "Live listings held.", sample{"", n}) + } + + write("allmende_guard_messages_dropped_total", "counter", + "Gossip messages dropped because a peer sent more than its rate.", sample{"", s.MessagesDropped}) + write("allmende_guard_messages_invalid_total", "counter", + "Gossip messages rejected as invalid.", sample{"", s.MessagesInvalid}) + write("allmende_guard_peers_banned_total", "counter", + "Peers banned for sending too many invalid messages.", sample{"", s.PeersBanned}) + write("allmende_guard_sync_refused_total", "counter", + "Sync requests refused (rate, parallel streams, banned peer).", sample{"", s.SyncRefused}) + write("allmende_connections_refused_total", "counter", + "Inbound connections refused.", + sample{label("reason", "address_full"), s.ConnectionsFull}, + sample{label("reason", "banned"), s.ConnectionsBanned}) + + var m runtime.MemStats + runtime.ReadMemStats(&m) + write("go_goroutines", "gauge", "Goroutines.", sample{"", runtime.NumGoroutine()}) + write("go_memstats_heap_alloc_bytes", "gauge", "Bytes of live heap objects.", sample{"", m.HeapAlloc}) + write("go_memstats_sys_bytes", "gauge", "Bytes the Go runtime obtained from the system.", sample{"", m.Sys}) + + w.Header().Set("Content-Type", "text/plain; version=0.0.4; charset=utf-8") + w.Header().Set("X-Content-Type-Options", "nosniff") + _, _ = w.Write([]byte(b.String())) + }) +} + +type sample struct { + labels string + value any +} + +// label formats one label, escaping what the text format requires. +func label(name, value string) string { + r := strings.NewReplacer(`\`, `\\`, `"`, `\"`, "\n", `\n`) + return name + `="` + r.Replace(value) + `"` +} diff --git a/internal/api/metrics_test.go b/internal/api/metrics_test.go new file mode 100644 index 0000000..5ffc2d3 --- /dev/null +++ b/internal/api/metrics_test.go @@ -0,0 +1,58 @@ +package api + +import ( + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" +) + +func scrape(t *testing.T, f *fixture, method string) (*http.Response, string) { + t.Helper() + srv := httptest.NewServer(MetricsHandler(f.node, f.s, `v1"x`, time.Unix(1_800_000_000, 0))) + defer srv.Close() + req, _ := http.NewRequest(method, srv.URL+"/metrics", nil) + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + b, _ := io.ReadAll(resp.Body) + return resp, string(b) +} + +func TestMetricsShowTheNodesCounters(t *testing.T) { + f := newFixture(t, token) + if code, body := f.do(t, "POST", "/api/v1/listings", draftJSON, true); code != 200 { + t.Fatalf("create: %d %s", code, body) + } + resp, body := scrape(t, f, "GET") + if resp.StatusCode != 200 || !strings.HasPrefix(resp.Header.Get("Content-Type"), "text/plain") { + t.Fatalf("status %d, type %q", resp.StatusCode, resp.Header.Get("Content-Type")) + } + for _, want := range []string{ + "# TYPE allmende_peers gauge\nallmende_peers 0\n", + `allmende_region_peers{region="u1x"} 0`, + "allmende_listings 1\n", + "allmende_start_time_seconds 1800000000\n", + `allmende_build_info{version="v1\"x"} 1`, // quotes in a label are escaped + "# TYPE allmende_guard_peers_banned_total counter\nallmende_guard_peers_banned_total 0\n", + `allmende_connections_refused_total{reason="address_full"} 0`, + `allmende_connections_refused_total{reason="banned"} 0`, + "go_goroutines ", + "go_memstats_heap_alloc_bytes ", + } { + if !strings.Contains(body, want) { + t.Errorf("missing %q in:\n%s", want, body) + } + } +} + +func TestMetricsOnlyAnswerReads(t *testing.T) { + f := newFixture(t, token) + if resp, _ := scrape(t, f, "POST"); resp.StatusCode != http.StatusMethodNotAllowed { + t.Fatalf("POST got %d", resp.StatusCode) + } +} diff --git a/internal/p2p/guard.go b/internal/p2p/guard.go index 52a3881..d45493f 100644 --- a/internal/p2p/guard.go +++ b/internal/p2p/guard.go @@ -4,6 +4,7 @@ import ( "context" "log/slog" "sync" + "sync/atomic" "time" pubsub "github.com/libp2p/go-libp2p-pubsub" @@ -38,6 +39,12 @@ type peerGuard struct { disconnect func(peer.ID) self peer.ID + // Totals since the start, for the metrics. + dropped atomic.Uint64 // messages dropped for exceeding the rate + invalid atomic.Uint64 // messages rejected as invalid + bans atomic.Uint64 // peers banned + syncRefused atomic.Uint64 // sync requests refused + mu sync.Mutex peers map[peer.ID]*peerCount streams map[peer.ID]int // sync streams open per peer @@ -107,6 +114,7 @@ func (g *peerGuard) admit(p peer.ID) bool { if c.total <= maxPerWindow { return true } + g.dropped.Add(1) if !c.noted { c.noted = true g.log.Warn("peer sends too much; dropping its messages until the minute is over", @@ -117,6 +125,7 @@ func (g *peerGuard) admit(p peer.ID) bool { // bad counts an invalid message from p and bans it past the limit. func (g *peerGuard) bad(p peer.ID) { + g.invalid.Add(1) g.mu.Lock() c := g.count(p) c.bad++ @@ -126,6 +135,7 @@ func (g *peerGuard) bad(p peer.ID) { return } g.bl.Add(p) + g.bans.Add(1) g.log.Warn("banned a peer that kept sending invalid messages", "peer", p, "invalid_in_a_minute", maxBadPerWindow, "for", banFor) if g.disconnect != nil { @@ -146,6 +156,14 @@ const ( // peers asking too often and peers with too many streams open; otherwise it // returns the function to call when the stream is done. func (g *peerGuard) beginSync(p peer.ID) (end func(), ok bool) { + end, ok = g.beginSyncUncounted(p) + if !ok { + g.syncRefused.Add(1) + } + return end, ok +} + +func (g *peerGuard) beginSyncUncounted(p peer.ID) (end func(), ok bool) { if g.banned(p) { return nil, false } diff --git a/internal/p2p/ipgate.go b/internal/p2p/ipgate.go index 526688d..888d006 100644 --- a/internal/p2p/ipgate.go +++ b/internal/p2p/ipgate.go @@ -29,6 +29,10 @@ type ipGate struct { counts map[string]int banned atomic.Pointer[func(peer.ID) bool] + + // Totals since the start, for the metrics. + refusedFull atomic.Uint64 // connections refused: the source address was full + refusedBanned atomic.Uint64 // connections refused: the peer is banned } func newIPGate(max int) *ipGate { return &ipGate{max: max, counts: map[string]int{}} } @@ -72,11 +76,16 @@ func (g *ipGate) full(a ma.Multiaddr) bool { func (g *ipGate) InterceptPeerDial(peer.ID) bool { return true } func (g *ipGate) InterceptAddrDial(peer.ID, ma.Multiaddr) bool { return true } func (g *ipGate) InterceptAccept(cm network.ConnMultiaddrs) bool { - return !g.full(cm.RemoteMultiaddr()) + if g.full(cm.RemoteMultiaddr()) { + g.refusedFull.Add(1) + return false + } + return true } func (g *ipGate) InterceptSecured(dir network.Direction, p peer.ID, _ network.ConnMultiaddrs) bool { if dir == network.DirInbound { if f := g.banned.Load(); f != nil && (*f)(p) { + g.refusedBanned.Add(1) return false } } diff --git a/internal/p2p/node.go b/internal/p2p/node.go index e79c16a..428ca37 100644 --- a/internal/p2p/node.go +++ b/internal/p2p/node.go @@ -138,6 +138,8 @@ type Node struct { log *slog.Logger // guard rate-limits and bans the peers that relay to us. guard *peerGuard + // gate limits inbound connections per address and refuses banned peers. + gate *ipGate // gossipIn counts listings that arrived by gossip since the last summary. gossipIn tally // recoverAsked counts the peers asked for our own listings (see recoverOwn). @@ -280,6 +282,7 @@ func New(ctx context.Context, cfg Config) (*Node, error) { regions: map[string]*regionRun{}, syncing: map[peer.ID]bool{}, boot: boot, + gate: gate, } if n.clock == nil { n.clock = time.Now diff --git a/internal/p2p/stats.go b/internal/p2p/stats.go new file mode 100644 index 0000000..52a7bfb --- /dev/null +++ b/internal/p2p/stats.go @@ -0,0 +1,33 @@ +package p2p + +// Stats is a snapshot of what the node counts about the network, for the +// metrics endpoint. The totals count from the start of the process. +type Stats struct { + Peers int // connected peers + RegionPeers map[string]int // peers known to follow each region we follow + + MessagesDropped uint64 // gossip dropped for exceeding a peer's rate + MessagesInvalid uint64 // gossip rejected as invalid + PeersBanned uint64 // peers banned for sending invalid messages + SyncRefused uint64 // sync requests refused (rate, streams, banned) + ConnectionsFull uint64 // inbound connections refused: source address at its limit + ConnectionsBanned uint64 // inbound connections refused: peer banned +} + +// Stats returns the current counters. +func (n *Node) Stats() Stats { + s := Stats{ + Peers: n.PeerCount(), + RegionPeers: map[string]int{}, + MessagesDropped: n.guard.dropped.Load(), + MessagesInvalid: n.guard.invalid.Load(), + PeersBanned: n.guard.bans.Load(), + SyncRefused: n.guard.syncRefused.Load(), + ConnectionsFull: n.gate.refusedFull.Load(), + ConnectionsBanned: n.gate.refusedBanned.Load(), + } + for _, r := range n.Regions() { + s.RegionPeers[r] = len(n.RegionPeers(r)) + } + return s +} diff --git a/internal/p2p/stats_test.go b/internal/p2p/stats_test.go new file mode 100644 index 0000000..8866a0c --- /dev/null +++ b/internal/p2p/stats_test.go @@ -0,0 +1,44 @@ +package p2p + +import ( + "testing" + + "github.com/libp2p/go-libp2p/core/network" +) + +func TestStatsCountWhatTheGuardAndTheGateDo(t *testing.T) { + a := startNode(t, nil, "u1x") + b := startNode(t, nil, "u1x") + connect(t, a, b) + eventually(t, "a sees b", func() bool { return a.Stats().Peers == 1 && a.Stats().RegionPeers["u1x"] == 1 }) + + // Invalid messages and a ban. + for i := 0; i < maxBadPerWindow; i++ { + a.guard.bad(b.host.ID()) + } + // A flood: messages over the rate are dropped. + for i := 0; i < maxPerWindow+5; i++ { + a.guard.admit(b.host.ID()) + } + // A banned peer's sync request, and a connection from a full address. + a.guard.beginSync(b.host.ID()) + a.gate.mu.Lock() + a.gate.counts["203.0.113.7"] = DefaultConnsPerIP + a.gate.mu.Unlock() + a.gate.InterceptAccept(fakeConnAddrs{mustAddr(t, "/ip4/203.0.113.7/tcp/1000")}) + a.gate.InterceptSecured(network.DirInbound, b.host.ID(), nil) + + s := a.Stats() + if s.MessagesInvalid != maxBadPerWindow || s.PeersBanned != 1 { + t.Errorf("invalid %d, banned %d", s.MessagesInvalid, s.PeersBanned) + } + if s.MessagesDropped != 5 { + t.Errorf("dropped %d, want 5", s.MessagesDropped) + } + if s.SyncRefused != 1 { + t.Errorf("sync refused %d, want 1", s.SyncRefused) + } + if s.ConnectionsFull != 1 || s.ConnectionsBanned != 1 { + t.Errorf("connections refused: full %d, banned %d", s.ConnectionsFull, s.ConnectionsBanned) + } +} diff --git a/k8s/README.md b/k8s/README.md index 89f7528..769bd93 100644 --- a/k8s/README.md +++ b/k8s/README.md @@ -76,6 +76,14 @@ so: new node is up. If you would rather have a renewable identity, create it once by hand with a phrase (`allmende init`, without `--no-phrase`) on the volume before the first start. +- **Metrics.** The node serves Prometheus metrics on container port 9090 + (`--metrics`): peers (and peers per region), listings held, gossip dropped or + rejected, peers banned, sync and connections refused, and Go memory. They show + whether the node is being attacked or running short of memory. The port has no + login and no Service or IngressRoute points to it, so only things inside the + cluster can reach it; keep it that way. Scrape it with a PodMonitor + (`port: metrics`) or `kubectl -n allmende port-forward allmende-0 9090:9090` + and `curl localhost:9090/metrics`. Counters start at zero on every restart. - **One replica only.** A second pod would be a second node with its own identity, not a copy. - **No sign-in link in the log.** `allmende run` normally prints the owner diff --git a/k8s/base/statefulset.yaml b/k8s/base/statefulset.yaml index d2b4806..2091173 100644 --- a/k8s/base/statefulset.yaml +++ b/k8s/base/statefulset.yaml @@ -52,6 +52,7 @@ spec: --no-login-link \ --difficulty "${DIFFICULTY:-24}" \ --http 0.0.0.0:8080 \ + --metrics 0.0.0.0:9090 \ --listen /ip4/0.0.0.0/tcp/4001 \ --listen /ip4/0.0.0.0/udp/4001/quic-v1 \ --announce "/dns4/${PUBLIC_HOST}/tcp/${PUBLIC_PORT}" \ @@ -88,6 +89,12 @@ spec: - name: http containerPort: 8080 protocol: TCP + # Prometheus metrics. No Service or IngressRoute points here, so the + # port is reachable only inside the cluster (by pod IP); it has no + # login. Scrape it with a PodMonitor or a pod annotation. + - name: metrics + containerPort: 9090 + protocol: TCP readinessProbe: httpGet: path: /api/v1/status