Skip to content

Agent Mesh

controlplane: export mesh state and per-route request metrics

Antonio Ojea52fd80ae838c
diff --git a/internal/controlplane/metrics.go b/internal/controlplane/metrics.go
new file mode 100644
index 00000000..cce00825
--- /dev/null
+++ b/internal/controlplane/metrics.go
@@ -0,0 +1,375 @@
+// Copyright 2026 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package controlplane
+
+import (
+ "context"
+ "net/http"
+ "strconv"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/google/sam/api"
+ "github.com/google/sam/internal/storage"
+ "github.com/prometheus/client_golang/prometheus"
+ "github.com/prometheus/client_golang/prometheus/promauto"
+ "github.com/prometheus/client_golang/prometheus/promhttp"
+)
+
+var (
+ httpRequestsTotal = promauto.NewCounterVec(
+ prometheus.CounterOpts{
+ Name: "sam_control_plane_http_requests_total",
+ Help: "Control-plane HTTP requests by registered route and status code",
+ },
+ []string{"route", "code"},
+ )
+
+ httpRequestDurationSeconds = promauto.NewHistogramVec(
+ prometheus.HistogramOpts{
+ Name: "sam_control_plane_http_request_duration_seconds",
+ Help: "Time a control-plane request occupied its handler",
+ Buckets: []float64{0.001, 0.0025, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10},
+ },
+ []string{"route"},
+ )
+)
+
+// observeRoute counts and times requests to one registered mux pattern. The
+// pattern, not the request path, is the label: paths carry peer ids and token
+// ids chosen off-plane, so the raw path can never become a label.
+func observeRoute(pattern string, h http.HandlerFunc) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ start := time.Now()
+ rec := &statusWriter{ResponseWriter: w}
+ h(rec, r)
+ httpRequestsTotal.WithLabelValues(pattern, strconv.Itoa(rec.status())).Inc()
+ httpRequestDurationSeconds.WithLabelValues(pattern).Observe(time.Since(start).Seconds())
+ })
+}
+
+type statusWriter struct {
+ http.ResponseWriter
+ code int
+}
+
+func (s *statusWriter) Unwrap() http.ResponseWriter { return s.ResponseWriter }
+
+func (s *statusWriter) status() int {
+ if s.code == 0 {
+ return http.StatusOK
+ }
+ return s.code
+}
+
+func (s *statusWriter) WriteHeader(code int) {
+ if s.code == 0 {
+ s.code = code
+ }
+ s.ResponseWriter.WriteHeader(code)
+}
+
+const (
+ // meshStateTTL bounds how often a scrape may hit the store. Router leases
+ // renew on the order of minutes, so anything fresher is noise.
+ meshStateTTL = 30 * time.Second
+ // meshStateTimeout caps one refresh so a slow store cannot hold a scrape
+ // past the scraper's own deadline.
+ meshStateTimeout = 5 * time.Second
+)
+
+// Node admission states as reported by meshStateCollector. "admitted" is
+// what CheckAdmission says, not liveness: a node that enrolled once and went
+// away stays admitted until its session expires. Liveness is
+// sam_control_plane_mesh_connected_peers.
+const (
+ nodeStateAdmitted = "admitted"
+ nodeStateExpired = "expired"
+ nodeStateBanned = "banned"
+)
+
+// Bootstrap token states as reported by meshStateCollector.
+const (
+ tokenStateActive = "active"
+ tokenStateRevoked = "revoked"
+ tokenStateExpired = "expired"
+ tokenStateExhausted = "exhausted"
+)
+
+// meshSnapshot is what one refresh of the store reduces to. Only counts and
+// per-router figures survive: a node's peer id is never a label.
+type meshSnapshot struct {
+ nodesByRoleState map[[2]string]int
+ users int
+ enrollmentRequests map[string]int
+ tokensByState map[string]int
+ routers []storage.RouterLease
+ meshConnectedPeers int
+}
+
+// meshStateCollector exports the control plane's view of the mesh: who is
+// enrolled, which routers hold a lease and what they report attached to them.
+// The store is the source of truth shared by every replica, so each replica
+// exports the same figures and a dashboard may take any one of them.
+type meshStateCollector struct {
+ store storage.Store
+ ttl time.Duration
+ timeout time.Duration
+ now func() time.Time
+
+ mu sync.Mutex
+ fetchedAt time.Time
+ snapshot meshSnapshot
+ ok bool
+
+ nodesDesc *prometheus.Desc
+ usersDesc *prometheus.Desc
+ requestsDesc *prometheus.Desc
+ tokensDesc *prometheus.Desc
+ routersDesc *prometheus.Desc
+ routerPeersDesc *prometheus.Desc
+ routerDHTDesc *prometheus.Desc
+ routerLeaseDesc *prometheus.Desc
+ meshPeersDesc *prometheus.Desc
+ scrapeOKDesc *prometheus.Desc
+ scrapeSampleDesc *prometheus.Desc
+}
+
+func newMeshStateCollector(store storage.Store) *meshStateCollector {
+ return &meshStateCollector{
+ store: store,
+ ttl: meshStateTTL,
+ timeout: meshStateTimeout,
+ now: time.Now,
+ nodesDesc: prometheus.NewDesc(
+ "sam_control_plane_enrolled_nodes",
+ "Enrolled identities by role and admission state",
+ []string{"role", "state"}, nil),
+ usersDesc: prometheus.NewDesc(
+ "sam_control_plane_users",
+ "Human identities that have enrolled",
+ nil, nil),
+ requestsDesc: prometheus.NewDesc(
+ "sam_control_plane_enrollment_requests",
+ "Enrollment requests by status",
+ []string{"status"}, nil),
+ tokensDesc: prometheus.NewDesc(
+ "sam_control_plane_bootstrap_tokens",
+ "Bootstrap tokens by state",
+ []string{"state"}, nil),
+ routersDesc: prometheus.NewDesc(
+ "sam_control_plane_routers_active",
+ "Routers holding an unexpired lease",
+ nil, nil),
+ routerPeersDesc: prometheus.NewDesc(
+ "sam_control_plane_router_connected_peers",
+ "Peers a router reported connected on its last lease renewal",
+ []string{"router"}, nil),
+ routerDHTDesc: prometheus.NewDesc(
+ "sam_control_plane_router_dht_size",
+ "DHT routing table size a router reported on its last lease renewal",
+ []string{"router"}, nil),
+ routerLeaseDesc: prometheus.NewDesc(
+ "sam_control_plane_router_lease_renewed_timestamp_seconds",
+ "Unix time of a router's last lease renewal",
+ []string{"router"}, nil),
+ meshPeersDesc: prometheus.NewDesc(
+ "sam_control_plane_mesh_connected_peers",
+ "Distinct non-router peers connected to at least one active router",
+ nil, nil),
+ scrapeOKDesc: prometheus.NewDesc(
+ "sam_control_plane_mesh_state_scrape_success",
+ "1 if the mesh state was read from the store, 0 if the last read failed",
+ nil, nil),
+ scrapeSampleDesc: prometheus.NewDesc(
+ "sam_control_plane_mesh_state_timestamp_seconds",
+ "Unix time the exported mesh state was read from the store",
+ nil, nil),
+ }
+}
+
+func (c *meshStateCollector) Describe(ch chan<- *prometheus.Desc) {
+ for _, d := range []*prometheus.Desc{
+ c.nodesDesc, c.usersDesc, c.requestsDesc, c.tokensDesc, c.routersDesc,
+ c.routerPeersDesc, c.routerDHTDesc, c.routerLeaseDesc, c.meshPeersDesc,
+ c.scrapeOKDesc, c.scrapeSampleDesc,
+ } {
+ ch <- d
+ }
+}
+
+func (c *meshStateCollector) Collect(ch chan<- prometheus.Metric) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+
+ now := c.now()
+ if now.Sub(c.fetchedAt) >= c.ttl {
+ c.refresh(now)
+ }
+
+ ok := 0.0
+ if c.ok {
+ ok = 1
+ }
+ ch <- prometheus.MustNewConstMetric(c.scrapeOKDesc, prometheus.GaugeValue, ok)
+ if c.fetchedAt.IsZero() {
+ return
+ }
+ ch <- prometheus.MustNewConstMetric(c.scrapeSampleDesc, prometheus.GaugeValue, float64(c.fetchedAt.Unix()))
+
+ s := c.snapshot
+ for k, n := range s.nodesByRoleState {
+ ch <- prometheus.MustNewConstMetric(c.nodesDesc, prometheus.GaugeValue, float64(n), k[0], k[1])
+ }
+ ch <- prometheus.MustNewConstMetric(c.usersDesc, prometheus.GaugeValue, float64(s.users))
+ for status, n := range s.enrollmentRequests {
+ ch <- prometheus.MustNewConstMetric(c.requestsDesc, prometheus.GaugeValue, float64(n), status)
+ }
+ for state, n := range s.tokensByState {
+ ch <- prometheus.MustNewConstMetric(c.tokensDesc, prometheus.GaugeValue, float64(n), state)
+ }
+ ch <- prometheus.MustNewConstMetric(c.routersDesc, prometheus.GaugeValue, float64(len(s.routers)))
+ for _, r := range s.routers {
+ ch <- prometheus.MustNewConstMetric(c.routerPeersDesc, prometheus.GaugeValue, float64(len(r.ConnectedPeers)), r.PeerID)
+ ch <- prometheus.MustNewConstMetric(c.routerDHTDesc, prometheus.GaugeValue, float64(r.DHTSize), r.PeerID)
+ ch <- prometheus.MustNewConstMetric(c.routerLeaseDesc, prometheus.GaugeValue, float64(r.LastRenewal.Unix()), r.PeerID)
+ }
+ ch <- prometheus.MustNewConstMetric(c.meshPeersDesc, prometheus.GaugeValue, float64(s.meshConnectedPeers))
+}
+
+// refresh replaces the snapshot from the store. A failed read keeps the last
+// good snapshot and flips the success gauge, so a store outage is visible
+// without the figures vanishing.
+func (c *meshStateCollector) refresh(now time.Time) {
+ ctx, cancel := context.WithTimeout(context.Background(), c.timeout)
+ defer cancel()
+
+ snap, err := readMeshSnapshot(ctx, c.store, now)
+ if err != nil {
+ logger.Warnf("Mesh state metrics refresh failed: %v", err)
+ c.ok = false
+ return
+ }
+ c.snapshot = snap
+ c.fetchedAt = now
+ c.ok = true
+}
+
+func readMeshSnapshot(ctx context.Context, store storage.Store, now time.Time) (meshSnapshot, error) {
+ snap := meshSnapshot{
+ nodesByRoleState: map[[2]string]int{},
+ enrollmentRequests: map[string]int{},
+ tokensByState: map[string]int{},
+ }
+
+ nodes, err := store.ListNodes(ctx)
+ if err != nil {
+ return snap, err
+ }
+ for i := range nodes {
+ snap.nodesByRoleState[[2]string{nodes[i].Role, nodeState(&nodes[i], now)}]++
+ }
+
+ users, err := store.ListUsers(ctx)
+ if err != nil {
+ return snap, err
+ }
+ snap.users = len(users)
+
+ reqs, err := store.ListEnrollmentRequests(ctx)
+ if err != nil {
+ return snap, err
+ }
+ for _, r := range reqs {
+ snap.enrollmentRequests[enrollmentStatusLabel(r.Status)]++
+ }
+
+ tokens, err := store.ListBootstrapTokens(ctx)
+ if err != nil {
+ return snap, err
+ }
+ for i := range tokens {
+ snap.tokensByState[tokenState(&tokens[i], now)]++
+ }
+
+ routers, err := store.GetActiveRouters(ctx)
+ if err != nil {
+ return snap, err
+ }
+ snap.routers = routers
+ snap.meshConnectedPeers = countMeshPeers(routers)
+
+ return snap, nil
+}
+
+// enrollmentStatusLabel turns ENROLLMENT_STATUS_PENDING into "pending".
+func enrollmentStatusLabel(s api.EnrollmentStatus) string {
+ return strings.ToLower(strings.TrimPrefix(s.String(), "ENROLLMENT_STATUS_"))
+}
+
+func nodeState(n *storage.EnrolledNode, now time.Time) string {
+ switch n.CheckAdmission(now) {
+ case nil:
+ return nodeStateAdmitted
+ case storage.ErrNodeBanned:
+ return nodeStateBanned
+ default:
+ return nodeStateExpired
+ }
+}
+
+func tokenState(t *storage.BootstrapToken, now time.Time) string {
+ switch {
+ case t.IsRevoked():
+ return tokenStateRevoked
+ case !t.ExpiresAt.IsZero() && now.After(t.ExpiresAt):
+ return tokenStateExpired
+ case t.UsagesCount >= t.MaxUsages:
+ return tokenStateExhausted
+ default:
+ return tokenStateActive
+ }
+}
+
+// countMeshPeers is the headline mesh size: every peer some active router has
+// attached, counted once, with the routers themselves left out since they
+// hold connections to each other.
+func countMeshPeers(routers []storage.RouterLease) int {
+ routerIDs := make(map[string]bool, len(routers))
+ for _, r := range routers {
+ routerIDs[r.PeerID] = true
+ }
+ seen := map[string]bool{}
+ for _, r := range routers {
+ for _, p := range r.ConnectedPeers {
+ if !routerIDs[p] {
+ seen[p] = true
+ }
+ }
+ }
+ return len(seen)
+}
+
+// metricsHandler serves the process-wide registry, which carries the request
+// counters above and the Go runtime, alongside this server's own mesh state.
+// The mesh collector is per server rather than global so two servers in one
+// process (tests, sam-one) never fight over a registration.
+func (s *Server) metricsHandler() http.Handler {
+ return promhttp.HandlerFor(
+ prometheus.Gatherers{prometheus.DefaultGatherer, s.metricsRegistry},
+ promhttp.HandlerOpts{},
+ )
+}
diff --git a/internal/controlplane/metrics_test.go b/internal/controlplane/metrics_test.go
new file mode 100644
index 00000000..e37c2da0
--- /dev/null
+++ b/internal/controlplane/metrics_test.go
@@ -0,0 +1,323 @@
+// Copyright 2026 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package controlplane
+
+import (
+ "context"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/google/sam/api"
+ "github.com/google/sam/internal/storage"
+ "github.com/prometheus/client_golang/prometheus"
+ dto "github.com/prometheus/client_model/go"
+)
+
+// gathered indexes one Gather() by metric name and sorted label pairs so a
+// test can ask for a sample by "name{k=v,...}".
+type gathered map[string]float64
+
+func gather(t *testing.T, c prometheus.Collector) gathered {
+ t.Helper()
+ reg := prometheus.NewPedanticRegistry()
+ if err := reg.Register(c); err != nil {
+ t.Fatalf("register: %v", err)
+ }
+ fams, err := reg.Gather()
+ if err != nil {
+ t.Fatalf("gather: %v", err)
+ }
+ out := gathered{}
+ for _, f := range fams {
+ for _, m := range f.GetMetric() {
+ out[sampleKey(f.GetName(), m)] = m.GetGauge().GetValue()
+ }
+ }
+ return out
+}
+
+func sampleKey(name string, m *dto.Metric) string {
+ var parts []string
+ for _, l := range m.GetLabel() {
+ parts = append(parts, l.GetName()+"="+l.GetValue())
+ }
+ if len(parts) == 0 {
+ return name
+ }
+ return name + "{" + strings.Join(parts, ",") + "}"
+}
+
+func (g gathered) want(t *testing.T, key string, v float64) {
+ t.Helper()
+ got, ok := g[key]
+ if !ok {
+ t.Fatalf("missing sample %s; have %v", key, g)
+ }
+ if got != v {
+ t.Errorf("%s = %v, want %v", key, got, v)
+ }
+}
+
+func newMetricsTestStore(t *testing.T) storage.Store {
+ t.Helper()
+ store, err := storage.NewSQLStore("sqlite", filepath.Join(t.TempDir(), "cp.db"))
+ if err != nil {
+ t.Fatalf("store: %v", err)
+ }
+ t.Cleanup(func() { _ = store.Close() })
+ return store
+}
+
+func seedMeshState(t *testing.T, store storage.Store, now time.Time) {
+ t.Helper()
+ ctx := context.Background()
+
+ nodes := []storage.EnrolledNode{
+ {PeerID: "node-a", Role: api.RoleNode, EnrolledAt: now, ExpiresAt: now.Add(time.Hour)},
+ {PeerID: "node-b", Role: api.RoleNode, EnrolledAt: now, ExpiresAt: now.Add(time.Hour)},
+ {PeerID: "node-old", Role: api.RoleNode, EnrolledAt: now.Add(-2 * time.Hour), ExpiresAt: now.Add(-time.Hour)},
+ {PeerID: "node-bad", Role: api.RoleNode, EnrolledAt: now, ExpiresAt: now.Add(time.Hour)},
+ {PeerID: "router-1", Role: api.RoleRouter, EnrolledAt: now, ExpiresAt: now.Add(time.Hour)},
+ {PeerID: "router-2", Role: api.RoleRouter, EnrolledAt: now, ExpiresAt: now.Add(time.Hour)},
+ }
+ for i := range nodes {
+ nodes[i].PublicKey = []byte("pk-" + nodes[i].PeerID)
+ nodes[i].Biscuit = []byte("biscuit")
+ nodes[i].EnrollmentType = "test"
+ if err := store.EnrollNode(ctx, &nodes[i]); err != nil {
+ t.Fatalf("enroll %s: %v", nodes[i].PeerID, err)
+ }
+ }
+ if err := store.SetNodeBanned(ctx, "node-bad", true); err != nil {
+ t.Fatalf("ban: %v", err)
+ }
+
+ // Routers peer with each other and share node-a; node-c is attached to
+ // router-2 without an enrollment row, as a peer mid-handshake would be.
+ leases := []storage.RouterLease{
+ {PeerID: "router-1", Addresses: []string{"/ip4/10.0.0.1/tcp/4501"}, LastRenewal: now, ExpiresAt: now.Add(time.Hour),
+ ConnectedPeers: []string{"router-2", "node-a", "node-b"}, DHTSize: 5},
+ {PeerID: "router-2", Addresses: []string{"/ip4/10.0.0.2/tcp/4501"}, LastRenewal: now.Add(-time.Minute), ExpiresAt: now.Add(time.Hour),
+ ConnectedPeers: []string{"router-1", "node-a", "node-c"}, DHTSize: 4},
+ {PeerID: "router-gone", Addresses: []string{"/ip4/10.0.0.3/tcp/4501"}, LastRenewal: now.Add(-2 * time.Hour), ExpiresAt: now.Add(-time.Hour),
+ ConnectedPeers: []string{"node-z"}, DHTSize: 1},
+ }
+ for i := range leases {
+ if err := store.UpsertRouterLease(ctx, &leases[i]); err != nil {
+ t.Fatalf("lease %s: %v", leases[i].PeerID, err)
+ }
+ }
+
+ if err := store.SaveUser(ctx, &storage.User{ID: "alice", Issuer: "https://issuer", Email: "[email protected]", Role: "user", CreatedAt: now}); err != nil {
+ t.Fatalf("user: %v", err)
+ }
+
+ tokens := []storage.BootstrapToken{
+ {ID: "tok-active", TokenHash: "h1", Role: api.RoleNode, MaxUsages: 5, UsagesCount: 1, CreatedAt: now, ExpiresAt: now.Add(time.Hour)},
+ {ID: "tok-exhausted", TokenHash: "h2", Role: api.RoleNode, MaxUsages: 1, UsagesCount: 1, CreatedAt: now, ExpiresAt: now.Add(time.Hour)},
+ {ID: "tok-expired", TokenHash: "h3", Role: api.RoleNode, MaxUsages: 5, CreatedAt: now.Add(-2 * time.Hour), ExpiresAt: now.Add(-time.Hour)},
+ {ID: "tok-revoked", TokenHash: "h4", Role: api.RoleNode, MaxUsages: 5, CreatedAt: now, ExpiresAt: now.Add(time.Hour)},
+ }
+ for i := range tokens {
+ if err := store.SaveBootstrapToken(ctx, &tokens[i]); err != nil {
+ t.Fatalf("token %s: %v", tokens[i].ID, err)
+ }
+ }
+ if err := store.RevokeBootstrapToken(ctx, "tok-revoked"); err != nil {
+ t.Fatalf("revoke: %v", err)
+ }
+
+ reqs := []storage.EnrollmentRequest{
+ {ID: "req-1", PeerID: "pending-1", TokenID: "tok-active", Status: api.EnrollmentStatus_ENROLLMENT_STATUS_PENDING, CreatedAt: now},
+ {ID: "req-2", PeerID: "pending-2", TokenID: "tok-active", Status: api.EnrollmentStatus_ENROLLMENT_STATUS_PENDING, CreatedAt: now},
+ {ID: "req-3", PeerID: "node-a", TokenID: "tok-active", Status: api.EnrollmentStatus_ENROLLMENT_STATUS_APPROVED, CreatedAt: now},
+ }
+ for i := range reqs {
+ reqs[i].PublicKey = []byte("pk-" + reqs[i].PeerID)
+ if err := store.CreateEnrollmentRequest(ctx, &reqs[i]); err != nil {
+ t.Fatalf("request %s: %v", reqs[i].ID, err)
+ }
+ }
+}
+
+func TestMeshStateCollectorExportsStoreState(t *testing.T) {
+ store := newMetricsTestStore(t)
+ now := time.Now()
+ seedMeshState(t, store, now)
+
+ c := newMeshStateCollector(store)
+ c.now = func() time.Time { return now }
+ g := gather(t, c)
+
+ g.want(t, "sam_control_plane_mesh_state_scrape_success", 1)
+ g.want(t, "sam_control_plane_mesh_state_timestamp_seconds", float64(now.Unix()))
+
+ g.want(t, "sam_control_plane_enrolled_nodes{role="+api.RoleNode+",state=admitted}", 2)
+ g.want(t, "sam_control_plane_enrolled_nodes{role="+api.RoleNode+",state=expired}", 1)
+ g.want(t, "sam_control_plane_enrolled_nodes{role="+api.RoleNode+",state=banned}", 1)
+ g.want(t, "sam_control_plane_enrolled_nodes{role="+api.RoleRouter+",state=admitted}", 2)
+ g.want(t, "sam_control_plane_users", 1)
+
+ g.want(t, "sam_control_plane_enrollment_requests{status=pending}", 2)
+ g.want(t, "sam_control_plane_enrollment_requests{status=approved}", 1)
+
+ g.want(t, "sam_control_plane_bootstrap_tokens{state=active}", 1)
+ g.want(t, "sam_control_plane_bootstrap_tokens{state=exhausted}", 1)
+ g.want(t, "sam_control_plane_bootstrap_tokens{state=expired}", 1)
+ g.want(t, "sam_control_plane_bootstrap_tokens{state=revoked}", 1)
+
+ // The lapsed lease is neither counted nor labelled.
+ g.want(t, "sam_control_plane_routers_active", 2)
+ g.want(t, "sam_control_plane_router_connected_peers{router=router-1}", 3)
+ g.want(t, "sam_control_plane_router_connected_peers{router=router-2}", 3)
+ g.want(t, "sam_control_plane_router_dht_size{router=router-1}", 5)
+ g.want(t, "sam_control_plane_router_dht_size{router=router-2}", 4)
+ g.want(t, "sam_control_plane_router_lease_renewed_timestamp_seconds{router=router-2}", float64(now.Add(-time.Minute).Unix()))
+ if _, ok := g["sam_control_plane_router_connected_peers{router=router-gone}"]; ok {
+ t.Error("lapsed router lease was exported")
+ }
+
+ // node-a counted once, routers excluded, node-z behind a dead lease ignored.
+ g.want(t, "sam_control_plane_mesh_connected_peers", 3)
+}
+
+func TestMeshStateCollectorCachesWithinTTL(t *testing.T) {
+ store := newMetricsTestStore(t)
+ now := time.Now()
+ seedMeshState(t, store, now)
+
+ clock := now
+ c := newMeshStateCollector(store)
+ c.now = func() time.Time { return clock }
+
+ gather(t, c).want(t, "sam_control_plane_routers_active", 2)
+
+ extra := storage.RouterLease{PeerID: "router-3", Addresses: []string{"/ip4/10.0.0.4/tcp/4501"}, LastRenewal: now, ExpiresAt: now.Add(time.Hour)}
+ if err := store.UpsertRouterLease(context.Background(), &extra); err != nil {
+ t.Fatal(err)
+ }
+
+ clock = now.Add(c.ttl / 2)
+ gather(t, c).want(t, "sam_control_plane_routers_active", 2)
+
+ clock = now.Add(c.ttl)
+ gather(t, c).want(t, "sam_control_plane_routers_active", 3)
+}
+
+func TestMeshStateCollectorKeepsLastSnapshotWhenStoreFails(t *testing.T) {
+ store := newMetricsTestStore(t)
+ now := time.Now()
+ seedMeshState(t, store, now)
+
+ clock := now
+ c := newMeshStateCollector(store)
+ c.now = func() time.Time { return clock }
+
+ g := gather(t, c)
+ g.want(t, "sam_control_plane_mesh_state_scrape_success", 1)
+ g.want(t, "sam_control_plane_routers_active", 2)
+
+ if err := store.Close(); err != nil {
+ t.Fatal(err)
+ }
+ clock = now.Add(c.ttl)
+
+ g = gather(t, c)
+ g.want(t, "sam_control_plane_mesh_state_scrape_success", 0)
+ g.want(t, "sam_control_plane_routers_active", 2)
+ g.want(t, "sam_control_plane_mesh_state_timestamp_seconds", float64(now.Unix()))
+}
+
+func TestMeshStateCollectorBeforeFirstReadReportsOnlyFailure(t *testing.T) {
+ store := newMetricsTestStore(t)
+ if err := store.Close(); err != nil {
+ t.Fatal(err)
+ }
+
+ g := gather(t, newMeshStateCollector(store))
+ g.want(t, "sam_control_plane_mesh_state_scrape_success", 0)
+ if len(g) != 1 {
+ t.Errorf("expected only the success gauge before any snapshot, got %v", g)
+ }
+}
+
+func TestObserveRouteLabelsByPatternAndCode(t *testing.T) {
+ before := counterValue(t, httpRequestsTotal, "/admin/nodes/", "404")
+
+ h := observeRoute("/admin/nodes/", func(w http.ResponseWriter, r *http.Request) {
+ http.Error(w, "no such node", http.StatusNotFound)
+ })
+ rec := httptest.NewRecorder()
+ h.ServeHTTP(rec, httptest.NewRequest(http.MethodPost, "/admin/nodes/12D3KooWsecret/unban", nil))
+ if rec.Code != http.StatusNotFound {
+ t.Fatalf("status = %d", rec.Code)
+ }
+
+ if got := counterValue(t, httpRequestsTotal, "/admin/nodes/", "404"); got != before+1 {
+ t.Errorf("counter = %v, want %v", got, before+1)
+ }
+
+ // A handler that never calls WriteHeader is a 200.
+ before = counterValue(t, httpRequestsTotal, "/info", "200")
+ observeRoute("/info", func(w http.ResponseWriter, r *http.Request) {
+ _, _ = io.WriteString(w, "ok")
+ }).ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/info", nil))
+ if got := counterValue(t, httpRequestsTotal, "/info", "200"); got != before+1 {
+ t.Errorf("counter = %v, want %v", got, before+1)
+ }
+}
+
+func counterValue(t *testing.T, vec *prometheus.CounterVec, labels ...string) float64 {
+ t.Helper()
+ var m dto.Metric
+ if err := vec.WithLabelValues(labels...).Write(&m); err != nil {
+ t.Fatal(err)
+ }
+ return m.GetCounter().GetValue()
+}
+
+func TestMetricsEndpointServesMeshStateAndRuntime(t *testing.T) {
+ issuer, _ := startCustomMockOIDC(t)
+ srv, store, baseURL := setupTestServer(t, issuer)
+ defer func() {
+ _ = srv.Close()
+ _ = store.Close()
+ }()
+
+ resp, err := http.Get(baseURL + "/metrics")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+ body, _ := io.ReadAll(resp.Body)
+ if resp.StatusCode != http.StatusOK {
+ t.Fatalf("status %d: %s", resp.StatusCode, body)
+ }
+ for _, want := range []string{
+ "sam_control_plane_mesh_state_scrape_success 1",
+ "sam_control_plane_routers_active 0",
+ "sam_control_plane_mesh_connected_peers 0",
+ "go_goroutines",
+ } {
+ if !strings.Contains(string(body), want) {
+ t.Errorf("/metrics missing %q", want)
+ }
+ }
+}
diff --git a/internal/controlplane/server.go b/internal/controlplane/server.go
index 6f7dd9e3..d440f6b0 100644
--- a/internal/controlplane/server.go
+++ b/internal/controlplane/server.go
@@ -45,7 +45,7 @@ import (
"github.com/libp2p/go-libp2p/core/crypto"
"github.com/libp2p/go-libp2p/core/peer"
"github.com/multiformats/go-multiaddr"
- "github.com/prometheus/client_golang/prometheus/promhttp"
+ "github.com/prometheus/client_golang/prometheus"
"golang.org/x/time/rate"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
@@ -93,6 +93,10 @@ type Server struct {
catalogMu sync.RWMutex
catalog map[string]nodeCatalogEntry
+ // metricsRegistry holds this server's store-backed mesh state collector;
+ // see metricsHandler.
+ metricsRegistry *prometheus.Registry
+
ctx context.Context
cancel context.CancelFunc
wg sync.WaitGroup
@@ -108,15 +112,19 @@ func NewServer(config Options, store storage.Store) (*Server, error) {
ctx, cancel := context.WithCancel(context.Background())
+ reg := prometheus.NewRegistry()
+ reg.MustRegister(newMeshStateCollector(store))
+
return &Server{
- config: config,
- store: store,
- mesh: NewNopMeshAdapter(),
- limiter: rate.NewLimiter(rate.Limit(EnrollRateLimit), EnrollBurst),
- providers: make(map[string]*oidc.Provider),
- catalog: make(map[string]nodeCatalogEntry),
- ctx: ctx,
- cancel: cancel,
+ config: config,
+ store: store,
+ mesh: NewNopMeshAdapter(),
+ limiter: rate.NewLimiter(rate.Limit(EnrollRateLimit), EnrollBurst),
+ providers: make(map[string]*oidc.Provider),
+ catalog: make(map[string]nodeCatalogEntry),
+ metricsRegistry: reg,
+ ctx: ctx,
+ cancel: cancel,
}, nil
}
@@ -208,30 +216,35 @@ func (s *Server) Init() error {
return nil
}
-// RegisterRoutes registers every control-plane HTTP handler on mux.
+// RegisterRoutes registers every control-plane HTTP handler on mux. Probes
+// and /metrics are left uncounted so scrapers do not dominate the figures.
func (s *Server) RegisterRoutes(mux *http.ServeMux) {
mux.HandleFunc("/healthz", s.HandleHealthz)
mux.HandleFunc("/readyz", s.HandleReadyz)
- mux.Handle("/metrics", promhttp.Handler())
- mux.HandleFunc("/info", s.HandleInfo)
- mux.HandleFunc("/register", noStore(s.HandleRegister))
- mux.HandleFunc("/keys", s.HandleKeys)
- mux.HandleFunc("/routers/lease", s.HandleRouterLease)
- mux.HandleFunc("/policies", s.HandlePolicies)
- mux.HandleFunc("/enroll", noStore(s.HandleEnroll))
- mux.HandleFunc("/enroll/status", noStore(s.HandleEnrollStatus))
- mux.HandleFunc("/refresh", noStore(s.HandleRefresh))
- mux.HandleFunc("/nodes/catalog", s.HandleNodeCatalog)
- mux.HandleFunc("/admin/bootstrap-tokens", noStore(s.HandleAdminBootstrapTokens))
- mux.HandleFunc("/admin/bootstrap-tokens/", noStore(s.HandleAdminBootstrapTokenAction))
- mux.HandleFunc("/admin/enrollments", noStore(s.HandleAdminEnrollments))
- mux.HandleFunc("/admin/enrollments/", noStore(s.HandleAdminEnrollmentAction))
- mux.HandleFunc("/admin/nodes/", noStore(s.HandleAdminNodeAction))
- mux.HandleFunc("/admin/revoke", noStore(s.HandleAdminRevoke))
- mux.HandleFunc("/admin/status", noStore(s.HandleAdminStatus))
- mux.HandleFunc("/user/status", noStore(s.HandleUserStatus))
- mux.HandleFunc("/user/bootstrap-tokens", noStore(s.HandleUserBootstrapTokens))
- mux.HandleFunc("/user/revoke", noStore(s.HandleUserRevoke))
+ mux.Handle("/metrics", s.metricsHandler())
+
+ handle := func(pattern string, h http.HandlerFunc) {
+ mux.Handle(pattern, observeRoute(pattern, h))
+ }
+ handle("/info", s.HandleInfo)
+ handle("/register", noStore(s.HandleRegister))
+ handle("/keys", s.HandleKeys)
+ handle("/routers/lease", s.HandleRouterLease)
+ handle("/policies", s.HandlePolicies)
+ handle("/enroll", noStore(s.HandleEnroll))
+ handle("/enroll/status", noStore(s.HandleEnrollStatus))
+ handle("/refresh", noStore(s.HandleRefresh))
+ handle("/nodes/catalog", s.HandleNodeCatalog)
+ handle("/admin/bootstrap-tokens", noStore(s.HandleAdminBootstrapTokens))
+ handle("/admin/bootstrap-tokens/", noStore(s.HandleAdminBootstrapTokenAction))
+ handle("/admin/enrollments", noStore(s.HandleAdminEnrollments))
+ handle("/admin/enrollments/", noStore(s.HandleAdminEnrollmentAction))
+ handle("/admin/nodes/", noStore(s.HandleAdminNodeAction))
+ handle("/admin/revoke", noStore(s.HandleAdminRevoke))
+ handle("/admin/status", noStore(s.HandleAdminStatus))
+ handle("/user/status", noStore(s.HandleUserStatus))
+ handle("/user/bootstrap-tokens", noStore(s.HandleUserBootstrapTokens))
+ handle("/user/revoke", noStore(s.HandleUserRevoke))
}
// noStore marks responses that carry credentials (biscuits, bootstrap tokens,