From f341463f827dcf296ad7f3b0baeefb6d63bf80ca Mon Sep 17 00:00:00 2001 From: Peter Sprygada Date: Wed, 28 Oct 2026 07:22:16 -0400 Subject: [PATCH] test: Enforce the instrumentation library in the unit suite Nothing in CI stopped new code from creating metrics or loggers outside go.miloapis.com/instrumentation, so the migration could regress while it is under way. A new internal/instrumentation package runs the library's checks over the module: - TestAdopted runs instrumenttest.AssertAdopted. It skips the directories in pending, which have not moved yet. Each one names the issue that removes it. - TestNoMetricsOutsideLibrary fails on prometheus metric constructors, NewRegistry, Registerer and Registry outside pending. The library's check only sees registration through package-level functions, so a metric registered on a Registerer parameter, the pattern most of Galactic uses, would otherwise pass. - TestMetricsLint runs instrumenttest.Lint over the packages it imports, and TestLintLinksEveryMetric fails when a package that creates a library metric is missing from that list. - Every command that serves /metrics gets a TestMetricsScrape, and TestEveryBinaryHasScrapeTest requires one for each new command. Lint fails when no library metric is linked, so the route-install gauge in internal/runtime/gobgp moves to metrics.NewGaugeVec. Its name, labels and registry are unchanged. galactic-router now also serves instrumentation_build_info. The CNI daemon and fabric-config-agent each build their private registry in a small function that the binary and its scrape test both call. TestLoggerAdopted in internal/logging is removed, because TestAdopted runs the same logger check. Fixes #1148 Co-Authored-By: Claude Opus 5.5 --- cmd/fabric-api/scrape_test.go | 26 +++ cmd/fabric-config-agent/main.go | 10 +- cmd/fabric-config-agent/scrape_test.go | 17 ++ cmd/fabric-router-controller/scrape_test.go | 19 ++ cmd/galactic-cni/scrape_test.go | 18 ++ cmd/galactic-controller/scrape_test.go | 19 ++ cmd/galactic-edge/scrape_test.go | 19 ++ cmd/galactic-gateway/scrape_test.go | 19 ++ cmd/galactic-nat/scrape_test.go | 19 ++ cmd/galactic-router/scrape_test.go | 19 ++ cmd/galactic-vrf/scrape_test.go | 19 ++ docs/observability/README.md | 30 +++ docs/observability/logging.md | 6 +- internal/installer/installer.go | 11 +- internal/instrumentation/adoption_test.go | 218 ++++++++++++++++++++ internal/instrumentation/doc.go | 9 + internal/instrumentation/lint_test.go | 125 +++++++++++ internal/logging/logging_test.go | 8 - internal/runtime/gobgp/vrfroutes.go | 8 +- 19 files changed, 598 insertions(+), 21 deletions(-) create mode 100644 cmd/fabric-api/scrape_test.go create mode 100644 cmd/fabric-config-agent/scrape_test.go create mode 100644 cmd/fabric-router-controller/scrape_test.go create mode 100644 cmd/galactic-cni/scrape_test.go create mode 100644 cmd/galactic-controller/scrape_test.go create mode 100644 cmd/galactic-edge/scrape_test.go create mode 100644 cmd/galactic-gateway/scrape_test.go create mode 100644 cmd/galactic-nat/scrape_test.go create mode 100644 cmd/galactic-router/scrape_test.go create mode 100644 cmd/galactic-vrf/scrape_test.go create mode 100644 internal/instrumentation/adoption_test.go create mode 100644 internal/instrumentation/doc.go create mode 100644 internal/instrumentation/lint_test.go diff --git a/cmd/fabric-api/scrape_test.go b/cmd/fabric-api/scrape_test.go new file mode 100644 index 000000000..f367ef1bf --- /dev/null +++ b/cmd/fabric-api/scrape_test.go @@ -0,0 +1,26 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package main + +import ( + "testing" + + "go.miloapis.com/instrumentation/instrumenttest" + "go.miloapis.com/instrumentation/metrics" + + "go.datum.net/galactic/internal/fabric/node" +) + +// TestMetricsScrape scrapes both roles' /metrics: the gateway's manager +// serves controller-runtime's registry, which metrics.Handler serves +// unchanged, and the node sidecar serves its own registry. +func TestMetricsScrape(t *testing.T) { + t.Run("gateway", func(t *testing.T) { + instrumenttest.AssertScrapes(t, metrics.Handler()) + }) + t.Run("node", func(t *testing.T) { + instrumenttest.AssertScrapes(t, node.NewMetrics().Handler()) + }) +} diff --git a/cmd/fabric-config-agent/main.go b/cmd/fabric-config-agent/main.go index 098088aab..cf07e855d 100644 --- a/cmd/fabric-config-agent/main.go +++ b/cmd/fabric-config-agent/main.go @@ -375,14 +375,20 @@ 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. +func newMetrics() (*fabricconfig.NextHopMetrics, *fabricconfig.AgentMetrics) { + m := fabricconfig.NewNextHopMetrics() + return m, fabricconfig.NewAgentMetrics(m.Registry) +} + // watchWithGuard runs a.Watch alongside a NextHopGuard over the same FRR // instance, and serves the guard's and the activation path's metrics, and // the boot source init recorded, when opts asks for them. With the // ConfigMap path retired it runs only the deployment agent and the guard // until ctx ends. func watchWithGuard(ctx context.Context, a *fabricconfig.Agent, opts *options) error { - metrics := fabricconfig.NewNextHopMetrics() - agentMetrics := fabricconfig.NewAgentMetrics(metrics.Registry) + metrics, agentMetrics := newMetrics() if rec, err := fabricconfig.ReadBootRecord(opts.bootRecord); err == nil { agentMetrics.SetBoot(rec.Source) } else { diff --git a/cmd/fabric-config-agent/scrape_test.go b/cmd/fabric-config-agent/scrape_test.go new file mode 100644 index 000000000..c6cb3c1bf --- /dev/null +++ b/cmd/fabric-config-agent/scrape_test.go @@ -0,0 +1,17 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package main + +import ( + "testing" + + "go.miloapis.com/instrumentation/instrumenttest" +) + +// TestMetricsScrape scrapes the registry the agent serves at /metrics. +func TestMetricsScrape(t *testing.T) { + m, _ := newMetrics() + instrumenttest.AssertScrapes(t, m.Handler()) +} diff --git a/cmd/fabric-router-controller/scrape_test.go b/cmd/fabric-router-controller/scrape_test.go new file mode 100644 index 000000000..557990fa6 --- /dev/null +++ b/cmd/fabric-router-controller/scrape_test.go @@ -0,0 +1,19 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package main + +import ( + "testing" + + "go.miloapis.com/instrumentation/instrumenttest" + "go.miloapis.com/instrumentation/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. +func TestMetricsScrape(t *testing.T) { + instrumenttest.AssertScrapes(t, metrics.Handler()) +} diff --git a/cmd/galactic-cni/scrape_test.go b/cmd/galactic-cni/scrape_test.go new file mode 100644 index 000000000..bcb009d60 --- /dev/null +++ b/cmd/galactic-cni/scrape_test.go @@ -0,0 +1,18 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package main + +import ( + "testing" + + "go.miloapis.com/instrumentation/instrumenttest" + + "go.datum.net/galactic/internal/installer" +) + +// TestMetricsScrape scrapes the registry the run daemon serves at /metrics. +func TestMetricsScrape(t *testing.T) { + instrumenttest.AssertScrapes(t, installer.NewMetrics().Handler()) +} diff --git a/cmd/galactic-controller/scrape_test.go b/cmd/galactic-controller/scrape_test.go new file mode 100644 index 000000000..557990fa6 --- /dev/null +++ b/cmd/galactic-controller/scrape_test.go @@ -0,0 +1,19 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package main + +import ( + "testing" + + "go.miloapis.com/instrumentation/instrumenttest" + "go.miloapis.com/instrumentation/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. +func TestMetricsScrape(t *testing.T) { + instrumenttest.AssertScrapes(t, metrics.Handler()) +} diff --git a/cmd/galactic-edge/scrape_test.go b/cmd/galactic-edge/scrape_test.go new file mode 100644 index 000000000..557990fa6 --- /dev/null +++ b/cmd/galactic-edge/scrape_test.go @@ -0,0 +1,19 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package main + +import ( + "testing" + + "go.miloapis.com/instrumentation/instrumenttest" + "go.miloapis.com/instrumentation/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. +func TestMetricsScrape(t *testing.T) { + instrumenttest.AssertScrapes(t, metrics.Handler()) +} diff --git a/cmd/galactic-gateway/scrape_test.go b/cmd/galactic-gateway/scrape_test.go new file mode 100644 index 000000000..557990fa6 --- /dev/null +++ b/cmd/galactic-gateway/scrape_test.go @@ -0,0 +1,19 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package main + +import ( + "testing" + + "go.miloapis.com/instrumentation/instrumenttest" + "go.miloapis.com/instrumentation/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. +func TestMetricsScrape(t *testing.T) { + instrumenttest.AssertScrapes(t, metrics.Handler()) +} diff --git a/cmd/galactic-nat/scrape_test.go b/cmd/galactic-nat/scrape_test.go new file mode 100644 index 000000000..557990fa6 --- /dev/null +++ b/cmd/galactic-nat/scrape_test.go @@ -0,0 +1,19 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package main + +import ( + "testing" + + "go.miloapis.com/instrumentation/instrumenttest" + "go.miloapis.com/instrumentation/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. +func TestMetricsScrape(t *testing.T) { + instrumenttest.AssertScrapes(t, metrics.Handler()) +} diff --git a/cmd/galactic-router/scrape_test.go b/cmd/galactic-router/scrape_test.go new file mode 100644 index 000000000..557990fa6 --- /dev/null +++ b/cmd/galactic-router/scrape_test.go @@ -0,0 +1,19 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package main + +import ( + "testing" + + "go.miloapis.com/instrumentation/instrumenttest" + "go.miloapis.com/instrumentation/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. +func TestMetricsScrape(t *testing.T) { + instrumenttest.AssertScrapes(t, metrics.Handler()) +} diff --git a/cmd/galactic-vrf/scrape_test.go b/cmd/galactic-vrf/scrape_test.go new file mode 100644 index 000000000..557990fa6 --- /dev/null +++ b/cmd/galactic-vrf/scrape_test.go @@ -0,0 +1,19 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package main + +import ( + "testing" + + "go.miloapis.com/instrumentation/instrumenttest" + "go.miloapis.com/instrumentation/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. +func TestMetricsScrape(t *testing.T) { + instrumenttest.AssertScrapes(t, metrics.Handler()) +} diff --git a/docs/observability/README.md b/docs/observability/README.md index 7abe72ac1..ddb49435c 100644 --- a/docs/observability/README.md +++ b/docs/observability/README.md @@ -15,6 +15,36 @@ Metrics, scrape configuration, shipped alert rules and log format. Use the subsy - [Shipped alerts](alerts.md) - [Logging](logging.md) +## Adding a metric + +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. `galactic-cni`, +`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: + +- `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. +- `TestNoMetricsOutsideLibrary` fails on any metric constructor or registry + from `client_golang`'s `prometheus` package, including one passed in as a + `prometheus.Registerer`. +- `TestMetricsLint` checks every library metric's name against Prometheus + conventions. It imports each package that defines one, and + `TestLintLinksEveryMetric` fails when a package is missing from that list + or defines its metrics in a command's `main` package. +- Each command that serves `/metrics` has a `TestMetricsScrape`, which fails + when two registries export the same series. `TestEveryBinaryHasScrapeTest` + requires one for every new command, but can't tell whether the test scrapes + the handler the command serves; reviewers check that. + +Both source checks skip the directories in `pending` in +`internal/instrumentation/adoption_test.go`, which haven't moved to the +library yet. + ## Where the metrics come from The dataplane and fabric-router DaemonSets use `hostNetwork: true`, so diff --git a/docs/observability/logging.md b/docs/observability/logging.md index 5bbfa1a60..6b83e9efc 100644 --- a/docs/observability/logging.md +++ b/docs/observability/logging.md @@ -85,9 +85,9 @@ text. For local runs, `--zap-devel --log-level=debug` gives console output with the verbose lines. No binary turns on development mode itself: -`internal/logging`'s `TestLoggerAdopted` runs the instrumentation library's -logger check over the whole module, which fails on any logger not built by the -library and on development mode turned on in source. +`internal/instrumentation`'s `TestAdopted` runs the instrumentation library's +adoption check over the whole module, which fails on any logger not built by +the library and on development mode turned on in source. `TestBinariesUseThisPackage` fails when a command under `cmd/` imports controller-runtime's zap package or calls `SetLogger` itself, and `TestLongRunningBinariesInstallTheHandler` fails when a command under `cmd/` diff --git a/internal/installer/installer.go b/internal/installer/installer.go index c7dbb8348..03944cee3 100644 --- a/internal/installer/installer.go +++ b/internal/installer/installer.go @@ -1075,6 +1075,14 @@ func radvActorFailed(actors *radvActorSet, failure radvActorFailure) { "err", failure.err, "hostInterface", failure.iface, "failures", p.failures, "retryIn", backoff) } +// NewMetrics builds the registry the run daemon serves at /metrics, before +// the datapath collectors that need loaded eBPF objects are added. +func NewMetrics() *metrics.Metrics { + m := metrics.New() + nldump.MustRegister(m.Registry) + return m +} + // Run executes the CNI installer main container tasks: // 1. Loads, pins, and attaches the eBPF uSID datapath and keeps its attachment // set re-evaluated against netlink events for the life of ctx. This is the @@ -1109,8 +1117,7 @@ func radvActorFailed(actors *radvActorSet, failure radvActorFailure) { func Run(ctx context.Context, grpcHealthPort, metricsPort int) error { slog.Info("Starting CNI installer run daemon", "grpcHealthPort", grpcHealthPort, "metricsPort", metricsPort) - m := metrics.New() - nldump.MustRegister(m.Registry) + m := NewMetrics() ebpfState, datapath, err := startEBPFDatapath(ctx, m) if err != nil { diff --git a/internal/instrumentation/adoption_test.go b/internal/instrumentation/adoption_test.go new file mode 100644 index 000000000..51f20f59f --- /dev/null +++ b/internal/instrumentation/adoption_test.go @@ -0,0 +1,218 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package instrumentation + +import ( + "go/ast" + "go/build/constraint" + "go/parser" + "go/token" + "io/fs" + "os" + "path/filepath" + "slices" + "strconv" + "strings" + "testing" + + "go.miloapis.com/instrumentation/instrumenttest" +) + +// moduleRoot is the repository root, relative to this package. +const moduleRoot = "../.." + +// pending lists the directories, relative to the module root, that still +// create or register metrics outside the instrumentation library. Both +// adoption checks skip them. Remove a directory once it has moved; the +// checks then fail on anything left behind. +var pending = []string{ + // #1149: serve controller-runtime's registry through library metrics. + "cmd/fabric-api", + "cmd/fabric-router-controller", + "cmd/galactic-controller", + "cmd/galactic-edge", + "cmd/galactic-gateway", + "cmd/galactic-nat", + "cmd/galactic-router", + "cmd/galactic-vrf", + // #1149: create metrics with the library's constructors instead of a + // registry parameter or a private registry. + "internal/edge/diag", + "internal/fabric/gateway", + "internal/fabric/node", + "internal/fabricconfig", + "internal/gateway", + "internal/ingresssidecar", + "internal/plumbing/ebpf/metrics", + "internal/plumbing/ebpf/xdpdispatch", + "internal/plumbing/nldump", + "internal/serviceroute", + // #1149: its manager disables metrics, which passes once any binary + // serves the library's handler. + "tests/psc/fixture", +} + +// TestAdopted runs the instrumentation library's adoption check over the +// module: nothing registers a metric outside the library, and every logger +// is built by it. +func TestAdopted(t *testing.T) { + instrumenttest.AssertAdopted(t, instrumenttest.SkipDir(pending...)) +} + +const promPath = "github.com/prometheus/client_golang/prometheus" + +// outsideLibrary names the prometheus identifiers that create a metric or +// a registry to register one on. The library's check only sees registration +// through package-level functions, so a metric built with these and +// registered on a prometheus.Registerer parameter would pass it. Custom +// collectors remain allowed: prometheus.NewDesc is not listed, and the only +// registry left to register them on is the library's. +var outsideLibrary = []string{ + "NewCounter", "NewCounterVec", "NewCounterFunc", + "NewGauge", "NewGaugeVec", "NewGaugeFunc", + "NewHistogram", "NewHistogramVec", + "NewSummary", "NewSummaryVec", + "NewUntypedFunc", + "NewRegistry", "NewPedanticRegistry", + "Registerer", "Registry", + "WrapRegistererWith", "WrapRegistererWithPrefix", +} + +// TestNoMetricsOutsideLibrary fails wherever the module's non-test source +// outside pending creates a metric or a registry with prometheus directly. +func TestNoMetricsOutsideLibrary(t *testing.T) { + skip := map[string]bool{} + for _, d := range pending { + if _, err := os.Stat(filepath.Join(moduleRoot, d)); err != nil { + t.Errorf("pending directory %s: %v", d, err) + } + skip[d] = true + } + fset := token.NewFileSet() + walkSource(t, func(rel string, f *ast.File) { + if skip[filepath.ToSlash(filepath.Dir(rel))] || underAny(rel, skip) { + return + } + for _, imp := range f.Imports { + if p, _ := strconv.Unquote(imp.Path.Value); p == promPath && imp.Name != nil && imp.Name.Name == "." { + t.Errorf("%s:%d: dot import of %s hides its constructors from this check", + rel, fset.Position(imp.Pos()).Line, promPath) + } + } + for _, sel := range selectors(f, promPath) { + if slices.Contains(outsideLibrary, sel.Sel.Name) { + t.Errorf("%s:%d: prometheus.%s creates a metric or registry outside %s; "+ + "use its constructors, or metrics.MustRegister for a custom collector", + rel, fset.Position(sel.Pos()).Line, sel.Sel.Name, metricsPath) + } + } + }, fset) +} + +// underAny reports whether rel lies under one of dirs. +func underAny(rel string, dirs map[string]bool) bool { + rel = filepath.ToSlash(rel) + for d := range dirs { + if strings.HasPrefix(rel, d+"/") { + return true + } + } + return false +} + +// walkSource parses every non-test Go file in the module, skipping nested +// modules, testdata, hidden directories and files built only with the ignore +// tag, and passes each to fn with its path relative to the module root. +func walkSource(t *testing.T, fn func(rel string, f *ast.File), fset *token.FileSet) { + t.Helper() + err := filepath.WalkDir(moduleRoot, func(path string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + if d.IsDir() { + if path == moduleRoot { + return nil + } + name := d.Name() + // Hidden directories include .worktrees, which holds other + // checkouts of this module. + if strings.HasPrefix(name, ".") || name == "testdata" || name == "vendor" { + return filepath.SkipDir + } + if _, err := os.Stat(filepath.Join(path, "go.mod")); err == nil { + return filepath.SkipDir + } + return nil + } + if !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") { + return nil + } + f, err := parser.ParseFile(fset, path, nil, parser.ParseComments|parser.SkipObjectResolution) + if err != nil { + return err + } + if ignored(f) { + return nil + } + rel, err := filepath.Rel(moduleRoot, path) + if err != nil { + return err + } + fn(rel, f) + return nil + }) + if err != nil { + t.Fatal(err) + } +} + +// ignored reports whether f is built only with the ignore tag. +func ignored(f *ast.File) bool { + for _, g := range f.Comments { + if g.Pos() >= f.Package { + break + } + for _, c := range g.List { + if !constraint.IsGoBuild(c.Text) { + continue + } + expr, err := constraint.Parse(c.Text) + if err == nil && !expr.Eval(func(tag string) bool { return tag != "ignore" }) { + return true + } + } + } + return false +} + +// selectors returns every pkg.Name expression in f where pkg is the name f +// imports path under. +func selectors(f *ast.File, path string) []*ast.SelectorExpr { + var names []string + for _, imp := range f.Imports { + if p, _ := strconv.Unquote(imp.Path.Value); p != path { + continue + } + switch { + case imp.Name == nil: + names = append(names, path[strings.LastIndex(path, "/")+1:]) + case imp.Name.Name != "_" && imp.Name.Name != ".": + names = append(names, imp.Name.Name) + } + } + if len(names) == 0 { + return nil + } + var out []*ast.SelectorExpr + ast.Inspect(f, func(n ast.Node) bool { + if sel, ok := n.(*ast.SelectorExpr); ok { + if id, ok := sel.X.(*ast.Ident); ok && slices.Contains(names, id.Name) { + out = append(out, sel) + } + } + return true + }) + return out +} diff --git a/internal/instrumentation/doc.go b/internal/instrumentation/doc.go new file mode 100644 index 000000000..f37a12d10 --- /dev/null +++ b/internal/instrumentation/doc.go @@ -0,0 +1,9 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +// Package instrumentation holds the module-wide checks that every metric and +// logger goes through go.miloapis.com/instrumentation. It has no code of its +// own; its tests read the module's source and link every package that +// defines a metric through the library. +package instrumentation diff --git a/internal/instrumentation/lint_test.go b/internal/instrumentation/lint_test.go new file mode 100644 index 000000000..6251cfb7b --- /dev/null +++ b/internal/instrumentation/lint_test.go @@ -0,0 +1,125 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package instrumentation + +import ( + "go/ast" + "go/parser" + "go/token" + "os" + "path" + "path/filepath" + "slices" + "strconv" + "strings" + "testing" + + "go.miloapis.com/instrumentation/instrumenttest" + + // Every package that creates a metric through the library, so Lint sees + // it. TestLintLinksEveryMetric keeps this list complete. + _ "go.datum.net/galactic/internal/runtime/gobgp" +) + +const ( + modulePath = "go.datum.net/galactic" + metricsPath = "go.miloapis.com/instrumentation/metrics" +) + +// TestMetricsLint checks every metric created through the library against +// Prometheus naming conventions. +func TestMetricsLint(t *testing.T) { + instrumenttest.Lint(t) +} + +// TestLintLinksEveryMetric fails when a package creates a metric through the +// library but this package doesn't import it, so Lint would never see the +// metric. A command's own metrics can't be linked from here, so they belong +// in a package the command imports. +func TestLintLinksEveryMetric(t *testing.T) { + linked := blankImports(t, "lint_test.go") + fset := token.NewFileSet() + walkSource(t, func(rel string, f *ast.File) { + creates := slices.ContainsFunc(selectors(f, metricsPath), func(sel *ast.SelectorExpr) bool { + return strings.HasPrefix(sel.Sel.Name, "New") || sel.Sel.Name == "MustRegister" + }) + if !creates { + return + } + pkg := path.Join(modulePath, filepath.ToSlash(filepath.Dir(rel))) + switch { + case f.Name.Name == "main": + t.Errorf("%s creates a metric in package main, which Lint can't link; move it to a package the command imports", rel) + case !linked[pkg]: + t.Errorf("%s creates a metric, but lint_test.go doesn't import %s", rel, pkg) + } + }, fset) +} + +// noMetricsEndpoint lists the commands that serve no metrics: the CNI +// plugins, exec'd once per call by the container runtime, and the one-shot +// galactic-usid codec. +var noMetricsEndpoint = []string{ + "galactic-bgp", + "galactic-ipam", + "galactic-route", + "galactic-tap", + "galactic-usid", + "galactic-veth", +} + +// TestEveryBinaryHasScrapeTest fails when a command that serves metrics has +// no test calling instrumenttest.AssertScrapes on its handler, which is +// where a series exported by two registries shows up. +func TestEveryBinaryHasScrapeTest(t *testing.T) { + root := filepath.Join(moduleRoot, "cmd") + dirs, err := os.ReadDir(root) + if err != nil { + t.Fatal(err) + } + fset := token.NewFileSet() + for _, d := range dirs { + if !d.IsDir() { + continue + } + tests, err := filepath.Glob(filepath.Join(root, d.Name(), "*_test.go")) + if err != nil { + t.Fatal(err) + } + scrapes := false + for _, file := range tests { + f, err := parser.ParseFile(fset, file, nil, parser.SkipObjectResolution) + if err != nil { + t.Fatal(err) + } + scrapes = scrapes || slices.ContainsFunc(selectors(f, "go.miloapis.com/instrumentation/instrumenttest"), + func(sel *ast.SelectorExpr) bool { return sel.Sel.Name == "AssertScrapes" }) + } + exempt := slices.Contains(noMetricsEndpoint, d.Name()) + switch { + case scrapes && exempt: + t.Errorf("cmd/%s has a scrape test; remove it from noMetricsEndpoint", d.Name()) + case !scrapes && !exempt: + t.Errorf("cmd/%s has no test calling instrumenttest.AssertScrapes on the handler it serves at /metrics", d.Name()) + } + } +} + +// blankImports returns the import paths file, in this package, imports as _. +func blankImports(t *testing.T, file string) map[string]bool { + t.Helper() + f, err := parser.ParseFile(token.NewFileSet(), file, nil, parser.ImportsOnly) + if err != nil { + t.Fatal(err) + } + out := map[string]bool{} + for _, imp := range f.Imports { + if imp.Name != nil && imp.Name.Name == "_" { + p, _ := strconv.Unquote(imp.Path.Value) + out[p] = true + } + } + return out +} diff --git a/internal/logging/logging_test.go b/internal/logging/logging_test.go index 2b9bf271f..14740b758 100644 --- a/internal/logging/logging_test.go +++ b/internal/logging/logging_test.go @@ -26,7 +26,6 @@ import ( "time" "github.com/spf13/pflag" - "go.miloapis.com/instrumentation/instrumenttest" "k8s.io/klog/v2" ctrl "sigs.k8s.io/controller-runtime" @@ -232,13 +231,6 @@ func TestValidateLevel(t *testing.T) { } } -// TestLoggerAdopted runs the instrumentation library's logger check over the -// whole module: every logger is built by its logging package, and nothing -// turns on development mode. -func TestLoggerAdopted(t *testing.T) { - instrumenttest.AssertStandardLogger(t) -} - // TestBinariesListsEveryCaller keeps Binaries, which the manifest check uses // to find Galactic containers, in step with the commands that import this // package. diff --git a/internal/runtime/gobgp/vrfroutes.go b/internal/runtime/gobgp/vrfroutes.go index e9a5fbc0c..07664a73a 100644 --- a/internal/runtime/gobgp/vrfroutes.go +++ b/internal/runtime/gobgp/vrfroutes.go @@ -14,7 +14,7 @@ import ( "time" "github.com/prometheus/client_golang/prometheus" - ctrlmetrics "sigs.k8s.io/controller-runtime/pkg/metrics" + "go.miloapis.com/instrumentation/metrics" "go.datum.net/galactic/internal/plumbing/srv6" ) @@ -44,15 +44,11 @@ const labelRouter = "router" // routes in a VRF's egress_route_table and "plain" for routes with no route // target. A value that stays above zero means part of a VPC, or an egress shard // or VIP, is unreachable from this node. -var routeInstallFailing = prometheus.NewGaugeVec(prometheus.GaugeOpts{ +var routeInstallFailing = metrics.NewGaugeVec(prometheus.GaugeOpts{ Name: "galactic_router_route_install_failing", Help: "Routes whose best path is known but whose last install into the kernel or datapath failed.", }, []string{labelRouter, "kind"}) -func init() { - ctrlmetrics.Registry.MustRegister(routeInstallFailing) -} - // installFailingReporter returns a report func setting router's // routeInstallFailing gauge for kind. func installFailingReporter(router, kind string) func(int) {