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