metrics: Prometheus endpoint on its own --metrics listener; the pod exposes it inside the cluster only

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AeFqV96dVeBX94inzcgZKw
This commit is contained in:
2026-11-19 10:56:43 +01:00
co-authored by Claude Sonnet 5.5
parent b922808a51
commit c653ae4206
13 changed files with 306 additions and 3 deletions
+1 -1
View File
@@ -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 |
+24
View File
@@ -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())
+5
View File
@@ -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.
+2 -1
View File
@@ -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) {
+93
View File
@@ -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) + `"`
}
+58
View File
@@ -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)
}
}
+18
View File
@@ -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
}
+10 -1
View File
@@ -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
}
}
+3
View File
@@ -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
+33
View File
@@ -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
}
+44
View File
@@ -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)
}
}
+8
View File
@@ -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
+7
View File
@@ -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