From 4f1b8c620ad75caa311ee94d0ff6d364c5b58654 Mon Sep 17 00:00:00 2001 From: "randomizedcoder dave.seddon.ca@gmail.com" Date: Thu, 26 Nov 2026 22:35:17 -0800 Subject: [PATCH 1/5] test(xtcp): uplinks follow a route change (red) Table tests for the uplink refresh: a metric swap moves the stamp, an unchanged list skips sysfs and lldpd, a lost uplink falls back to the physical NICs, lldpd failing keeps the NIC columns, the refresh interval rules, the ticker loop, and a race test that a record never mixes two stamps. They don't build yet: uplinkSources and the refresh are next. Co-Authored-By: Claude Opus 5.5 --- pkg/xtcp/enrich_uplinks_refresh_test.go | 252 ++++++++++++++++++++++++ 1 file changed, 252 insertions(+) create mode 100644 pkg/xtcp/enrich_uplinks_refresh_test.go diff --git a/pkg/xtcp/enrich_uplinks_refresh_test.go b/pkg/xtcp/enrich_uplinks_refresh_test.go new file mode 100644 index 000000000..6768ef78b --- /dev/null +++ b/pkg/xtcp/enrich_uplinks_refresh_test.go @@ -0,0 +1,252 @@ +package xtcp + +import ( + "context" + "errors" + "slices" + "sync" + "testing" + "time" + + "github.com/prometheus/client_golang/prometheus/testutil" + "google.golang.org/protobuf/types/known/durationpb" + + "github.com/randomizedcoder/xtcp2/gen/go/xtcp_config" + "github.com/randomizedcoder/xtcp2/gen/go/xtcp_flat_record" + "github.com/randomizedcoder/xtcp2/pkg/lldp" + "github.com/randomizedcoder/xtcp2/pkg/nicinfo" +) + +// fakeUplinks scripts the uplink sources: each call to defaultUplinks returns +// the next list in routes (the last one repeats), and it counts the sysfs and +// lldpd reads a refresh makes. +type fakeUplinks struct { + mu sync.Mutex + routes [][]string + physical []string + lldpErr error + calls int + collects int + fetches int +} + +func (f *fakeUplinks) sources() uplinkSources { + return uplinkSources{ + defaultUplinks: func(maxN int) []string { + f.mu.Lock() + defer f.mu.Unlock() + i := min(f.calls, len(f.routes)-1) + f.calls++ + return slices.Clone(f.routes[i]) + }, + physical: func(maxN int) []string { return slices.Clone(f.physical) }, + collect: func(ifnames []string) []nicinfo.NIC { + f.mu.Lock() + f.collects++ + f.mu.Unlock() + nics := make([]nicinfo.NIC, 0, len(ifnames)) + for _, n := range ifnames { + nics = append(nics, nicinfo.NIC{Ifname: n, Driver: "drv-" + n}) + } + return nics + }, + fetchLLDP: func(context.Context) (map[string]lldp.Neighbor, error) { + f.mu.Lock() + f.fetches++ + err := f.lldpErr + f.mu.Unlock() + if err != nil { + return nil, err + } + return map[string]lldp.Neighbor{"eth0": {Ifname: "eth0", ChassisName: "sw-a"}, "eth1": {Ifname: "eth1", ChassisName: "sw-b"}}, nil + }, + } +} + +func uplinkFixture(t *testing.T, f *fakeUplinks) *XTCP { + t.Helper() + x := newMetricsFixture(t, time.Minute) + x.config.EnrichNicEnable = true + x.config.EnrichLldpEnable = true + x.uplinkSrc = f.sources() + return x +} + +func stampedUplink1(x *XTCP) (ifname, driver, chassis string) { + r := &xtcp_flat_record.XtcpFlatRecord{} + x.applyEnrichment(r) + return r.Uplink1Ifname, r.Uplink1NicDriver, r.Uplink1LldpChassisName +} + +func refreshCount(x *XTCP, outcome string) float64 { + return testutil.ToFloat64(x.pC.WithLabelValues("refreshUplinks", "uplinks", outcome)) +} + +// go test ./pkg/xtcp/ -run TestRefreshUplinksOnce +func TestRefreshUplinksOnce(t *testing.T) { + tests := []struct { + name string + category string + description string + routes [][]string // startup, then one refresh + physical []string + lldpErr error // on the refresh only + wantUplink1 string + wantDriver string + wantChassis string + wantCollects int + wantOutcome string + }{ + {name: "swap_follows", category: "positive", description: "a metric swap moves the stamp", + routes: [][]string{{"eth0", "eth1"}, {"eth1", "eth0"}}, wantUplink1: "eth1", wantDriver: "drv-eth1", wantChassis: "sw-b", + wantCollects: 2, wantOutcome: "changed"}, + {name: "unchanged_no_rebuild", category: "negative", description: "the same list reads neither sysfs nor lldpd again", + routes: [][]string{{"eth0", "eth1"}, {"eth0", "eth1"}}, wantUplink1: "eth0", wantDriver: "drv-eth0", wantChassis: "sw-a", + wantCollects: 1, wantOutcome: "unchanged"}, + {name: "uplink_lost", category: "boundary", description: "the default route goes away: the physical fallback takes over", + routes: [][]string{{"eth0"}, {}}, physical: []string{"eth2"}, wantUplink1: "eth2", wantDriver: "drv-eth2", + wantCollects: 2, wantOutcome: "changed"}, + {name: "none_left", category: "boundary", description: "no route and no physical NIC: the columns go empty", + routes: [][]string{{"eth0"}, {}}, wantCollects: 1, wantOutcome: "changed"}, + {name: "lldp_fails_on_refresh", category: "corner", description: "lldpd down on refresh keeps the new NIC columns", + routes: [][]string{{"eth0", "eth1"}, {"eth1", "eth0"}}, lldpErr: errors.New("lldpd gone"), + wantUplink1: "eth1", wantDriver: "drv-eth1", wantCollects: 2, wantOutcome: "lldp_error"}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + f := &fakeUplinks{routes: tc.routes, physical: tc.physical} + x := uplinkFixture(t, f) + x.initUplinkEnrichers(context.Background()) + current := tc.routes[0] + + f.mu.Lock() + f.lldpErr = tc.lldpErr + f.mu.Unlock() + x.refreshUplinksOnce(context.Background(), maxUplinks, current) + + gotIf, gotDrv, gotCh := stampedUplink1(x) + if gotIf != tc.wantUplink1 || gotDrv != tc.wantDriver || gotCh != tc.wantChassis { + t.Errorf("%s: uplink1 = %q/%q/%q, expected %q/%q/%q", tc.description, gotIf, gotDrv, gotCh, tc.wantUplink1, tc.wantDriver, tc.wantChassis) + } + if f.collects != tc.wantCollects { + t.Errorf("%s: %d sysfs reads, expected %d", tc.description, f.collects, tc.wantCollects) + } + if got := refreshCount(x, tc.wantOutcome); got != 1 { + t.Errorf("%s: refreshUplinks %s = %v, expected 1", tc.description, tc.wantOutcome, got) + } + }) + } +} + +// go test ./pkg/xtcp/ -run TestUplinkRefreshInterval +func TestUplinkRefreshInterval(t *testing.T) { + tests := []struct { + name string + category string + description string + config *xtcp_config.XtcpConfig + expected time.Duration + }{ + {name: "auto_refresh", category: "positive", description: "auto-detected uplinks refresh on the locality interval", + config: &xtcp_config.XtcpConfig{EnrichNicEnable: true, LocalityRefreshInterval: durationpb.New(time.Minute)}, expected: time.Minute}, + {name: "pinned_no_refresh", category: "negative", description: "pinned uplink interfaces never refresh", + config: &xtcp_config.XtcpConfig{EnrichNicEnable: true, UplinkInterfaces: []string{"eth9"}, LocalityRefreshInterval: durationpb.New(time.Minute)}}, + {name: "interval_zero", category: "boundary", description: "locality_refresh_interval 0 loads once", + config: &xtcp_config.XtcpConfig{EnrichNicEnable: true, LocalityRefreshInterval: durationpb.New(0)}}, + {name: "interval_unset", category: "corner", description: "no interval at all loads once", + config: &xtcp_config.XtcpConfig{EnrichLldpEnable: true}}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + if got := uplinkRefreshInterval(tc.config); got != tc.expected { + t.Errorf("%s: got %v, expected %v", tc.description, got, tc.expected) + } + }) + } +} + +// go test ./pkg/xtcp/ -run TestRefreshUplinksLoop +func TestRefreshUplinksLoop(t *testing.T) { + tests := []struct { + name string + category string + description string + ticks int + expected string // uplink1 after the ticks + }{ + {name: "two_ticks", category: "positive", description: "each tick re-reads the routes", ticks: 2, expected: "eth0"}, + {name: "one_tick", category: "boundary", description: "one tick applies the swap", ticks: 1, expected: "eth1"}, + {name: "no_tick", category: "corner", description: "cancel before any tick keeps the startup stamp", ticks: 0, expected: "eth0"}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + f := &fakeUplinks{routes: [][]string{{"eth0", "eth1"}, {"eth1", "eth0"}, {"eth0", "eth1"}}} + x := uplinkFixture(t, f) + x.initUplinkEnrichers(context.Background()) + + ctx, cancel := context.WithCancel(context.Background()) + tick := make(chan time.Time) + done := make(chan struct{}) + go func() { + x.refreshUplinks(ctx, maxUplinks, []string{"eth0", "eth1"}, tick) + close(done) + }() + for range tc.ticks { + tick <- time.Now() + } + cancel() + select { + case <-done: + case <-time.After(5 * time.Second): + t.Fatalf("%s: the refresh loop did not return after cancel", tc.description) + } + if got, _, _ := stampedUplink1(x); got != tc.expected { + t.Errorf("%s: uplink1 = %q, expected %q", tc.description, got, tc.expected) + } + }) + } +} + +// TestUplinkStampConcurrent: stamping while a refresh swaps the stamp is +// race-free and never mixes two stamps in one record. Run with -race. +func TestUplinkStampConcurrent(t *testing.T) { + f := &fakeUplinks{routes: [][]string{{"eth0", "eth1"}}} + x := uplinkFixture(t, f) + x.initUplinkEnrichers(context.Background()) + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + var wg sync.WaitGroup + wg.Go(func() { + lists := [][]string{{"eth1", "eth0"}, {"eth0", "eth1"}} + current := []string{"eth0", "eth1"} + for i := 0; ctx.Err() == nil && i < 2000; i++ { + f.mu.Lock() + f.routes = [][]string{lists[i%2]} + f.calls = 0 + f.mu.Unlock() + current = x.refreshUplinksOnce(ctx, maxUplinks, current) + } + }) + for range 20000 { + r := &xtcp_flat_record.XtcpFlatRecord{} + x.applyEnrichment(r) + if r.Uplink1NicDriver != "drv-"+r.Uplink1Ifname || r.Uplink2NicDriver != "drv-"+r.Uplink2Ifname || r.Uplink1Ifname == r.Uplink2Ifname { + t.Fatalf("mixed stamp: %q/%q, %q/%q", r.Uplink1Ifname, r.Uplink1NicDriver, r.Uplink2Ifname, r.Uplink2NicDriver) + } + } + cancel() + wg.Wait() +} + +// go test ./pkg/xtcp/ -run '^$' -bench BenchmarkApplyEnrichmentUplink -benchmem +func BenchmarkApplyEnrichmentUplink(b *testing.B) { + x := new(XTCP) + s := buildUplinkStamp([]string{"eth0", "eth1"}, []nicinfo.NIC{{Ifname: "eth0", Driver: "mlx5_core"}, {Ifname: "eth1", Driver: "ice"}}, nil) + x.uplinkStamp.Store(&s) + r := &xtcp_flat_record.XtcpFlatRecord{} + b.ReportAllocs() + for b.Loop() { + x.applyEnrichment(r) + } +} From 73528f15068ba3edb14d7c1ba7be5e6d23f97131 Mon Sep 17 00:00:00 2001 From: "randomizedcoder dave.seddon.ca@gmail.com" Date: Thu, 26 Nov 2026 22:38:18 -0800 Subject: [PATCH 2/5] fix(xtcp): uplinks follow a route change The uplink columns were chosen once at startup, so a route-metric swap moved egress and locality within a refresh but left the uplinks naming the old interface until a restart. Auto-detected uplinks are now re-read every locality_refresh_interval (0 = never; pinned uplink_interfaces are never re-read). The stamp is an atomic.Pointer swapped whole, so a record never mixes two. An unchanged list costs one /proc read; a changed one is read again from sysfs and lldpd off the hot path. Outcomes count under function=refreshUplinks: unchanged, changed, lldp_error. applyEnrichment: 18.2-20.1 ns/op vs 17.9-18.2 before (host load 5-9), 0 allocs. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + cmd/xtcp2/xtcp2.go | 2 +- docs/design-metadata-enrichment.md | 8 + pkg/nicinfo/uplinks.go | 5 +- pkg/xtcp/enrich.go | 198 ++++++++++++++++++++---- pkg/xtcp/enrich_uplinks_refresh_test.go | 6 +- pkg/xtcp/xtcp.go | 10 +- 7 files changed, 186 insertions(+), 44 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e4088f727..54d6b0024 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -35,6 +35,7 @@ ### Fixes +- **Uplinks follow a route change.** The uplink columns were chosen once at startup, so after a route-metric swap they still named the old uplink until a restart, while egress and locality had moved. Auto-detected uplinks are now re-read every `-localityRefreshInterval` (default 60s, 0 = never; pinned `-uplinkInterfaces` are never re-read). An unchanged list costs one `/proc` read; a changed one is read again from sysfs and lldpd and swapped in whole. New counter outcomes under `function="refreshUplinks"`: `unchanged`, `changed`, `lldp_error`. - **Egress follows the lowest route metric.** With two routes for the same prefix, `enrich_socket_dest_egress_ifname` named the one listed last, which the kernel lists by ascending metric, so it was the highest-metric route. That is the one the kernel uses last. The lowest metric now wins, and on a tie the first route listed, as in the kernel's lookup. - **Congestion names are matched whole.** `inet_diag_cong_enum` came from the first three letters, so `dctcp-reno` (DCTCP's fallback when ECN isn't negotiated) read as DCTCP and any name starting `cub` as CUBIC. Names now match exactly: `dctcp-reno` and look-alikes are UNSPECIFIED with their name kept, `bbr1` is BBR1, and `prague` gets its enum. A 2-letter name (`nv`, `lp`) without NLA padding is accepted (the minimum was 4 bytes). The in-tree names are now constants, so decoding them no longer allocates. - **`nsid` 0 is no longer ambiguous.** The kernel's first namespace id is 0, which read the same as "no id" and as `-populateNsid` off; Docker gives its containers ids 0, 1, 2… in creation order, so one container per host had the ambiguous 0. New column `nsid_assigned` (proto tag 33, a free slot, so no record epoch bump) is true exactly when `nsid` holds an assigned id: filter on it, not on `nsid != 0`. Existing ClickHouse deployments add it with `build/containers/clickhouse/sql/migrations/nsid-assigned.sql`; rows from older daemons read false. The CSV/TSV default columns gain it after `nsid`, shifting the later columns by one. Golden records compare `nsid` again, numbered like the other ids. diff --git a/cmd/xtcp2/xtcp2.go b/cmd/xtcp2/xtcp2.go index d2c2a2be3..dcb2a7683 100644 --- a/cmd/xtcp2/xtcp2.go +++ b/cmd/xtcp2/xtcp2.go @@ -684,7 +684,7 @@ func defineEnrichmentFlags(f *mainFlags) { f.ipmetaBootstrapPath = flag.String("ipmetaBootstrapPath", ipmetaBootstrapPathCst, "optional zstd-compressed lookup artifact baked into the image and used by -enrichAsn before live refresh. Falls back to IPMETA_BOOTSTRAP_PATH env.") f.ipmetaCachePath = flag.String("ipmetaCachePath", ipmetaCachePathCst, "optional writable zstd-compressed lookup artifact used by -enrichAsn before the image bootstrap and refreshed after successful live reloads. Falls back to IPMETA_CACHE_PATH env.") f.enrichLocality = flag.Bool("enrichLocality", enrichLocalityCst, "best-effort: per namespace, dump the local addresses + routing table via rtnetlink and classify each socket's destination as self/local-subnet/remote, stamping the enrich_socket_dest_locality + interface-name columns (bound idiag_if and route egress). Non-fatal on read failure. Falls back to ENRICH_LOCALITY env."+enricherBuildNote(xtcp.EnricherLocality)) - f.localityRefreshInterval = flag.Duration("localityRefreshInterval", localityRefreshIntervalCst, "how often -enrichLocality re-dumps every namespace's addresses/routes on the reconcile path (new namespaces are always dumped on the next reconcile; failed or loopback-only namespaces retry on a 30s-5m backoff); 0 = discover each namespace once, never refresh. Falls back to LOCALITY_REFRESH_INTERVAL env.") + f.localityRefreshInterval = flag.Duration("localityRefreshInterval", localityRefreshIntervalCst, "how often -enrichLocality re-dumps every namespace's addresses/routes on the reconcile path (new namespaces are always dumped on the next reconcile; failed or loopback-only namespaces retry on a 30s-5m backoff); 0 = discover each namespace once, never refresh. Auto-detected uplinks (no -uplinkInterfaces) are re-read on the same interval. Falls back to LOCALITY_REFRESH_INTERVAL env.") f.localityEvents = flag.Bool("localityEvents", localityEventsCst, "with -enrichLocality, keep each namespace's locality snapshot current from rtnetlink link/address/route notifications (one listener per namespace) so a change shows within about a second; -localityRefreshInterval then becomes a backstop resync. Ignored without -enrichLocality. Falls back to LOCALITY_EVENTS env.") } diff --git a/docs/design-metadata-enrichment.md b/docs/design-metadata-enrichment.md index 7216d95d9..334ec9c28 100644 --- a/docs/design-metadata-enrichment.md +++ b/docs/design-metadata-enrichment.md @@ -85,6 +85,14 @@ usable routes count (up, not reject, not on `lo`: every host has the kernel's bridge) is replaced by the physical NICs under its `lower_*` sysfs links, since those carry the NIC attributes and the LLDP neighbours. +Auto-detected uplinks are re-read every `-localityRefreshInterval` (default 60s, +0 = never), so a route-metric swap moves the uplink columns within one interval, +the same as egress and locality. A tick whose list is unchanged reads only +`/proc`; a changed list is read again from sysfs and lldpd off the hot path and +its stamp replaces the old one atomically, so a record never mixes two. Pinned +`-uplinkInterfaces` are never re-read. Outcomes are counted under +`function="refreshUplinks"`: `unchanged`, `changed`, `lldp_error`. + ### Docker API limits Docker's list and inspect bodies carry tenant-chosen data (image labels, the diff --git a/pkg/nicinfo/uplinks.go b/pkg/nicinfo/uplinks.go index f2fcbaf22..b1750a06a 100644 --- a/pkg/nicinfo/uplinks.go +++ b/pkg/nicinfo/uplinks.go @@ -35,8 +35,9 @@ const maxLowerDepth = 8 // The metric is not read: the kernel lists same-prefix routes in ascending // metric order (IPv4 fib_find_alias, net/ipv4/fib_trie.c; IPv6 // fib6_add_rt2node, net/ipv6/ip6_fib.c), so the listing order is already the -// lowest metric first. xtcp2 calls this once at startup; a later route change -// does not move the uplink columns until a restart. +// lowest metric first. xtcp2 calls this at startup and again every +// locality_refresh_interval, so a route change moves the uplink columns +// within one interval (pkg/xtcp refreshUplinks). func DefaultUplinks(maxN int) []string { return defaultUplinks("/proc", "/sys", maxN) } diff --git a/pkg/xtcp/enrich.go b/pkg/xtcp/enrich.go index fe049f654..c59324d99 100644 --- a/pkg/xtcp/enrich.go +++ b/pkg/xtcp/enrich.go @@ -4,11 +4,13 @@ import ( "context" "log" "net/netip" + "slices" "strings" "time" "golang.org/x/sys/unix" + "github.com/randomizedcoder/xtcp2/gen/go/xtcp_config" "github.com/randomizedcoder/xtcp2/gen/go/xtcp_flat_record" "github.com/randomizedcoder/xtcp2/pkg/dockermeta" "github.com/randomizedcoder/xtcp2/pkg/lldp" @@ -135,34 +137,73 @@ func (x *XTCP) initDockerEnricher(ctx context.Context) { } } -// initUplinkEnrichers selects the uplink interfaces and captures the static NIC -// + LLDP columns once. Both sources are independently best-effort. -func (x *XTCP) initUplinkEnrichers(ctx context.Context) { - if !x.config.EnrichNicEnable && !x.config.EnrichLldpEnable { - return +// uplinkSources are where the uplink enricher reads from. A nil field means +// the real source (see orDefault); tests script them. +type uplinkSources struct { + defaultUplinks func(maxN int) []string + physical func(maxN int) []string + collect func(ifnames []string) []nicinfo.NIC + fetchLLDP func(ctx context.Context) (map[string]lldp.Neighbor, error) +} + +// orDefault fills each nil source with the real one. +func (s uplinkSources) orDefault(x *XTCP) uplinkSources { + if s.defaultUplinks == nil { + s.defaultUplinks = nicinfo.DefaultUplinks + } + if s.physical == nil { + s.physical = func(maxN int) []string { return nicinfo.PhysicalInterfaces("/sys", maxN) } } + if s.collect == nil { + s.collect = func(ifnames []string) []nicinfo.NIC { return nicinfo.Collect("/sys", ifnames) } + } + if s.fetchLLDP == nil { + s.fetchLLDP = func(ctx context.Context) (map[string]lldp.Neighbor, error) { + return lldp.Fetch(ctx, x.config.LldpdSocketPath, x.config.LldpdVersionHint) + } + } + return s +} - count := int(x.config.UplinkCount) - if count <= 0 { +// uplinkCount is the number of uplink slots to fill: uplink_count, clamped +// to 1..maxUplinks. +func uplinkCount(c *xtcp_config.XtcpConfig) int { + count := int(c.GetUplinkCount()) + if count <= 0 || count > maxUplinks { count = maxUplinks } - if count > maxUplinks { - count = maxUplinks + return count +} + +// uplinkRefreshInterval is how often the auto-detected uplinks are re-read: +// locality_refresh_interval, or 0 (never) when NIC and LLDP enrichment are +// both off, the uplinks are pinned by uplink_interfaces, or the interval is +// not positive. +func uplinkRefreshInterval(c *xtcp_config.XtcpConfig) time.Duration { + if !c.GetEnrichNicEnable() && !c.GetEnrichLldpEnable() { + return 0 + } + if len(c.GetUplinkInterfaces()) > 0 { + return 0 } + return max(c.GetLocalityRefreshInterval().AsDuration(), 0) +} - ifnames := x.config.UplinkInterfaces - if len(ifnames) == 0 { - ifnames = nicinfo.DefaultUplinks(count) +// initUplinkEnrichers selects the uplink interfaces and captures their NIC + +// LLDP columns. Both sources are independently best-effort. Auto-detected +// uplinks (no uplink_interfaces) are then re-read every +// locality_refresh_interval, so a route change moves the uplink columns +// with it (see refreshUplinks). +func (x *XTCP) initUplinkEnrichers(ctx context.Context) { + if !x.config.EnrichNicEnable && !x.config.EnrichLldpEnable { + return } + src := x.uplinkSrc.orDefault(x) + count := uplinkCount(x.config) + + ifnames := x.config.UplinkInterfaces if len(ifnames) == 0 { - // No explicit override and no default-route uplink (e.g. the default - // route lives on a separate management NIC, or none is configured). - // Fall back to the physical interfaces present in sysfs so NIC/LLDP - // columns still populate. - ifnames = nicinfo.PhysicalInterfaces("/sys", count) - if len(ifnames) > 0 { - x.pC.WithLabelValues("initEnrichers", "uplinks", "physical_fallback").Inc() - } + ifnames = x.selectUplinks(src, count, "initEnrichers") } if len(ifnames) > count { ifnames = ifnames[:count] @@ -170,31 +211,118 @@ func (x *XTCP) initUplinkEnrichers(ctx context.Context) { if len(ifnames) == 0 { x.pC.WithLabelValues("initEnrichers", "uplinks", "none").Inc() log.Printf("initUplinkEnrichers: no uplink interfaces detected (no override, no default route, no physical NIC in sysfs); NIC/LLDP columns left empty") - return + } else { + s, nics, neigh, err := x.buildStamp(ctx, src, ifnames) + if x.config.EnrichNicEnable { + x.pC.WithLabelValues("initEnrichers", "nic", "collected").Add(float64(nics)) + } + if err != nil { + x.pC.WithLabelValues("initEnrichers", "lldp", "error").Inc() + log.Printf("initUplinkEnrichers: LLDP enrichment disabled (best-effort): %v", err) + } else if x.config.EnrichLldpEnable { + x.pC.WithLabelValues("initEnrichers", "lldp", "neighbors").Add(float64(neigh)) + } + x.uplinkStamp.Store(&s) + log.Printf("initUplinkEnrichers: uplinks=%v nics=%d lldpNeighbors=%d", ifnames, nics, neigh) + } + + if interval := uplinkRefreshInterval(x.config); interval > 0 { + go func() { + ticker := time.NewTicker(interval) + defer ticker.Stop() + x.refreshUplinks(ctx, count, ifnames, ticker.C) + }() } +} +// selectUplinks picks up to count uplinks: the default-route interfaces, or +// when there are none (the default route lives on a separate management NIC, +// or none is configured) the physical interfaces in sysfs, so the NIC/LLDP +// columns still populate. The fallback is counted under function fn. +func (x *XTCP) selectUplinks(src uplinkSources, count int, fn string) []string { + ifnames := src.defaultUplinks(count) + if len(ifnames) == 0 { + ifnames = src.physical(count) + if len(ifnames) > 0 { + x.pC.WithLabelValues(fn, "uplinks", "physical_fallback").Inc() + } + } + if len(ifnames) > count { + ifnames = ifnames[:count] + } + return ifnames +} + +// buildStamp reads the NIC and LLDP columns of ifnames from sysfs and lldpd +// (each only when enabled) and returns the stamp, the NIC and neighbor +// counts, and the lldpd error, if any. The stamp keeps the NIC columns when +// lldpd fails. +func (x *XTCP) buildStamp(ctx context.Context, src uplinkSources, ifnames []string) (uplinkStamp, int, int, error) { var nics []nicinfo.NIC if x.config.EnrichNicEnable { - nics = nicinfo.Collect("/sys", ifnames) - x.pC.WithLabelValues("initEnrichers", "nic", "collected").Add(float64(len(nics))) + nics = src.collect(ifnames) } - - var neigh map[string]lldp.Neighbor + var ( + neigh map[string]lldp.Neighbor + err error + ) if x.config.EnrichLldpEnable { fetchCtx, cancel := context.WithTimeout(ctx, enrichDialTimeout) - n, err := lldp.Fetch(fetchCtx, x.config.LldpdSocketPath, x.config.LldpdVersionHint) + neigh, err = src.fetchLLDP(fetchCtx) cancel() if err != nil { - x.pC.WithLabelValues("initEnrichers", "lldp", "error").Inc() - log.Printf("initUplinkEnrichers: LLDP enrichment disabled (best-effort): %v", err) - } else { - neigh = n - x.pC.WithLabelValues("initEnrichers", "lldp", "neighbors").Add(float64(len(neigh))) + neigh = nil } } + return buildUplinkStamp(ifnames, nics, neigh), len(nics), len(neigh), err +} + +// refreshUplinks is initUplinkEnrichers' background loop: on every tick it +// re-reads the auto-detected uplinks (refreshUplinksOnce), starting from +// current. Runs until ctx is canceled. +func (x *XTCP) refreshUplinks(ctx context.Context, count int, current []string, tick <-chan time.Time) { + src := x.uplinkSrc.orDefault(x) + for { + select { + case <-ctx.Done(): + return + case <-tick: + current = x.refreshUplinksSrc(ctx, src, count, current) + } + } +} - x.uplinkStamp = buildUplinkStamp(ifnames, nics, neigh) - log.Printf("initUplinkEnrichers: uplinks=%v nics=%d lldpNeighbors=%d", ifnames, len(nics), len(neigh)) +// refreshUplinksOnce re-selects the uplinks and returns the list now in +// service. The same list as current costs one /proc read: no sysfs, no +// lldpd, no new stamp. A different list is read in full and its stamp +// replaces the old one (an empty stamp when no uplink is left). Outcomes are +// counted under function="refreshUplinks": unchanged, changed, or +// lldp_error (a changed list whose lldpd read failed: it keeps its NIC +// columns). +func (x *XTCP) refreshUplinksOnce(ctx context.Context, count int, current []string) []string { + return x.refreshUplinksSrc(ctx, x.uplinkSrc.orDefault(x), count, current) +} + +func (x *XTCP) refreshUplinksSrc(ctx context.Context, src uplinkSources, count int, current []string) []string { + ifnames := x.selectUplinks(src, count, "refreshUplinks") + if slices.Equal(ifnames, current) { + x.pC.WithLabelValues("refreshUplinks", "uplinks", "unchanged").Inc() + return current + } + s := uplinkStamp{} + outcome := "changed" + if len(ifnames) > 0 { + var err error + s, _, _, err = x.buildStamp(ctx, src, ifnames) + if err != nil { + outcome = "lldp_error" + log.Printf("refreshUplinks: LLDP columns left empty (best-effort): %v", err) + } + } + x.uplinkStamp.Store(&s) + x.pC.WithLabelValues("refreshUplinks", "uplinks", outcome).Inc() + log.Printf("refreshUplinks: uplinks %v -> %v", current, ifnames) + return ifnames } // buildUplinkStamp folds the per-interface NIC + LLDP lookups into the flat @@ -239,7 +367,9 @@ func buildUplinkStamp(ifnames []string, nics []nicinfo.NIC, neigh map[string]lld // the owning container and (opt-in) nsid, and copies the static uplink columns. // All lookups are O(1) and no-op when their enricher is disabled. func (x *XTCP) applyEnrichment(r *xtcp_flat_record.XtcpFlatRecord) { - x.uplinkStamp.apply(r) + if s := x.uplinkStamp.Load(); s != nil { + s.apply(r) + } if x.dockerIndex != nil { if c, ok := x.dockerIndex.Lookup(r.NetnsInode); ok { diff --git a/pkg/xtcp/enrich_uplinks_refresh_test.go b/pkg/xtcp/enrich_uplinks_refresh_test.go index 6768ef78b..78e103648 100644 --- a/pkg/xtcp/enrich_uplinks_refresh_test.go +++ b/pkg/xtcp/enrich_uplinks_refresh_test.go @@ -116,7 +116,7 @@ func TestRefreshUplinksOnce(t *testing.T) { t.Run(tc.name, func(t *testing.T) { f := &fakeUplinks{routes: tc.routes, physical: tc.physical} x := uplinkFixture(t, f) - x.initUplinkEnrichers(context.Background()) + x.initUplinkEnrichers(t.Context()) current := tc.routes[0] f.mu.Lock() @@ -182,7 +182,7 @@ func TestRefreshUplinksLoop(t *testing.T) { t.Run(tc.name, func(t *testing.T) { f := &fakeUplinks{routes: [][]string{{"eth0", "eth1"}, {"eth1", "eth0"}, {"eth0", "eth1"}}} x := uplinkFixture(t, f) - x.initUplinkEnrichers(context.Background()) + x.initUplinkEnrichers(t.Context()) ctx, cancel := context.WithCancel(context.Background()) tick := make(chan time.Time) @@ -212,7 +212,7 @@ func TestRefreshUplinksLoop(t *testing.T) { func TestUplinkStampConcurrent(t *testing.T) { f := &fakeUplinks{routes: [][]string{{"eth0", "eth1"}}} x := uplinkFixture(t, f) - x.initUplinkEnrichers(context.Background()) + x.initUplinkEnrichers(t.Context()) ctx, cancel := context.WithCancel(context.Background()) defer cancel() diff --git a/pkg/xtcp/xtcp.go b/pkg/xtcp/xtcp.go index 22869de29..38ab2617a 100644 --- a/pkg/xtcp/xtcp.go +++ b/pkg/xtcp/xtcp.go @@ -125,12 +125,14 @@ type XTCP struct { // each degrades to leaving its columns empty). See enrich.go. // // dockerIndex maps a socket's netns inode -> owning container (per-namespace, - // kept fresh by a background goroutine). uplinkStamp holds the static - // per-boot NIC + LLDP topology columns, precomputed once at startup and - // copied into every record. nsidByInode is the opt-in nsid snapshot, rebuilt + // kept fresh by a background goroutine). uplinkStamp holds the uplinks' + // NIC + LLDP columns, built at startup, replaced whole when a refresh + // finds the uplinks changed, and copied into every record; uplinkSrc is + // where they are read from (zero = the real sources). nsidByInode is the opt-in nsid snapshot, rebuilt // each discovery cycle and read lock-free on the stamping path. dockerIndex *dockermeta.Index - uplinkStamp uplinkStamp + uplinkStamp atomic.Pointer[uplinkStamp] + uplinkSrc uplinkSources nsidByInode atomic.Pointer[map[uint64]int32] // The two compile-time-gated enrichers. Both are interfaces, and both are From 6cc07a29cab650b110b230a9f11c366b1dcceb48 Mon Sep 17 00:00:00 2001 From: "randomizedcoder dave.seddon.ca@gmail.com" Date: Thu, 26 Nov 2026 22:38:40 -0800 Subject: [PATCH 3/5] test(xtcp2): flag golden for the localityRefreshInterval help Co-Authored-By: Claude Opus 5.5 --- cmd/xtcp2/testdata/defineflags-golden.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmd/xtcp2/testdata/defineflags-golden.txt b/cmd/xtcp2/testdata/defineflags-golden.txt index 4f742dd8a..9cf257c03 100644 --- a/cmd/xtcp2/testdata/defineflags-golden.txt +++ b/cmd/xtcp2/testdata/defineflags-golden.txt @@ -78,7 +78,7 @@ listenerSignedSkewMinutes 1 HMAC UTC-minute signed token skew in minutes (0-5). lldpdSocket /run/lldpd.socket path to the lldpd control unix socket used by -enrichLldp. Falls back to LLDPD_SOCKET env. lldpdVersionHint optional lldpd version hint (e.g. "1.0.18") to disambiguate the control-protocol struct layout; empty = auto-detect. Falls back to LLDPD_VERSION_HINT env. localityEvents false with -enrichLocality, keep each namespace's locality snapshot current from rtnetlink link/address/route notifications (one listener per namespace) so a change shows within about a second; -localityRefreshInterval then becomes a backstop resync. Ignored without -enrichLocality. Falls back to LOCALITY_EVENTS env. -localityRefreshInterval 1m0s how often -enrichLocality re-dumps every namespace's addresses/routes on the reconcile path (new namespaces are always dumped on the next reconcile; failed or loopback-only namespaces retry on a 30s-5m backoff); 0 = discover each namespace once, never refresh. Falls back to LOCALITY_REFRESH_INTERVAL env. +localityRefreshInterval 1m0s how often -enrichLocality re-dumps every namespace's addresses/routes on the reconcile path (new namespaces are always dumped on the next reconcile; failed or loopback-only namespaces retry on a 30s-5m backoff); 0 = discover each namespace once, never refresh. Auto-detected uplinks (no -uplinkInterfaces) are re-read on the same interval. Falls back to LOCALITY_REFRESH_INTERVAL env. location deployment grouping/facility this daemon runs in (data center, PoP, region, site, …); stamped on every record's `location`. Falls back to LOCATION env. marshal protobufList Marshaling of the exported data (protobufList, protoJson, protoText, msgpack, jsonl, csv, tsv) maxDumpBytes 268435456 cap on the bytes of one namespace's inet_diag dump per poll; packets past it are drained undecoded and counted in xtcp_dump_dropped_total{reason="bytes"}. 0 = unlimited. Falls back to MAX_DUMP_BYTES env. From 2b938fdf6a3f51c84d2158c5dce2963450e820ee Mon Sep 17 00:00:00 2001 From: "randomizedcoder dave.seddon.ca@gmail.com" Date: Thu, 26 Nov 2026 22:40:10 -0800 Subject: [PATCH 4/5] test(golden): uplink_follows_metric, a route swap moves the uplinks After poll 2 (the fixture) the capture moves the e1000e's default route in front of ionic0's, waits for refreshUplinks to count the change and for a poll that starts after it, and checks that poll's uplink1 is the e1000e. stop_and_fetch_second_poll takes an optional path for the newest object; with one argument it behaves as before (families). The golden collector refreshes every 5s. Co-Authored-By: Claude Opus 5.5 --- nix/microvms/mkVm.nix | 4 ++++ nix/microvms/scripts/golden-capture.sh | 22 +++++++++++++++++++++- nix/microvms/scripts/golden-common.sh | 20 ++++++++++++++------ 3 files changed, 39 insertions(+), 7 deletions(-) diff --git a/nix/microvms/mkVm.nix b/nix/microvms/mkVm.nix index 46985e075..424901efa 100644 --- a/nix/microvms/mkVm.nix +++ b/nix/microvms/mkVm.nix @@ -2422,8 +2422,12 @@ let ] # The golden flavor adds locality and ASN over goldenAsnDb; the families # check keeps the base args. + # The 5s refresh lets the capture's uplink_follows_metric row see a route + # swap re-read within a poll (refreshUplinks). ++ lib.optionals isS3ParquetGolden [ "-enrichLocality" + "-localityRefreshInterval" + "5s" "-enrichAsn" "-asnDbPath" "${goldenAsnDb}" diff --git a/nix/microvms/scripts/golden-capture.sh b/nix/microvms/scripts/golden-capture.sh index c9029c1d2..dd0ca66fb 100644 --- a/nix/microvms/scripts/golden-capture.sh +++ b/nix/microvms/scripts/golden-capture.sh @@ -68,7 +68,21 @@ done golden_ns_id=$(ip netns list | sed -n 's/^golden-ns (id: \([0-9]*\))$/\1/p') caps=$(systemctl show xtcp2 -p CapabilityBoundingSet --value) -stop_and_fetch_second_poll "$OUT/raw.parquet" +# Uplinks follow a route change (refreshUplinks): move uplink 2's default +# route (the e1000e's, metric 2048) in front of ionic0's (512), wait for +# xtcp2 to re-read the uplinks (-localityRefreshInterval 5s), then for a +# poll that starts after that. Poll 2, the fixture, was taken before the +# swap; the later poll goes to $OUT/swap.parquet for uplink_follows_metric +# and is deleted after it. +swap_dev=$(ip -j route show default via 10.0.3.2 | jq -r '.[0].dev // empty') +[ -n "$swap_dev" ] || fail "uplink swap: no default route via 10.0.3.2" +ip route add default via 10.0.3.2 dev "$swap_dev" metric 256 +ip route del default via 10.0.3.2 dev "$swap_dev" metric 2048 +wait_for uplinks changed 1 30 +wait_for envelopeFlush poll_end "$(($(metric envelopeFlush poll_end) + 1))" 60 +stop_and_fetch_second_poll "$OUT/raw.parquet" "$OUT/swap.parquet" +ip route add default via 10.0.3.2 dev "$swap_dev" metric 2048 +ip route del default via 10.0.3.2 dev "$swap_dev" metric 256 P="read_parquet('$OUT/raw.parquet')" rows=$(q "SELECT count(*) FROM $P") @@ -352,6 +366,12 @@ got=$(q "SELECT concat_ws(',', max(uplink2_nic_driver), max(uplink2_nic_pci_vend ok=0 [ "$got" = "e1000e,32902,true,true" ] && ok=1 row uplink2 positive "$ok" "uplink2 driver, PCI vendor, firmware set, bus set: $got" +S="read_parquet('$OUT/swap.parquet')" +got=$(q "SELECT concat_ws(',', string_agg(DISTINCT uplink1_nic_driver, '/'), string_agg(DISTINCT uplink2_nic_driver, '/')) FROM $S") +ok=0 +[ "$got" = "e1000e,ionic" ] && ok=1 +row uplink_follows_metric positive "$ok" "uplink1, uplink2 drivers in a poll after $swap_dev's default route moved to metric 256: $got" +rm -f "$OUT/swap.parquet" n=$(q "SELECT count(*) FROM $P WHERE uplink1_nic_driver = 'virtio_net' OR uplink2_nic_driver = 'virtio_net'") ok=0 [ "$n" -eq 0 ] && ok=1 diff --git a/nix/microvms/scripts/golden-common.sh b/nix/microvms/scripts/golden-common.sh index 73de975c9..c0cf766dd 100644 --- a/nix/microvms/scripts/golden-common.sh +++ b/nix/microvms/scripts/golden-common.sh @@ -59,19 +59,27 @@ wait_second_poll() { fail "expected two poll_end and no poll_timeout, got $ends and $timeouts" } -# stop_and_fetch_second_poll stops xtcp2 (Close uploads poll 2's object) -# and downloads that object, the newer of the two, to $1. +# stop_and_fetch_second_poll stops xtcp2 (Close uploads the last poll's +# object) and downloads poll 2's object, the second oldest, to $1. With no +# $2 there must be exactly two objects; with $2, xtcp2 was left running for +# more polls: there must be at least three, and the newest goes to $2. stop_and_fetch_second_poll() { systemctl stop xtcp2 - local listing="" count second + local listing="" count second want=2 + if [ -n "${2:-}" ]; then want=3; fi for _ in $(seq 1 30); do listing=$(rclone lsf -R --files-only --include '*.parquet' --format tp --separator ' ' "s3:$BUCKET" 2>/dev/null || true) - if [ "$(printf '%s' "$listing" | grep -c . || true)" -ge 2 ]; then break; fi + if [ "$(printf '%s' "$listing" | grep -c . || true)" -ge "$want" ]; then break; fi sleep 1 done count=$(printf '%s' "$listing" | grep -c . || true) - [ "$count" -eq 2 ] || fail "expected 2 objects (polls 1 and 2), got $count" - second=$(printf '%s\n' "$listing" | sort | tail -n1 | awk '{print $NF}') + if [ -z "${2:-}" ]; then + [ "$count" -eq 2 ] || fail "expected 2 objects (polls 1 and 2), got $count" + else + [ "$count" -ge 3 ] || fail "expected at least 3 objects (polls 1, 2 and later), got $count" + rclone copyto "s3:$BUCKET/$(printf '%s\n' "$listing" | sort | tail -n1 | awk '{print $NF}')" "$2" || fail "download failed" + fi + second=$(printf '%s\n' "$listing" | sort | sed -n 2p | awk '{print $NF}') rclone copyto "s3:$BUCKET/$second" "$1" || fail "download failed" } From fe223a02a0ab8723b652c0401f9a1da437e3c20f Mon Sep 17 00:00:00 2001 From: "randomizedcoder dave.seddon.ca@gmail.com" Date: Thu, 26 Nov 2026 23:15:32 -0800 Subject: [PATCH 5/5] docs: the uplink TODO is done Co-Authored-By: Claude Opus 5.5 --- docs/design-rocm-ernic-tests.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/design-rocm-ernic-tests.md b/docs/design-rocm-ernic-tests.md index 6ece07e39..88e5d983d 100644 --- a/docs/design-rocm-ernic-tests.md +++ b/docs/design-rocm-ernic-tests.md @@ -186,7 +186,7 @@ Any column that comes out exactly equal also gets a goldenrec unit row (`pkg/gol - **A dropped SYN (found later):** in 2 of 12 captures `oracle_segs_out` was 1 or 2 short, while the kernel's own sum (`ss`, printed beside xtcp2's) agreed with xtcp2. The pcap on tap-ionic0 showed one SYN with no reply, and a new connection from another port 1 s later. ionic1 had dropped the SYN (every 64th frame). tcp_client's 1 s dial timeout then closed that socket just as the kernel's first SYN retransmit came due (`TCP_TIMEOUT_INIT`, include/net/tcp.h:174), and the closed socket's `segs_out` was lost. The ernic clients now use `-dialTimeout 30s`, so the kernel resends the SYN on the same socket. - **Dropped rows:** `retrans_covers_drops` and `bytes_retrans_mss` were not added. The bulk transfers are echoes, so some dropped frames are pure ACKs for the echoed data, and TCP never retransmits those. Retransmits can therefore be fewer than the drops. - **netem `loss_seen`:** the row's detail now reports netem's own drop count per namespace (`tc -s qdisc`). No failure has happened since, so the cause is still open (TODO). -- **Uplinks (phase 6):** `DefaultUplinks` trusts the kernel's listing order (ascending metric), puts IPv4 before IPv6, and runs once at startup (pkg/xtcp/enrich.go). `TestDefaultUplinksMetric` pins that behavior. TODO: the uplink columns don't follow a runtime metric change until xtcp2 restarts. Egress and locality refresh every 60 s, so only the uplinks lag. +- **Uplinks (phase 6):** `DefaultUplinks` trusts the kernel's listing order (ascending metric), puts IPv4 before IPv6, and runs once at startup (pkg/xtcp/enrich.go). `TestDefaultUplinksMetric` pins that behavior. Done in round 4: auto-detected uplinks are re-read every `locality_refresh_interval` (`refreshUplinks`; unchanged lists cost one `/proc` read, the stamp is swapped whole), so a metric swap moves them with egress and locality. The golden capture's `uplink_follows_metric` row swaps the e1000e's route in front of ionic0's after poll 2 and checks a later poll. `applyEnrichment` with the atomic stamp: 18.2 to 20.1 ns/op against 17.9 to 18.2 before (host load 5 to 9), 0 allocs. - **Keepalive probe in flight (diff flake, TODO):** in one of five captures, `xtcp2-golden diff` reported an idle `golden-cc-a` connection with `inet_diag_msg_retrans` 1 and `tcp_info_probes` 1, but `total_retrans` 0 and nothing unacked. The poll caught Go's default 15 s keepalive probe before its ACK: the probe sets `icsk_probes_out` (net/ipv4/tcp_timer.c:844), `tcp_ack` clears it (net/ipv4/tcp_input.c:4430), and inet_diag reports it as `idiag_retrans` while the keepalive timer is pending (net/ipv4/inet_diag.c:295). This predates this work. A fix is `-keepalive 1h` on the idle workloads: the keepalive timer still shows (`inet_diag_msg_timer` 2), but no probe is sent during a capture. - **Captures:** five, all 47 rows PASS on each (one at host load 18.6), with the oracle exact on all four NICs every time. `xtcp2-golden diff` is clean between captures 1, 3, 4 and 5; capture 2 differs only by the keepalive probe above. The sequence flow sent about 3100 frames with 12 drops, retransmitted 11 or 12 times (an 11 means one drop was a pure ACK), and never had an RTO, so `seq_no_rto` is asserted. - **After the SYN fix:** eight more captures with a pcap on tap-ionic0. In seven, every row passed and the oracle was exact on all four NICs. The eighth failed only `loss_seen`, the netem TODO above, and aborted before the oracle ran.