From 24a328f765346cae434cbe4bc851c870d04468a6 Mon Sep 17 00:00:00 2001 From: Peter Sprygada Date: Tue, 27 Oct 2026 10:02:40 -0400 Subject: [PATCH] feat: Count interrupted netlink listings A netlink listing of links, addresses or routes that another process interrupts is retried up to 50 times before it fails, and nothing recorded the retries. Sustained churn on a node stayed invisible until it exhausted them and a component failed. nldump now runs every attempt itself instead of leaving the first ten of each round to the netlink library's hidden retry, so it sees each interruption. The bound is unchanged: five rounds of ten back-to-back attempts, with 20, 40, 60 and 80 ms pauses between rounds. Two counters, labelled by listing kind, record what happens: - galactic_netlink_dump_interrupted_total counts every attempt the kernel interrupted. - galactic_netlink_dump_failures_total counts listings still interrupted on their last attempt. Every long-running binary that reaches nldump registers them on its metrics port: galactic-cni's daemon, galactic-router, galactic-vrf, galactic-gateway, galactic-nat and galactic-edge. The CNI plugins run once per attach and expose no metrics. Retries log nothing, so normal churn adds no log lines. docs/observability/netlink.md documents the counters, the port and scrape job of each component that exposes them, and example queries. A listing that exhausts its retries now reports the real attempt count in its error, since netlink's own message counts only the handle's single try. Resolves #1134 --- cmd/galactic-edge/main.go | 2 + cmd/galactic-gateway/root.go | 2 + cmd/galactic-nat/root.go | 2 + cmd/galactic-router/root.go | 2 + cmd/galactic-vrf/root.go | 2 + docs/observability/README.md | 1 + docs/observability/netlink.md | 45 +++++++ internal/installer/installer.go | 2 + .../plumbing/nldump/churn_internal_test.go | 101 +++++++++++++++ internal/plumbing/nldump/nldump.go | 99 +++++++++++---- .../plumbing/nldump/nldump_internal_test.go | 119 ++++++++++++++---- 11 files changed, 329 insertions(+), 48 deletions(-) create mode 100644 docs/observability/netlink.md create mode 100644 internal/plumbing/nldump/churn_internal_test.go diff --git a/cmd/galactic-edge/main.go b/cmd/galactic-edge/main.go index 76fb85b71..501f52c45 100644 --- a/cmd/galactic-edge/main.go +++ b/cmd/galactic-edge/main.go @@ -45,6 +45,7 @@ import ( "go.datum.net/galactic/internal/edge/timing" "go.datum.net/galactic/internal/metadata" "go.datum.net/galactic/internal/plumbing/ebpf/attach" + "go.datum.net/galactic/internal/plumbing/nldump" ) type options struct { @@ -173,6 +174,7 @@ func run(parent context.Context, o *options) error { Metrics: diag.NewMetrics(ctrlmetrics.Registry, "node"), }, } + nldump.MustRegister(ctrlmetrics.Registry) if err := ctrlmetrics.Registry.Register(agent.Collector{Agent: a}); err != nil { return fmt.Errorf("register edge node metrics: %w", err) } diff --git a/cmd/galactic-gateway/root.go b/cmd/galactic-gateway/root.go index 49cb6317a..95ee6bbde 100644 --- a/cmd/galactic-gateway/root.go +++ b/cmd/galactic-gateway/root.go @@ -31,6 +31,7 @@ import ( "go.datum.net/galactic/internal/gateway" "go.datum.net/galactic/internal/metadata" "go.datum.net/galactic/internal/plumbing/ebpf/xdpdispatch" + "go.datum.net/galactic/internal/plumbing/nldump" "go.datum.net/galactic/internal/plumbing/sysctl" ) @@ -198,6 +199,7 @@ func runCmd(cfg *config.GatewayConfig) error { gwQuota := gateway.NewNodeQuotaEnforcer(gateway.DefaultMaxRulesPerTenant, gateway.DefaultMaxRuleTableEntries) gwTelemetry := gateway.NewPrometheusTelemetryEmitter() gwTelemetry.MustRegister(ctrlmetrics.Registry) + nldump.MustRegister(ctrlmetrics.Registry) gwEngine := gateway.NewEngine(gwDatapath, gwQuota, gwTelemetry) // The gateway engine reconciler. No SRv6 address is passed: this datapath diff --git a/cmd/galactic-nat/root.go b/cmd/galactic-nat/root.go index a8160574b..1e145d436 100644 --- a/cmd/galactic-nat/root.go +++ b/cmd/galactic-nat/root.go @@ -30,6 +30,7 @@ import ( "go.datum.net/galactic/internal/controller" "go.datum.net/galactic/internal/metadata" "go.datum.net/galactic/internal/plumbing/ebpf/xdpdispatch" + "go.datum.net/galactic/internal/plumbing/nldump" "go.datum.net/galactic/internal/plumbing/sysctl" ) @@ -143,6 +144,7 @@ func runCmd(cfg *config.NATConfig) error { if err != nil { return fmt.Errorf("setup egress translation eBPF datapath: %w", err) } + nldump.MustRegister(ctrlmetrics.Registry) if err := ctrlmetrics.Registry.Register( newShardStateCollector(datapath, cfg.DatapathEnabled, cfg.XDPAttach)); err != nil { return fmt.Errorf("register egress shard state metrics: %w", err) diff --git a/cmd/galactic-router/root.go b/cmd/galactic-router/root.go index 5c4b3e0c5..01eb110ca 100644 --- a/cmd/galactic-router/root.go +++ b/cmd/galactic-router/root.go @@ -40,6 +40,7 @@ import ( "go.datum.net/galactic/internal/plumbing/ebpf/attach" "go.datum.net/galactic/internal/plumbing/ebpf/vipxlatmap" "go.datum.net/galactic/internal/plumbing/loaddr" + "go.datum.net/galactic/internal/plumbing/nldump" "go.datum.net/galactic/internal/reconcile" galacticruntime "go.datum.net/galactic/internal/runtime" "go.datum.net/galactic/internal/runtime/gobgp" @@ -105,6 +106,7 @@ func runCmd(cfg *config.RouterConfig) error { } serviceRouteMetrics := serviceroute.NewMetrics() serviceRouteMetrics.MustRegister(ctrlmetrics.Registry) + nldump.MustRegister(ctrlmetrics.Registry) // ctx carries a cause so an ordinary signal-triggered shutdown can be told // apart from the health server's own Serve failure below. See the cause diff --git a/cmd/galactic-vrf/root.go b/cmd/galactic-vrf/root.go index 6252d17a7..de84cf559 100644 --- a/cmd/galactic-vrf/root.go +++ b/cmd/galactic-vrf/root.go @@ -24,6 +24,7 @@ import ( "go.datum.net/galactic/internal/config" "go.datum.net/galactic/internal/ingresssidecar" "go.datum.net/galactic/internal/metadata" + "go.datum.net/galactic/internal/plumbing/nldump" ) const ( @@ -67,6 +68,7 @@ func runCmd(cfg *config.VRFConfig) error { metrics := ingresssidecar.NewMetrics() metrics.MustRegister(ctrlmetrics.Registry) + nldump.MustRegister(ctrlmetrics.Registry) lifecycle := ingresssidecar.NewLifecycleMetrics(cfg.SweepInterval, cfg.TeardownGracePeriod) lifecycle.MustRegister(ctrlmetrics.Registry) diff --git a/docs/observability/README.md b/docs/observability/README.md index c8069237b..30ad448aa 100644 --- a/docs/observability/README.md +++ b/docs/observability/README.md @@ -11,6 +11,7 @@ Metrics, scrape configuration and shipped alert rules. Use the subsystem referen - [Routing](routing.md) - [NAT66 / NAT64 — `galactic_nat_*`](nat.md) - [Fabric looking glass — `fabric_api_*`](fabric-api.md) +- [Netlink listings — `galactic_netlink_dump_*`](netlink.md) - [Shipped alerts](alerts.md) ## Where the metrics come from diff --git a/docs/observability/netlink.md b/docs/observability/netlink.md new file mode 100644 index 000000000..0fc1ba059 --- /dev/null +++ b/docs/observability/netlink.md @@ -0,0 +1,45 @@ +# Netlink listings — `galactic_netlink_dump_*` + +See [scraping and component ports](README.md#where-the-metrics-come-from). + +The kernel interrupts a listing of links, addresses or routes when another +process changes them while it runs. The listing is then discarded and +retried: up to 5 rounds of 10 back-to-back attempts, with a pause of 20, 40, +60 and 80 ms between rounds. These counters show how often that happens on a +node, so sustained churn is visible before it makes a component fail. + +| Metric | Type | Labels | Meaning | +| ----------------------------------------- | ------- | ----------------------------------- | ---------------------------------------------------------------------------------------------- | +| `galactic_netlink_dump_interrupted_total` | counter | `kind` (`link`, `address`, `route`) | Listing attempts the kernel interrupted. Each one is discarded and retried | +| `galactic_netlink_dump_failures_total` | counter | `kind` (`link`, `address`, `route`) | Listings still interrupted on their last attempt. The caller got an error and acted on nothing | + +Each process counts only its own listings, on its existing metrics port: + +| Component | Port | `job` from `config/monitoring/` | +| --------------------------------------- | -------------- | ---------------------------------------- | +| `galactic-cni` (`credential-refresh`) | 9180 | `galactic-cni` | +| `galactic-router`, `galactic-router-rr` | 9179 | `galactic-router` / `galactic-router-rr` | +| `galactic-nat` | 9182 | `galactic-nat` | +| `galactic-edge` | 9186 | `galactic-edge` | +| `galactic-vrf` | 9182 (default) | none shipped | +| `galactic-gateway` | 8081 | none shipped | + +`galactic-vrf` and `galactic-gateway` need a scrape object of your own. +Until one exists, the queries below show nothing for them, which is not the +same as no churn. + +The CNI plugins run once per attach and expose no metrics, so their +listings are not counted; an exhausted retry there fails the attach or +detach with the interruption error. Listings that do not go through the +shared retry are not counted either. + +Interruptions are normal while pods start and stop. A failure is not: the +component returned an error for that pass and retries it later. + +```promql +# Interruptions per second, by node, component and kind +sum by (node, job, kind) (rate(galactic_netlink_dump_interrupted_total[5m])) + +# Listings that failed after every retry in the last hour +sum by (node, job, kind) (increase(galactic_netlink_dump_failures_total[1h])) > 0 +``` diff --git a/internal/installer/installer.go b/internal/installer/installer.go index b5869e6e5..aa2722c19 100644 --- a/internal/installer/installer.go +++ b/internal/installer/installer.go @@ -40,6 +40,7 @@ import ( "go.datum.net/galactic/internal/plumbing/ebpf/metrics" "go.datum.net/galactic/internal/plumbing/ebpf/prog" "go.datum.net/galactic/internal/plumbing/ebpf/usidmap" + "go.datum.net/galactic/internal/plumbing/nldump" "go.datum.net/galactic/internal/plumbing/radv" ) @@ -1109,6 +1110,7 @@ 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) ebpfState, datapath, err := startEBPFDatapath(ctx, m) if err != nil { diff --git a/internal/plumbing/nldump/churn_internal_test.go b/internal/plumbing/nldump/churn_internal_test.go new file mode 100644 index 000000000..eb4bf0445 --- /dev/null +++ b/internal/plumbing/nldump/churn_internal_test.go @@ -0,0 +1,101 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package nldump + +import ( + "fmt" + "os" + "sync" + "testing" + "time" + + "github.com/containernetworking/plugins/pkg/ns" + "github.com/prometheus/client_golang/prometheus/testutil" + "github.com/vishvananda/netlink" +) + +func requireRoot(t *testing.T) { + t.Helper() + if os.Geteuid() != 0 { + t.Skip("test requires root (CAP_NET_ADMIN) to create a network namespace; re-run via sudo") + } +} + +// TestLinkList_CountsRealInterruptions lists links on a real kernel while +// other goroutines add and remove links in the same namespace. Every listing +// succeeds, and the interrupted counter records the interruptions the +// kernel reported along the way. +func TestLinkList_CountsRealInterruptions(t *testing.T) { + requireRoot(t) + nsObj, err := ns.TempNetNS() + if err != nil { + t.Fatalf("create test netns: %v", err) + } + t.Cleanup(func() { _ = nsObj.Close() }) + + err = nsObj.Do(func(_ ns.NetNS) error { + for i := range 300 { + if err := netlink.LinkAdd(&netlink.Dummy{LinkAttrs: netlink.LinkAttrs{Name: fmt.Sprintf("stab%d", i)}}); err != nil { + return fmt.Errorf("add stable link %d: %w", i, err) + } + } + return nil + }) + if err != nil { + t.Fatal(err) + } + + stop := make(chan struct{}) + var wg sync.WaitGroup + for c := range 2 { + wg.Add(1) + go func() { + defer wg.Done() + _ = nsObj.Do(func(_ ns.NetNS) error { + for i := 0; ; i++ { + select { + case <-stop: + return nil + default: + } + dummy := &netlink.Dummy{LinkAttrs: netlink.LinkAttrs{Name: fmt.Sprintf("churn%d_%d", c, i%4)}} + if err := netlink.LinkAdd(dummy); err == nil { + _ = netlink.LinkDel(dummy) + } + // Bursts of changes, not a saturated loop that could + // outlast any bounded retry. + time.Sleep(2 * time.Millisecond) + } + }) + }() + } + t.Cleanup(func() { + close(stop) + wg.Wait() + }) + + before := testutil.ToFloat64(interrupted.WithLabelValues(kindLink)) + beforeFailures := testutil.ToFloat64(failures.WithLabelValues(kindLink)) + err = nsObj.Do(func(_ ns.NetNS) error { + // Churn interrupts a listing within a few iterations; the deadline + // only bounds a kernel that never reports one. + deadline := time.Now().Add(10 * time.Second) + for i := 0; testutil.ToFloat64(interrupted.WithLabelValues(kindLink)) == before; i++ { + if time.Now().After(deadline) { + return fmt.Errorf("no interruption counted after %d listings under link churn", i) + } + if _, err := LinkList(); err != nil { + return fmt.Errorf("LinkList failed on iteration %d while links were changing: %w", i, err) + } + } + return nil + }) + if err != nil { + t.Fatal(err) + } + if d := testutil.ToFloat64(failures.WithLabelValues(kindLink)) - beforeFailures; d != 0 { + t.Errorf("failure counter rose by %v, want 0", d) + } +} diff --git a/internal/plumbing/nldump/nldump.go b/internal/plumbing/nldump/nldump.go index 6b6fccaf4..6ea3d5274 100644 --- a/internal/plumbing/nldump/nldump.go +++ b/internal/plumbing/nldump/nldump.go @@ -9,10 +9,11 @@ // the dump runs, as it does whenever another process adds or removes a link, // address or route. The package-level netlink list functions make a single // attempt and return netlink.ErrDumpInterrupted, so any churn on the node -// fails the caller. These functions dump over a handle that retries -// internally, retry the whole dump a bounded number of times on top of that, -// and never return a partial result: an entry missing from an interrupted -// dump would look absent. +// fails the caller. These functions retry an interrupted dump a bounded +// number of times and never return a partial result: an entry missing from an +// interrupted dump would look absent. Every interrupted attempt, and every +// dump still interrupted on its last attempt, is counted in the metrics +// MustRegister exposes, so churn is visible before it fails a caller. // // Each call opens its own netlink socket in the calling thread's network // namespace, with the same send and receive timeout, as the package-level @@ -21,48 +22,93 @@ package nldump import ( "errors" + "fmt" "time" + "github.com/prometheus/client_golang/prometheus" "github.com/vishvananda/netlink" "golang.org/x/sys/unix" ) -// dumpAttempts and dumpBackoff bound how long a dump keeps retrying when -// other processes keep interrupting it. Each attempt is itself up to 10 tries -// inside netlink, so this only matters under sustained churn; the pause lets -// a burst of changes finish before the next dump. +// dumpRounds, triesPerRound and roundBackoff bound how long a dump keeps +// retrying when other processes keep interrupting it. The tries within a +// round run back to back, as netlink's own retry does; the pause after each +// round, longer each time, lets a burst of changes finish before the next. const ( - dumpAttempts = 5 - dumpBackoff = 20 * time.Millisecond + dumpRounds = 5 + triesPerRound = 10 + roundBackoff = 20 * time.Millisecond ) +// labelKind names the listing kind, one of the kind* values. +const labelKind = "kind" + +// Listing kinds, the values of labelKind. +const ( + kindLink = "link" + kindAddress = "address" + kindRoute = "route" +) + +var ( + interrupted = prometheus.NewCounterVec(prometheus.CounterOpts{ + Namespace: "galactic", + Subsystem: "netlink_dump", + Name: "interrupted_total", + Help: "Netlink listing attempts the kernel interrupted because the state they walked changed, " + + "by kind. Each is discarded and retried.", + }, []string{labelKind}) + failures = prometheus.NewCounterVec(prometheus.CounterOpts{ + Namespace: "galactic", + Subsystem: "netlink_dump", + Name: "failures_total", + Help: "Netlink listings still interrupted on their last attempt, which failed their caller, by kind.", + }, []string{labelKind}) +) + +func init() { + for _, kind := range []string{kindLink, kindAddress, kindRoute} { + interrupted.WithLabelValues(kind) + failures.WithLabelValues(kind) + } +} + +// MustRegister registers the interruption and failure counters against reg, +// panicking on a duplicate as the underlying registry does. The counters are +// process-wide, so a process registers them once, at startup. +func MustRegister(reg prometheus.Registerer) { + reg.MustRegister(interrupted, failures) +} + // sleep is time.Sleep, replaced by tests. var sleep = time.Sleep // LinkList returns every link in the calling thread's network namespace. func LinkList() ([]netlink.Link, error) { - return dump(func(h *netlink.Handle) ([]netlink.Link, error) { return h.LinkList() }) + return dump(kindLink, func(h *netlink.Handle) ([]netlink.Link, error) { return h.LinkList() }) } // AddrList returns link's addresses of family, or every link's when link is // nil. Errors other than an interrupted dump are returned as netlink returns // them. func AddrList(link netlink.Link, family int) ([]netlink.Addr, error) { - return dump(func(h *netlink.Handle) ([]netlink.Addr, error) { return h.AddrList(link, family) }) + return dump(kindAddress, func(h *netlink.Handle) ([]netlink.Addr, error) { return h.AddrList(link, family) }) } // RouteListFiltered returns the routes of family that match filter on the // fields filterMask selects, as netlink.RouteListFiltered does. func RouteListFiltered(family int, filter *netlink.Route, filterMask uint64) ([]netlink.Route, error) { - return dump(func(h *netlink.Handle) ([]netlink.Route, error) { + return dump(kindRoute, func(h *netlink.Handle) ([]netlink.Route, error) { return h.RouteListFiltered(family, filter, filterMask) }) } -// dump runs list over a retrying rtnetlink handle, through retry. -func dump[T any](list func(*netlink.Handle) (T, error)) (T, error) { +// dump runs list over an rtnetlink handle, through retry. +func dump[T any](kind string, list func(*netlink.Handle) (T, error)) (T, error) { var zero T - handle, err := netlink.NewHandleWithOptions(netlink.HandleOptions{RetryInterrupted: true}, unix.NETLINK_ROUTE) + // The handle makes one attempt per call, so retry sees, and counts, every + // interruption. + handle, err := netlink.NewHandle(unix.NETLINK_ROUTE) if err != nil { return zero, err } @@ -73,22 +119,31 @@ func dump[T any](list func(*netlink.Handle) (T, error)) (T, error) { if err := handle.SetSocketTimeout(netlink.GetSocketTimeout()); err != nil { return zero, err } - return retry(func() (T, error) { return list(handle) }) + return retry(kind, func() (T, error) { return list(handle) }) } // retry calls list until it returns anything but netlink.ErrDumpInterrupted, -// at most dumpAttempts times, pausing longer after each interruption. The -// result of an interrupted attempt is discarded, never returned. -func retry[T any](list func() (T, error)) (T, error) { +// at most dumpRounds*triesPerRound times, pausing after each round. It counts +// every interrupted attempt, and a final one as a failure. The result of an +// interrupted attempt is discarded, never returned. +func retry[T any](kind string, list func() (T, error)) (T, error) { var zero T for attempt := 1; ; attempt++ { got, err := list() if err == nil { return got, nil } - if !errors.Is(err, netlink.ErrDumpInterrupted) || attempt == dumpAttempts { + if !errors.Is(err, netlink.ErrDumpInterrupted) { return zero, err } - sleep(time.Duration(attempt) * dumpBackoff) + interrupted.WithLabelValues(kind).Inc() + if attempt == dumpRounds*triesPerRound { + failures.WithLabelValues(kind).Inc() + // netlink's own message counts only the handle's single try. + return zero, fmt.Errorf("netlink %s dump still interrupted after %d attempts: %w", kind, attempt, err) + } + if attempt%triesPerRound == 0 { + sleep(time.Duration(attempt/triesPerRound) * roundBackoff) + } } } diff --git a/internal/plumbing/nldump/nldump_internal_test.go b/internal/plumbing/nldump/nldump_internal_test.go index c17ba690c..77f8c8dbb 100644 --- a/internal/plumbing/nldump/nldump_internal_test.go +++ b/internal/plumbing/nldump/nldump_internal_test.go @@ -8,23 +8,29 @@ import ( "errors" "fmt" "slices" + "strings" "testing" "time" + "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/client_golang/prometheus/testutil" "github.com/vishvananda/netlink" "golang.org/x/sys/unix" ) // errInterrupted is how netlink reports a dump the kernel flagged interrupted. -var errInterrupted = fmt.Errorf("execute netlink request after 10 attempts: %w", netlink.ErrDumpInterrupted) +var errInterrupted = fmt.Errorf("execute netlink request after 1 attempts: %w", netlink.ErrDumpInterrupted) -// fakeDump returns each of results in turn, counting its calls. -func fakeDump(results ...func() ([]string, error)) (func() ([]string, error), *int) { +// fakeDump fails its first n calls as interrupted, each with a partial +// result, then returns the complete result. It counts its calls. +func fakeDump(n int) (func() ([]string, error), *int) { calls := 0 return func() ([]string, error) { - r := results[calls] calls++ - return r() + if calls <= n { + return []string{"partial"}, errInterrupted + } + return []string{"a", "b"}, nil }, &calls } @@ -37,56 +43,117 @@ func withNoSleep(t *testing.T) *[]time.Duration { return &slept } +// counts returns the interrupted and failure counts for kind. +func counts(kind string) (float64, float64) { + return testutil.ToFloat64(interrupted.WithLabelValues(kind)), testutil.ToFloat64(failures.WithLabelValues(kind)) +} + func TestRetry_RetriesInterruptedDumpAndDropsPartialResult(t *testing.T) { slept := withNoSleep(t) - partial := func() ([]string, error) { return []string{"partial"}, errInterrupted } - complete := func() ([]string, error) { return []string{"a", "b"}, nil } - list, calls := fakeDump(partial, partial, complete) + beforeInterrupted, beforeFailures := counts(kindLink) + list, calls := fakeDump(triesPerRound + 2) - got, err := retry(list) + got, err := retry(kindLink, list) if err != nil { t.Fatalf("retry: %v", err) } if !slices.Equal(got, []string{"a", "b"}) { t.Errorf("got %v, want the complete dump [a b]", got) } - if *calls != 3 { - t.Errorf("dumped %d times, want 3", *calls) + if *calls != triesPerRound+3 { + t.Errorf("dumped %d times, want %d", *calls, triesPerRound+3) } - if want := []time.Duration{dumpBackoff, 2 * dumpBackoff}; !slices.Equal(*slept, want) { - t.Errorf("slept %v, want %v", *slept, want) + if want := []time.Duration{roundBackoff}; !slices.Equal(*slept, want) { + t.Errorf("slept %v, want one pause of %v after the first round", *slept, want) + } + afterInterrupted, afterFailures := counts(kindLink) + if d := afterInterrupted - beforeInterrupted; d != triesPerRound+2 { + t.Errorf("interrupted counter rose by %v, want %d", d, triesPerRound+2) + } + if afterFailures != beforeFailures { + t.Errorf("failure counter rose by %v, want 0", afterFailures-beforeFailures) } } func TestRetry_GivesUpAfterBound(t *testing.T) { - withNoSleep(t) - results := make([]func() ([]string, error), dumpAttempts) - for i := range results { - results[i] = func() ([]string, error) { return []string{"partial"}, errInterrupted } - } - list, calls := fakeDump(results...) + slept := withNoSleep(t) + beforeInterrupted, beforeFailures := counts(kindRoute) + const bound = dumpRounds * triesPerRound + list, calls := fakeDump(bound) - got, err := retry(list) + got, err := retry(kindRoute, list) if !errors.Is(err, netlink.ErrDumpInterrupted) { t.Fatalf("err = %v, want ErrDumpInterrupted", err) } + if want := fmt.Sprintf("after %d attempts", bound); !strings.Contains(err.Error(), want) { + t.Errorf("err = %q, want it to report %q", err, want) + } if got != nil { t.Errorf("got %v, want no partial result", got) } - if *calls != dumpAttempts { - t.Errorf("dumped %d times, want %d", *calls, dumpAttempts) + if *calls != bound { + t.Errorf("dumped %d times, want %d", *calls, bound) + } + want := []time.Duration{roundBackoff, 2 * roundBackoff, 3 * roundBackoff, 4 * roundBackoff} + if !slices.Equal(*slept, want) { + t.Errorf("slept %v, want %v", *slept, want) + } + afterInterrupted, afterFailures := counts(kindRoute) + if d := afterInterrupted - beforeInterrupted; d != bound { + t.Errorf("interrupted counter rose by %v, want %d", d, bound) + } + if d := afterFailures - beforeFailures; d != 1 { + t.Errorf("failure counter rose by %v, want 1", d) } } func TestRetry_ReturnsOtherErrorsAtOnce(t *testing.T) { slept := withNoSleep(t) - list, calls := fakeDump(func() ([]string, error) { return nil, unix.ENODEV }) + beforeInterrupted, beforeFailures := counts(kindAddress) + calls := 0 + list := func() ([]string, error) { + calls++ + return nil, unix.ENODEV + } - _, err := retry(list) + _, err := retry(kindAddress, list) if !errors.Is(err, unix.ENODEV) { t.Fatalf("err = %v, want ENODEV", err) } - if *calls != 1 || len(*slept) != 0 { - t.Errorf("dumped %d times and slept %d times, want 1 and 0", *calls, len(*slept)) + if calls != 1 || len(*slept) != 0 { + t.Errorf("dumped %d times and slept %d times, want 1 and 0", calls, len(*slept)) + } + afterInterrupted, afterFailures := counts(kindAddress) + if afterInterrupted != beforeInterrupted || afterFailures != beforeFailures { + t.Errorf("counters moved on a non-interrupt error") + } +} + +// TestMustRegister_ExposesEveryKind pins that a scrape shows both counters +// for every listing kind from startup, before any listing is interrupted, so +// a rate over them is defined from the first scrape. +func TestMustRegister_ExposesEveryKind(t *testing.T) { + reg := prometheus.NewRegistry() + MustRegister(reg) + families, err := reg.Gather() + if err != nil { + t.Fatalf("gather: %v", err) + } + got := map[string][]string{} + for _, f := range families { + for _, m := range f.GetMetric() { + for _, l := range m.GetLabel() { + if l.GetName() == labelKind { + got[f.GetName()] = append(got[f.GetName()], l.GetValue()) + } + } + } + } + want := []string{kindAddress, kindLink, kindRoute} + for _, name := range []string{"galactic_netlink_dump_interrupted_total", "galactic_netlink_dump_failures_total"} { + slices.Sort(got[name]) + if !slices.Equal(got[name], want) { + t.Errorf("%s kinds = %v, want %v", name, got[name], want) + } } }