Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions cmd/fabric-config-agent/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import (
"time"

"github.com/spf13/cobra"
instmetrics "go.miloapis.com/instrumentation/metrics"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
Expand Down Expand Up @@ -375,11 +376,10 @@ func writerLock(opts *options, metrics *fabricconfig.AgentMetrics, writer string
return fabricconfig.TimedLock{Locker: lock, Metrics: metrics, Writer: writer}
}

// newMetrics builds the registry served at /metrics, holding the next-hop
// guard's and the activation path's metrics.
// newMetrics creates the next-hop guard's and the activation path's metrics,
// which /metrics serves from the instrumentation library's registry.
func newMetrics() (*fabricconfig.NextHopMetrics, *fabricconfig.AgentMetrics) {
m := fabricconfig.NewNextHopMetrics()
return m, fabricconfig.NewAgentMetrics(m.Registry)
return fabricconfig.NewNextHopMetrics(), fabricconfig.NewAgentMetrics()
}

// watchWithGuard runs a.Watch alongside a NextHopGuard over the same FRR
Expand Down Expand Up @@ -421,7 +421,7 @@ func watchWithGuard(ctx context.Context, a *fabricconfig.Agent, opts *options) e

if opts.metricsBindAddress != "" {
mux := http.NewServeMux()
mux.Handle("/metrics", metrics.Handler())
mux.Handle("/metrics", instmetrics.Handler())
srv := &http.Server{
Addr: opts.metricsBindAddress,
Handler: mux,
Expand Down
10 changes: 7 additions & 3 deletions cmd/fabric-config-agent/scrape_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,14 @@ import (
"testing"

"go.miloapis.com/instrumentation/instrumenttest"
"go.miloapis.com/instrumentation/metrics"
)

// TestMetricsScrape scrapes the registry the agent serves at /metrics.
// TestMetricsScrape scrapes what the agent serves at /metrics, the
// instrumentation library's registry, once newMetrics has created the
// agent's series, and lints them.
func TestMetricsScrape(t *testing.T) {
m, _ := newMetrics()
instrumenttest.AssertScrapes(t, m.Handler())
newMetrics()
instrumenttest.AssertScrapes(t, metrics.Handler())
instrumenttest.Lint(t)
}
6 changes: 2 additions & 4 deletions cmd/fabric-router-controller/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,12 @@ import (
"fmt"

"github.com/spf13/cobra"
"go.miloapis.com/instrumentation/metrics"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/runtime"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/healthz"
ctrlmetrics "sigs.k8s.io/controller-runtime/pkg/metrics"
metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server"

networkv1alpha1 "go.datum.net/galactic/api/network/v1alpha1"
Expand Down Expand Up @@ -98,9 +98,7 @@ metrics on the metrics address.`,
// The leader exports the fleet's state from its cache beside
// controller-runtime's own metrics.
fleet := &routingmetrics.Collector{Reader: mgr.GetClient(), Rollout: rolloutEnabled}
if err := ctrlmetrics.Registry.Register(fleet); err != nil {
return fmt.Errorf("register fleet metrics: %w", err)
}
metrics.MustRegister(fleet)
if err := mgr.Add(fleet); err != nil {
return fmt.Errorf("add fleet metrics: %w", err)
}
Expand Down
15 changes: 12 additions & 3 deletions cmd/fabric-router-controller/scrape_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,24 @@
package main

import (
"sync"
"testing"

"go.miloapis.com/instrumentation/instrumenttest"
"go.miloapis.com/instrumentation/metrics"

routingmetrics "go.datum.net/galactic/internal/fabric/routing/metrics"
)

// TestMetricsScrape scrapes what the manager serves at /metrics:
// controller-runtime's registry, which metrics.Handler serves unchanged,
// holding every metric this command's packages register when linked.
// startup registers the collector once per test process, as run does once
// per process, so repeated runs of TestMetricsScrape share it.
var startup sync.Once

// TestMetricsScrape scrapes what the manager serves at /metrics, the
// instrumentation library's registry, with the fleet collector run
// registers. Only the leader's collector emits series, so this one, never
// started, checks that its descriptors fit beside the others.
func TestMetricsScrape(t *testing.T) {
startup.Do(func() { metrics.MustRegister(&routingmetrics.Collector{}) })
instrumenttest.AssertScrapes(t, metrics.Handler())
}
10 changes: 5 additions & 5 deletions docs/observability/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,11 @@ Create every metric with the constructors in
[`go.miloapis.com/instrumentation/metrics`](https://github.com/milo-os/instrumentation),
and register a collector that reads state at scrape time with its
`metrics.MustRegister`. Both put the metric on controller-runtime's registry,
which every controller-runtime manager serves and `galactic-cni` serves with
the library's `metrics.Handler`. `fabric-config-agent` and the fabric-api node
sidecar serve only their own registries, so a library metric linked into them
is not exported until they serve the library's handler. The tests in
`internal/instrumentation` enforce the rule in the unit suite:
which every controller-runtime manager serves and `galactic-cni` and
`fabric-config-agent` serve with the library's `metrics.Handler`. The
fabric-api node sidecar serves only its own registry, so a library metric
linked into it is not exported until it serves the library's handler. The
tests in `internal/instrumentation` enforce the rule in the unit suite:

- `TestAdopted` runs the library's adoption check, which fails on a metric
registered outside the library and on a logger the library didn't build.
Expand Down
25 changes: 16 additions & 9 deletions internal/fabricconfig/metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
"time"

"github.com/prometheus/client_golang/prometheus"
"go.miloapis.com/instrumentation/metrics"
)

// Activation outcomes the agent counts.
Expand Down Expand Up @@ -127,7 +128,7 @@ func ReadBootRecord(path string) (BootRecord, error) {
}

// AgentMetrics is the activation path's and the writer lock's
// instrumentation. Register it on the registry the watch container serves.
// instrumentation.
type AgentMetrics struct {
activations *prometheus.CounterVec
duration *prometheus.HistogramVec
Expand All @@ -136,39 +137,45 @@ type AgentMetrics struct {
boot *prometheus.GaugeVec
}

// NewAgentMetrics builds the agent's metrics and registers them on reg.
func NewAgentMetrics(reg prometheus.Registerer) *AgentMetrics {
// NewAgentMetrics creates the agent's metrics on the instrumentation
// library's registry. The registry keeps the series across calls, so each
// call starts them over.
func NewAgentMetrics() *AgentMetrics {
m := &AgentMetrics{
activations: prometheus.NewCounterVec(prometheus.CounterOpts{
activations: metrics.NewCounterVec(prometheus.CounterOpts{
Name: "fabric_router_activations_total",
Help: "Activations by outcome. committed, recovered, degraded and refused count each epoch once " +
"per agent process, so a restarted agent may count an epoch it meets again; error counts every " +
"failed attempt.",
}, []string{"outcome"}),
duration: prometheus.NewHistogramVec(prometheus.HistogramOpts{
duration: metrics.NewHistogramVec(prometheus.HistogramOpts{
Name: "fabric_router_activation_duration_seconds",
Help: "Time the agent took to commit, recover or degrade an activation, its stabilization window " +
"included.",
Buckets: []float64{1, 5, 10, 30, 60, 120, 300, 600, 1200, 1800, 3600},
}, []string{"outcome"}),
staging: prometheus.NewCounterVec(prometheus.CounterOpts{
staging: metrics.NewCounterVec(prometheus.CounterOpts{
Name: "fabric_router_staging_runs_total",
Help: "Candidate revisions the agent validated and diffed without applying, by result: staged, " +
"rejected or revision_not_found.",
}, []string{"result"}),
lockWait: prometheus.NewHistogramVec(prometheus.HistogramOpts{
lockWait: metrics.NewHistogramVec(prometheus.HistogramOpts{
Name: "fabric_router_writer_lock_wait_seconds",
Help: "Time each FRR writer waited for the node's writer lock, by result: acquired, timeout or " +
"error. The lock is retried every 100ms.",
Buckets: []float64{.1, .5, 1, 5, 10, 30, 60, 120, 300, 900},
}, []string{"writer", "result"}),
boot: prometheus.NewGaugeVec(prometheus.GaugeOpts{
boot: metrics.NewGaugeVec(prometheus.GaugeOpts{
Name: "fabric_router_boot_source",
Help: "1 for where the pod's init container took the configuration FRR started with: configmap, " +
"checkpoint_offline, checkpoint_online or active_revision.",
}, []string{"source"}),
}
reg.MustRegister(m.activations, m.duration, m.staging, m.lockWait, m.boot)
m.activations.Reset()
m.duration.Reset()
m.staging.Reset()
m.lockWait.Reset()
m.boot.Reset()
return m
}

Expand Down
13 changes: 7 additions & 6 deletions internal/fabricconfig/metrics_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ func activations(m *AgentMetrics, outcome string) float64 {
// often the agent sees the epoch again.
func TestAgentMetricsActivations(t *testing.T) {
h := newHarness(t, deployment(networkv1alpha1.FabricConfigSourceCRD))
m := NewAgentMetrics(prometheus.NewRegistry())
m := NewAgentMetrics()
h.agent.Metrics = m
if err := h.client.Create(context.Background(), release(h.revs[0], h.revs[1])); err != nil {
t.Fatal(err)
Expand Down Expand Up @@ -121,7 +121,7 @@ func TestErrorOutcome(t *testing.T) {
// validates a candidate, not each sync that finds it already staged.
func TestAgentMetricsStaging(t *testing.T) {
h := newHarness(t, deployment(networkv1alpha1.FabricConfigSourceShadow))
m := NewAgentMetrics(prometheus.NewRegistry())
m := NewAgentMetrics()
h.agent.Metrics = m
h.frr.running = rendered(t, h.revs[0])
h.update(func(d *networkv1alpha1.FabricRouterDeployment) {
Expand Down Expand Up @@ -157,8 +157,9 @@ func (l slowLock) Lock(context.Context) (func(), error) {
// TestTimedLock observes every wait under its writer and how it ended:
// acquired, ended by its deadline, or failed otherwise.
func TestTimedLock(t *testing.T) {
reg := prometheus.NewRegistry()
m := NewAgentMetrics(reg)
m := NewAgentMetrics()
reg := prometheus.NewPedanticRegistry()
reg.MustRegister(m.lockWait)
for _, l := range []struct {
writer string
err error
Expand Down Expand Up @@ -207,7 +208,7 @@ func TestTimedLock(t *testing.T) {
// TestActivationCounterOnce counts a finished or refused epoch once per
// process, and every failed attempt.
func TestActivationCounterOnce(t *testing.T) {
m := NewAgentMetrics(prometheus.NewRegistry())
m := NewAgentMetrics()
d := &DeploymentAgent{Metrics: m}
for range 3 {
d.count("uid", 1, OutcomeRefused, 0)
Expand Down Expand Up @@ -250,7 +251,7 @@ func TestBootRecord(t *testing.T) {
t.Errorf("ClearBootRecord of nothing = %v", err)
}

m := NewAgentMetrics(prometheus.NewRegistry())
m := NewAgentMetrics()
m.SetBoot(BootConfigMap)
m.SetBoot(got.Source)
if n := testutil.CollectAndCount(m.boot); n != 1 {
Expand Down
28 changes: 11 additions & 17 deletions internal/fabricconfig/nexthop.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,12 @@ import (
"encoding/json"
"fmt"
"log/slog"
"net/http"
"net/netip"
"sort"
"time"

"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"go.miloapis.com/instrumentation/metrics"
corev1 "k8s.io/api/core/v1"
"k8s.io/client-go/tools/events"
)
Expand Down Expand Up @@ -49,43 +48,38 @@ type BGP interface {
ResetNeighbor(ctx context.Context, neighbor string) error
}

// NextHopMetrics holds NextHopGuard's Prometheus instrumentation in a private
// registry.
// NextHopMetrics holds NextHopGuard's Prometheus instrumentation.
type NextHopMetrics struct {
Registry *prometheus.Registry

mapped *prometheus.GaugeVec
resets *prometheus.CounterVec
uninstalled *prometheus.GaugeVec
}

// NewNextHopMetrics builds a NextHopMetrics with every metric registered.
// NewNextHopMetrics creates NextHopMetrics on the instrumentation library's
// registry. The registry keeps the series across calls, so each call starts
// them over.
func NewNextHopMetrics() *NextHopMetrics {
m := &NextHopMetrics{
Registry: prometheus.NewRegistry(),
mapped: prometheus.NewGaugeVec(prometheus.GaugeOpts{
mapped: metrics.NewGaugeVec(prometheus.GaugeOpts{
Name: "fabric_router_bgp_mapped_nexthop",
Help: "1 when an established session sourced from a global IPv6 address announces an IPv4-mapped " +
"next hop, 0 when it announces a usable one.",
}, []string{"peer"}),
resets: prometheus.NewCounterVec(prometheus.CounterOpts{
resets: metrics.NewCounterVec(prometheus.CounterOpts{
Name: "fabric_router_bgp_mapped_nexthop_resets_total",
Help: "Hard resets of sessions that announced an IPv4-mapped next hop.",
}, []string{"peer"}),
uninstalled: prometheus.NewGaugeVec(prometheus.GaugeOpts{
uninstalled: metrics.NewGaugeVec(prometheus.GaugeOpts{
Name: "fabric_router_bgp_uninstalled_routes",
Help: "Prefixes with a BGP route in zebra and no route of any protocol installed in the kernel.",
}, []string{"afi"}),
}
m.Registry.MustRegister(m.mapped, m.resets, m.uninstalled)
m.mapped.Reset()
m.resets.Reset()
m.uninstalled.Reset()
return m
}

// Handler returns the http.Handler serving the registry.
func (m *NextHopMetrics) Handler() http.Handler {
return promhttp.HandlerFor(m.Registry, promhttp.HandlerOpts{})
}

// NextHopGuard finds IPv6 sessions announcing an IPv4-mapped next hop and
// hard-resets them, and counts BGP routes zebra failed to install.
//
Expand Down
2 changes: 0 additions & 2 deletions internal/instrumentation/adoption_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,10 @@ const moduleRoot = "../.."
var pending = []string{
// #1149: serve controller-runtime's registry through library metrics.
"cmd/fabric-api",
"cmd/fabric-router-controller",
// #1149: create metrics with the library's constructors instead of a
// registry parameter or a private registry.
"internal/fabric/gateway",
"internal/fabric/node",
"internal/fabricconfig",
}

// TestAdopted runs the instrumentation library's adoption check over the
Expand Down
1 change: 1 addition & 0 deletions internal/instrumentation/lint_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (
// Every package that creates a metric through the library, so Lint sees
// it. TestLintLinksEveryMetric keeps this list complete.
_ "go.datum.net/galactic/internal/edge/diag"
_ "go.datum.net/galactic/internal/fabricconfig"
_ "go.datum.net/galactic/internal/gateway"
_ "go.datum.net/galactic/internal/ingresssidecar"
_ "go.datum.net/galactic/internal/plumbing/ebpf/metrics"
Expand Down
Loading