diff --git a/net/tstun/subnetmetrics.go b/net/tstun/subnetmetrics.go index eaeb3d333..28da4ca21 100644 --- a/net/tstun/subnetmetrics.go +++ b/net/tstun/subnetmetrics.go @@ -4,12 +4,15 @@ package tstun import ( + "cmp" "expvar" "net/netip" + "slices" "sync/atomic" "github.com/gaissmai/bart" "tailscale.com/feature/buildfeatures" + "tailscale.com/net/tsaddr" "tailscale.com/util/clientmetric" "tailscale.com/util/usermetric" ) @@ -35,6 +38,16 @@ const ( packetsHelp = "Packets forwarded on behalf of tailnet peers for each advertised subnet route. " + `Direction is from the subnet router's point of view: "tx" was sent into the subnet, ` + `"rx" was received from the subnet and returned to the peer.` + + // maxRetainedRoutes caps how many routes' counters are kept alive for the + // process's lifetime; see subnetCounters.counters for why retention is + // needed and evictRetainedLocked for what happens past the cap. + // + // A subnet router's advertised set is admin-configured and small; the cap + // only matters if it churns unexpectedly. 4 KiB of routeCounters is a few + // hundred KiB, and at the cap the labeled series are still bounded by the + // advertised set, not by this. + maxRetainedRoutes = 4096 ) // Aggregate node-level clientmetrics, registered over the same [expvar.Int] @@ -57,6 +70,11 @@ type routeCounters struct { rxBytes expvar.Int txPackets expvar.Int rxPackets expvar.Int + + // lastActiveSeq is the value of subnetCounters.seq when this route was + // last advertised. Eviction drops the least recently advertised routes + // first. Only ever accessed from setRoutes. + lastActiveSeq uint64 } // add records a packet of size bytes in the given direction. @@ -78,6 +96,12 @@ func (rc *routeCounters) add(bytes int, rx bool) { // lookup plus atomic adds: no allocation, no label formatting, and no map // hashing per packet. // +// A subnetCounters lives for the lifetime of the [Wrapper] once created, even +// while the feature is disabled: the aggregate clientmetrics it registers +// values with cannot be unregistered individually, and both metric views are +// counters, which must never decrease. Disabling clears the lookup table +// instead, which is what the packet path checks. +// // It is not safe to call setRoutes concurrently with itself; the engine calls // it only from Reconfig. Lookups are safe concurrently with setRoutes. type subnetCounters struct { @@ -87,23 +111,38 @@ type subnetCounters struct { // table maps an address to the counters for the most specific advertised // route containing it. setRoutes swaps in a wholly new table rather than // mutating the published one, so the packet path needs no locking. + // + // It is nil when no countable route is advertised, which is how the packet + // path skips its work: see [Wrapper.subnetCountersActive]. table atomicPrefixTable - // counters holds the counters for every route advertised during this - // process's lifetime, including withdrawn ones. + // counters holds the counters for every route advertised recently, + // including withdrawn ones, up to maxRetainedRoutes entries. // - // Entries are never removed. Withdrawn routes must stay registered with - // the aggregate clientmetrics, because those are counters and dropping a - // route's contribution would make them decrease. Retaining the entry also - // means a route that is withdrawn and later re-advertised resumes its - // previous total instead of resetting. The labeled usermetric series *are* - // removed on withdrawal, so per-route cardinality tracks the advertised - // set. Only ever accessed from setRoutes. + // Withdrawn routes are retained because they must stay registered with the + // aggregate clientmetrics: those are counters, and dropping a route's + // contribution would make them decrease. Retaining the entry also means a + // route that is withdrawn and later re-advertised resumes its previous + // total instead of resetting. The labeled usermetric series *are* removed + // on withdrawal, so per-route cardinality tracks the advertised set. + // + // Only ever accessed from setRoutes. counters map[netip.Prefix]*routeCounters + // evicted accumulates the totals of routes dropped from counters once it + // reached maxRetainedRoutes. It stays registered with the aggregates + // forever, so eviction preserves their value; only the per-route breakdown + // of those bytes is lost, and an evicted route has not been advertised for + // at least maxRetainedRoutes reconfigs. Only ever accessed from setRoutes. + evicted routeCounters + // active is the set of currently advertised routes, i.e. those with live // labeled series. Only ever accessed from setRoutes. active map[netip.Prefix]bool + + // seq increments on every setRoutes call and orders routes by how recently + // they were advertised, for eviction. Only ever accessed from setRoutes. + seq uint64 } // atomicPrefixTable is an atomically-swappable longest-prefix-match table. @@ -117,13 +156,13 @@ func (a *atomicPrefixTable) store(t *bart.Table[*routeCounters]) { } // newSubnetCounters returns a subnetCounters that publishes its per-route -// series into reg. +// series into reg. It starts with no routes, i.e. inactive. func newSubnetCounters(reg *usermetric.Registry) *subnetCounters { sc := &subnetCounters{ counters: map[netip.Prefix]*routeCounters{}, active: map[netip.Prefix]bool{}, } - sc.table.store(&bart.Table[*routeCounters]{}) + sc.registerAggregate(&sc.evicted) if buildfeatures.HasUserMetrics { sc.bytesTotal = usermetric.NewMultiLabelMapWithRegistry[subnetRouteLabels]( reg, "tailscaled_subnet_forwarded_bytes_total", "counter", bytesHelp) @@ -139,12 +178,39 @@ func newSubnetCounters(reg *usermetric.Registry) *subnetCounters { // exit-node traffic to 0.0.0.0/0 would be misleading. This mirrors the // Bits() > 0 check the network flow logger uses when classifying subnet // traffic. -func countableRoute(p netip.Prefix) bool { return p.IsValid() && p.Bits() > 0 } +// +// 4via6 routes are excluded too, for M1. Their prefixes live inside +// fd7a:115c:a1e0::/48, so both endpoints of 4via6 traffic are Tailscale +// addresses and countSubnetRouteTraffic's "exactly one Tailscale endpoint" +// test never admits such a packet. Admitting the route anyway would publish +// four series that can never move, which reads to an operator as an idle +// router rather than an unsupported route type. Counting 4via6 properly needs +// attribution on the translated v4 address, which is a later milestone. +func countableRoute(p netip.Prefix) bool { + return p.IsValid() && p.Bits() > 0 && !tsaddr.IsViaPrefix(p) +} + +// anyCountableRoute reports whether routes contains at least one route that +// would get counters, i.e. whether counting should be active at all. +func anyCountableRoute(routes []netip.Prefix) bool { + for _, p := range routes { + if countableRoute(p) { + return true + } + } + return false +} // setRoutes updates the set of advertised routes being counted. +// +// Passing no countable routes deactivates counting without discarding any +// retained totals: the lookup table is cleared and the labeled series are +// removed, but the [expvar.Int] values stay registered with the aggregates so +// neither metric view decreases. func (sc *subnetCounters) setRoutes(routes []netip.Prefix) { + sc.seq++ next := make(map[netip.Prefix]bool, len(routes)) - tbl := &bart.Table[*routeCounters]{} + var tbl *bart.Table[*routeCounters] for _, p := range routes { if !countableRoute(p) { @@ -160,10 +226,14 @@ func (sc *subnetCounters) setRoutes(routes []netip.Prefix) { sc.counters[p] = rc sc.registerAggregate(rc) } + rc.lastActiveSeq = sc.seq if !sc.active[p] { sc.setSeries(p, rc) } next[p] = true + if tbl == nil { + tbl = &bart.Table[*routeCounters]{} + } tbl.Insert(p, rc) } @@ -175,9 +245,58 @@ func (sc *subnetCounters) setRoutes(routes []netip.Prefix) { } sc.active = next + sc.evictRetained() sc.table.store(tbl) } +// evictRetained drops the least recently advertised retained routes once +// counters exceeds maxRetainedRoutes, folding their totals into sc.evicted so +// that the aggregate clientmetrics keep their value. +// +// Currently advertised routes are never evicted: the cap is on retention of +// withdrawn routes, and the advertised set is bounded by admin configuration. +func (sc *subnetCounters) evictRetained() { + if len(sc.counters) <= maxRetainedRoutes { + return + } + // Evict down to half the cap so this runs amortized-rarely rather than on + // every reconfig once at the cap. + target := maxRetainedRoutes / 2 + type candidate struct { + p netip.Prefix + seq uint64 + } + cands := make([]candidate, 0, len(sc.counters)) + for p, rc := range sc.counters { + if sc.active[p] { + continue + } + cands = append(cands, candidate{p, rc.lastActiveSeq}) + } + // Oldest first. + slices.SortFunc(cands, func(a, b candidate) int { return cmp.Compare(a.seq, b.seq) }) + for _, c := range cands { + if len(sc.counters) <= target { + break + } + rc := sc.counters[c.p] + // Fold the evicted totals into the residual counter, which stays + // registered with the aggregates, then drop the entry. rc's own values + // are still in the aggregates' registered set with no way to remove + // them, so zero them out to avoid double counting: nothing references + // rc after this, so no further adds can land on it. + sc.evicted.txBytes.Add(rc.txBytes.Value()) + sc.evicted.rxBytes.Add(rc.rxBytes.Value()) + sc.evicted.txPackets.Add(rc.txPackets.Value()) + sc.evicted.rxPackets.Add(rc.rxPackets.Value()) + rc.txBytes.Set(0) + rc.rxBytes.Set(0) + rc.txPackets.Set(0) + rc.rxPackets.Set(0) + delete(sc.counters, c.p) + } +} + // registerAggregate adds rc's counters to the node-level clientmetrics. func (sc *subnetCounters) registerAggregate(rc *routeCounters) { if !buildfeatures.HasClientMetrics { @@ -214,9 +333,14 @@ func (sc *subnetCounters) deleteSeries(p netip.Prefix) { } // forAddr returns the counters for the most specific advertised route -// containing addr, or nil if addr is not within any advertised route. +// containing addr, or nil if addr is not within any advertised route or +// counting is currently inactive. func (sc *subnetCounters) forAddr(addr netip.Addr) *routeCounters { - rc, _ := sc.table.load().Lookup(addr) + tbl := sc.table.load() + if tbl == nil { + return nil + } + rc, _ := tbl.Lookup(addr) return rc } @@ -229,3 +353,21 @@ func (sc *subnetCounters) forRoute(p netip.Prefix) *routeCounters { } return sc.counters[p] } + +// retainedForRoute returns the counters retained for exactly p whether or not +// it is currently advertised, or nil if p has never been advertised (or was +// evicted). For tests. +func (sc *subnetCounters) retainedForRoute(p netip.Prefix) *routeCounters { + return sc.counters[p.Masked()] +} + +// aggregateTxBytesForTest returns the sum of tx bytes across every retained +// route plus the residual from evicted ones, i.e. what the aggregate +// clientmetric should read for this instance. +func (sc *subnetCounters) aggregateTxBytesForTest() int64 { + total := sc.evicted.txBytes.Value() + for _, rc := range sc.counters { + total += rc.txBytes.Value() + } + return total +} diff --git a/net/tstun/subnetmetrics_test.go b/net/tstun/subnetmetrics_test.go index 06bf2da08..9a4f55a14 100644 --- a/net/tstun/subnetmetrics_test.go +++ b/net/tstun/subnetmetrics_test.go @@ -4,10 +4,14 @@ package tstun import ( + "expvar" + "fmt" "net/netip" "testing" tsmetrics "tailscale.com/metrics" + "tailscale.com/net/packet" + "tailscale.com/net/tsaddr" "tailscale.com/util/eventbus/eventbustest" "tailscale.com/util/usermetric" ) @@ -205,16 +209,372 @@ func TestSubnetCountersNoAllocs(t *testing.T) { } } +// TestSubnetCountersDisableEnableCycle checks that toggling the feature off and +// back on does not reset the labeled counters. Prometheus counters must never +// decrease: a reset produces a phantom rate() spike and false alerts. +// +// tailscale down/up, a profile switch, and Reconfig(&router.Config{}) from +// enterStateLocked all drive an empty route set through this path. +func TestSubnetCountersDisableEnableCycle(t *testing.T) { + bus := eventbustest.NewBus(t) + _, tun := newFakeTUN(t.Logf, bus, false) + defer tun.Close() + + routes := []netip.Prefix{netip.MustParsePrefix("10.1.0.0/16")} + tun.SetSubnetRoutes(routes) + sc := tun.subnetCounters() + if sc == nil { + t.Fatal("counting disabled after SetSubnetRoutes") + } + sc.forAddr(netip.MustParseAddr("10.1.2.3")).add(1000000, false) + + // The labeled series and the aggregates must agree here, before the toggle. + if got := labeledSeriesValue(t, sc, "10.1.0.0/16", directionTx, true); got != 1000000 { + t.Fatalf("labeled tx_bytes before the toggle = %d, want 1000000", got) + } + + // Disable, then re-enable with the same route. + tun.SetSubnetRoutes(nil) + tun.SetSubnetRoutes(routes) + + sc2 := tun.subnetCounters() + if sc2 == nil { + t.Fatal("counting disabled after re-enabling") + } + if got := labeledSeriesValue(t, sc2, "10.1.0.0/16", directionTx, true); got != 1000000 { + t.Errorf("labeled tx_bytes after a disable/enable cycle = %d, want 1000000 retained "+ + "(a Prometheus counter must never decrease)", got) + } + if txBytes, _, _, _ := routeCountsFor(t, sc2, "10.1.0.0/16"); txBytes != 1000000 { + t.Errorf("route tx_bytes after a disable/enable cycle = %d, want 1000000 retained", txBytes) + } +} + +// labeledSeriesValue returns the value published under the given labels, or -1 +// if there is no such series. +func labeledSeriesValue(t *testing.T, sc *subnetCounters, route, direction string, bytes bool) int64 { + t.Helper() + m := sc.packetsTotal + if bytes { + m = sc.bytesTotal + } + got := int64(-1) + m.Do(func(kv tsmetrics.KeyValue[subnetRouteLabels]) { + if kv.Key.Route != route || kv.Key.Direction != direction { + return + } + iv, ok := kv.Value.(*expvar.Int) + if !ok { + t.Fatalf("series %v/%v has value type %T, want *expvar.Int", route, direction, kv.Value) + } + got = iv.Value() + }) + return got +} + +// TestSubnetCountersDisabledCountsNothing checks that while the feature is +// disabled no traffic is counted, and that withdrawn routes' labeled series are +// removed even though their totals are retained. +func TestSubnetCountersDisabledCountsNothing(t *testing.T) { + bus := eventbustest.NewBus(t) + _, tun := newFakeTUN(t.Logf, bus, false) + defer tun.Close() + + routes := []netip.Prefix{netip.MustParsePrefix("10.1.0.0/16")} + tun.SetSubnetRoutes(routes) + sc := tun.subnetCounters() + pkt := udp4("100.64.0.1", "10.1.2.3", 123, 456) + if _, err := tun.tdevWrite([][]byte{pkt}, 0); err != nil { + t.Fatalf("tdevWrite: %v", err) + } + _, _, want, _ := routeCountsFor(t, sc, "10.1.0.0/16") + if want != 1 { + t.Fatalf("txPackets while enabled = %d, want 1", want) + } + + tun.SetSubnetRoutes(nil) + + // Nothing is counted while disabled, and no series remain published. + for range 5 { + if _, err := tun.tdevWrite([][]byte{pkt}, 0); err != nil { + t.Fatalf("tdevWrite: %v", err) + } + } + if got := seriesCount(sc); got != 0 { + t.Errorf("series count while disabled = %d, want 0", got) + } + // forRoute reports only advertised routes, so the withdrawn one is gone + // from there; the retained totals must be untouched by the 5 packets. + if got := sc.forRoute(netip.MustParsePrefix("10.1.0.0/16")); got != nil { + t.Error("a withdrawn route still resolves via forRoute") + } + rc := sc.retainedForRoute(netip.MustParsePrefix("10.1.0.0/16")) + if rc == nil { + t.Fatal("the withdrawn route's counters were discarded, not retained") + } + if got := rc.txPackets.Value(); got != 1 { + t.Errorf("retained txPackets after 5 packets while disabled = %d, want still 1", got) + } +} + +// TestSubnetCountersNoAggregateLeak checks that repeatedly enabling and +// disabling does not leak expvar values into the process-global aggregate +// clientmetrics. AggregateCounter has no unregister-one API and Value() is +// O(n) over the registered set, on every scrape and every logtail delta. +func TestSubnetCountersNoAggregateLeak(t *testing.T) { + bus := eventbustest.NewBus(t) + _, tun := newFakeTUN(t.Logf, bus, false) + defer tun.Close() + + routes := []netip.Prefix{netip.MustParsePrefix("10.1.0.0/16")} + tun.SetSubnetRoutes(routes) + base := aggregateRegisteredCount() + + for range 10 { + tun.SetSubnetRoutes(nil) + tun.SetSubnetRoutes(routes) + } + if got := aggregateRegisteredCount() - base; got != 0 { + t.Errorf("10 disable/enable cycles registered %d additional values with the "+ + "aggregate clientmetrics, want 0", got) + } +} + +// aggregateRegisteredCount returns how many expvar values are registered with +// the four aggregate clientmetrics. +func aggregateRegisteredCount() int { + return cMetricSubnetForwardedTxBytes.RegisteredCountForTest() + + cMetricSubnetForwardedRxBytes.RegisteredCountForTest() + + cMetricSubnetForwardedTxPackets.RegisteredCountForTest() + + cMetricSubnetForwardedRxPackets.RegisteredCountForTest() +} + +// TestSubnetCountersRetentionBound checks that the retained-counter map is +// bounded. Retention is deliberate (a withdrawn route must keep contributing to +// the aggregates, which are counters) but unbounded retention lets an +// unexpectedly churning route set grow memory without limit. +func TestSubnetCountersRetentionBound(t *testing.T) { + sc := newSubnetCounters(new(usermetric.Registry)) + + // Churn far more distinct routes than the cap, counting a byte on each so + // that eviction has to preserve something. + const n = maxRetainedRoutes * 3 + var wantTotal int64 + for i := range n { + p := netip.MustParsePrefix(fmt.Sprintf("10.%d.%d.0/24", i/256, i%256)) + sc.setRoutes([]netip.Prefix{p}) + sc.forAddr(p.Addr().Next()).add(100, false) + wantTotal += 100 + } + + if got := len(sc.counters); got > maxRetainedRoutes { + t.Errorf("after %d single-route reconfigs, retained %d routeCounters, want at most %d", + n, got, maxRetainedRoutes) + } + // Eviction must not lose counted bytes: the aggregate is a counter. + if got := sc.aggregateTxBytesForTest(); got != wantTotal { + t.Errorf("total tx bytes across retained plus evicted = %d, want %d "+ + "(eviction must not make the aggregate decrease)", got, wantTotal) + } +} + +// TestSubnetCountersExitNodeOnlyNotEnabled checks that a node advertising only +// exit routes does not install the counting hook: it would publish zero series +// while paying a decode and a lookup on every packet. +func TestSubnetCountersExitNodeOnlyNotEnabled(t *testing.T) { + bus := eventbustest.NewBus(t) + _, tun := newFakeTUN(t.Logf, bus, false) + defer tun.Close() + + tun.SetSubnetRoutes([]netip.Prefix{ + netip.MustParsePrefix("0.0.0.0/0"), + netip.MustParsePrefix("::/0"), + }) + if tun.SubnetRouteCountingEnabledForTest() { + t.Error("counting is enabled for an exit-node-only route set; want disabled") + } +} + +// TestSubnetCountersViaRouteExcluded checks that 4via6 routes get no series. +// Both endpoints of 4via6 traffic are inside the Tailscale ULA range, so +// countSubnetRouteTraffic can never attribute a packet to one, and publishing +// four permanently-zero series would read as "this route is idle". +func TestSubnetCountersViaRouteExcluded(t *testing.T) { + sc := newSubnetCounters(new(usermetric.Registry)) + // 4via6 form of 10.1.0.0/16 through site 7. + via := netip.MustParsePrefix("fd7a:115c:a1e0:b1a:0:7:a01:0/112") + if !tsaddr.IsViaPrefix(via) { + t.Fatalf("%v is not a via prefix; fix the test fixture", via) + } + sc.setRoutes([]netip.Prefix{via}) + if got := seriesCount(sc); got != 0 { + t.Errorf("a 4via6 route published %d series, want 0 (they could never move)", got) + } + if sc.forAddr(via.Addr().Next()) != nil { + t.Error("a 4via6 route is present in the lookup table") + } +} + +// TestWrapperSubnetRouteCountingOwnTraffic checks that traffic the node +// originates itself toward an address inside one of its own advertised prefixes +// is not counted. Only forwarded traffic belongs in these counters, and such a +// packet has exactly one Tailscale endpoint, so the endpoint test alone admits +// it -- with the direction inverted, since it is egress being counted as rx. +func TestWrapperSubnetRouteCountingOwnTraffic(t *testing.T) { + bus := eventbustest.NewBus(t) + chtun, tun := newChannelTUN(t.Logf, bus, false) + defer tun.Close() + + const selfIP = "100.64.0.1" + tun.SetSelfTailscaleAddrs(netip.MustParseAddr(selfIP), netip.Addr{}) + tun.SetSubnetRoutes([]netip.Prefix{netip.MustParsePrefix("10.0.0.0/8")}) + sc := tun.subnetCounters() + if sc == nil { + t.Fatal("counting disabled after SetSubnetRoutes") + } + + // The node's own egress to a host inside its advertised prefix. This + // leaves via the TUN read path, where forwarded return traffic is rx. + go func() { chtun.Outbound <- udp4(selfIP, "10.1.2.3", 123, 456) }() + + var buf [MaxPacketSize]byte + buffs := [][]byte{buf[:]} + sizes := make([]int, 1) + if _, err := tun.Read(buffs, sizes, 0); err != nil { + t.Fatalf("Read: %v", err) + } + + txBytes, rxBytes, txPackets, rxPackets := routeCountsFor(t, sc, "10.0.0.0/8") + if rxPackets != 0 || rxBytes != 0 { + t.Errorf("the node's own egress was counted as rx: rxBytes=%d rxPackets=%d; want 0, 0", + rxBytes, rxPackets) + } + if txPackets != 0 || txBytes != 0 { + t.Errorf("the node's own egress was counted as tx: txBytes=%d txPackets=%d; want 0, 0", + txBytes, txPackets) + } +} + +// TestWrapperSubnetRouteCountingForwardedStillCounted is the companion to +// TestWrapperSubnetRouteCountingOwnTraffic: excluding the node's own traffic +// must not also exclude the forwarded traffic these counters exist for. +func TestWrapperSubnetRouteCountingForwardedStillCounted(t *testing.T) { + bus := eventbustest.NewBus(t) + chtun, tun := newChannelTUN(t.Logf, bus, false) + defer tun.Close() + + tun.SetSelfTailscaleAddrs(netip.MustParseAddr("100.64.0.1"), netip.Addr{}) + tun.SetSubnetRoutes([]netip.Prefix{netip.MustParsePrefix("10.0.0.0/8")}) + sc := tun.subnetCounters() + + // Forwarded: from a subnet host, to a *peer*, not to this node. + pkt := udp4("10.1.2.3", "100.64.0.2", 456, 123) + go func() { chtun.Outbound <- pkt }() + + var buf [MaxPacketSize]byte + buffs := [][]byte{buf[:]} + sizes := make([]int, 1) + if _, err := tun.Read(buffs, sizes, 0); err != nil { + t.Fatalf("Read: %v", err) + } + + _, rxBytes, _, rxPackets := routeCountsFor(t, sc, "10.0.0.0/8") + if rxPackets != 1 || rxBytes != int64(len(pkt)) { + t.Errorf("forwarded traffic: rxBytes=%d rxPackets=%d; want %d, 1", rxBytes, rxPackets, len(pkt)) + } +} + +// TestWrapperSubnetRouteCountingStalePacket checks that the Read hook does not +// attribute traffic using addresses left over from a previous packet. Parsed is +// pool-reused across the loop and Decode does not clear Src/Dst when it bails +// out early, so a hook that reads them without an IPVersion check can count a +// stale address. +func TestWrapperSubnetRouteCountingStalePacket(t *testing.T) { + bus := eventbustest.NewBus(t) + chtun, tun := newChannelTUN(t.Logf, bus, false) + defer tun.Close() + + tun.SetSelfTailscaleAddrs(netip.MustParseAddr("100.64.0.1"), netip.Addr{}) + tun.SetSubnetRoutes([]netip.Prefix{netip.MustParsePrefix("10.0.0.0/8")}) + sc := tun.subnetCounters() + + // A real forwarded packet, then a garbage one in the same batch. The + // second must not be counted against the first's route. + good := udp4("10.1.2.3", "100.64.0.2", 456, 123) + junk := []byte{0x45, 0x74, 0x63, 0x70} // decodes as IPVersion 0 + go func() { + chtun.Outbound <- good + chtun.Outbound <- junk + }() + + var bufs [2][MaxPacketSize]byte + buffs := [][]byte{bufs[0][:], bufs[1][:]} + sizes := make([]int, 2) + for range 2 { + if _, err := tun.Read(buffs, sizes, 0); err != nil { + t.Fatalf("Read: %v", err) + } + } + + _, rxBytes, _, rxPackets := routeCountsFor(t, sc, "10.0.0.0/8") + if rxPackets != 1 || rxBytes != int64(len(good)) { + t.Errorf("after one good and one undecodable packet: rxBytes=%d rxPackets=%d; want %d, 1", + rxBytes, rxPackets, len(good)) + } +} + +// TestSubnetCountersHotPathNoAllocs pins the real hooks, not just the +// forAddr+add pair, to zero allocations. A prefix.String() creeping back into +// countSubnetRouteTraffic would allocate twice per packet. +func TestSubnetCountersHotPathNoAllocs(t *testing.T) { + bus := eventbustest.NewBus(t) + _, tun := newFakeTUN(t.Logf, bus, false) + defer tun.Close() + + tun.SetSelfTailscaleAddrs(netip.MustParseAddr("100.64.0.1"), netip.Addr{}) + tun.SetSubnetRoutes(mustPrefixes(t, []string{"10.0.0.0/8", "10.1.0.0/16", "192.168.0.0/24"})) + + pkt := udp4("100.64.0.2", "10.1.2.3", 123, 456) + buf := make([]byte, PacketStartOffset+MaxPacketSize) + copy(buf[PacketStartOffset:], pkt) + + // The tdevWrite/injectedRead hook, including its decode and the active + // check the packet path actually runs. + if got := testing.AllocsPerRun(1000, func() { + if sc := tun.subnetCountersActive(); sc != nil { + tun.countSubnetRoutePacket(sc, buf[PacketStartOffset:], false) + } + }); got != 0 { + t.Errorf("countSubnetRoutePacket allocated %v times per run, want 0", got) + } + + // And the Read hook, which counts an already-decoded packet. + var p packet.Parsed + p.Decode(buf[PacketStartOffset:]) + if got := testing.AllocsPerRun(1000, func() { + if sc := tun.subnetCountersActive(); sc != nil { + tun.countSubnetRouteParsed(sc, &p, true) + } + }); got != 0 { + t.Errorf("countSubnetRouteParsed allocated %v times per run, want 0", got) + } + + // The disabled path must be free too: nodes that have not opted in pay + // only the nil check. + tun.SetSubnetRoutes(nil) + if got := testing.AllocsPerRun(1000, func() { + if sc := tun.subnetCountersActive(); sc != nil { + t.Fatal("counting is still active after SetSubnetRoutes(nil)") + } + }); got != 0 { + t.Errorf("the disabled check allocated %v times per run, want 0", got) + } +} + func BenchmarkSubnetCountersAdd(b *testing.B) { b.ReportAllocs() sc := newSubnetCounters(new(usermetric.Registry)) - sc.setRoutes([]netip.Prefix{ - netip.MustParsePrefix("10.0.0.0/8"), - netip.MustParsePrefix("10.1.0.0/16"), - netip.MustParsePrefix("192.168.0.0/24"), - netip.MustParsePrefix("172.16.0.0/12"), - netip.MustParsePrefix("10.2.0.0/16"), - }) + sc.setRoutes(benchRoutes) addr := netip.MustParseAddr("10.1.2.3") for range b.N { if rc := sc.forAddr(addr); rc != nil { @@ -223,6 +583,54 @@ func BenchmarkSubnetCountersAdd(b *testing.B) { } } +var benchRoutes = []netip.Prefix{ + netip.MustParsePrefix("10.0.0.0/8"), + netip.MustParsePrefix("10.1.0.0/16"), + netip.MustParsePrefix("192.168.0.0/24"), + netip.MustParsePrefix("172.16.0.0/12"), + netip.MustParsePrefix("10.2.0.0/16"), +} + +// BenchmarkSubnetCountersHook measures the whole per-packet hook as the write +// path runs it: the active check, the decode, the forwarded-traffic tests, the +// lookup, and the adds. +func BenchmarkSubnetCountersHook(b *testing.B) { + b.ReportAllocs() + bus := eventbustest.NewBus(b) + _, tun := newFakeTUN(b.Logf, bus, false) + defer tun.Close() + + tun.SetSelfTailscaleAddrs(netip.MustParseAddr("100.64.0.1"), netip.Addr{}) + tun.SetSubnetRoutes(benchRoutes) + + pkt := udp4("100.64.0.2", "10.1.2.3", 123, 456) + buf := make([]byte, PacketStartOffset+MaxPacketSize) + copy(buf[PacketStartOffset:], pkt) + body := buf[PacketStartOffset:] + + for range b.N { + if sc := tun.subnetCountersActive(); sc != nil { + tun.countSubnetRoutePacket(sc, body, false) + } + } +} + +// BenchmarkSubnetCountersHookDisabled measures what a node that has not opted +// in pays: the nil check and nothing else. +func BenchmarkSubnetCountersHookDisabled(b *testing.B) { + b.ReportAllocs() + bus := eventbustest.NewBus(b) + _, tun := newFakeTUN(b.Logf, bus, false) + defer tun.Close() + + pkt := udp4("100.64.0.2", "10.1.2.3", 123, 456) + for range b.N { + if sc := tun.subnetCountersActive(); sc != nil { + tun.countSubnetRoutePacket(sc, pkt, false) + } + } +} + // TestWrapperSubnetRouteCountingTx checks that traffic entering the TUN from a // tailnet peer, bound for a host inside an advertised subnet, is counted as tx: // the router is sending it into the subnet on the peer's behalf. diff --git a/net/tstun/wrap.go b/net/tstun/wrap.go index 2bd6de74a..5fd9da420 100644 --- a/net/tstun/wrap.go +++ b/net/tstun/wrap.go @@ -222,11 +222,20 @@ type Wrapper struct { connCounter syncs.AtomicValue[netlogfunc.ConnectionCounter] // subnetRouteCounters counts forwarded traffic per advertised subnet - // route. It is nil until SetSubnetRoutes is called with a non-empty set - // of routes, so nodes that are not subnet routers, and nodes that have - // not opted in, pay only a nil load on the packet path. + // route. It is nil until SetSubnetRoutes is called with at least one + // countable route, so nodes that are not subnet routers, and nodes that + // have not opted in, pay only a nil load on the packet path. + // + // Once created it stays non-nil, because it owns registrations that cannot + // be undone; use [Wrapper.subnetCountersActive] on the packet path, which + // also covers the currently-disabled case. subnetRouteCounters atomic.Pointer[subnetCounters] + // selfAddrs holds this node's own Tailscale addresses, used by the subnet + // counters to tell forwarded traffic from the node's own. Nil until + // SetSelfTailscaleAddrs is called. + selfAddrs atomic.Pointer[selfTailscaleAddrs] + captureHook syncs.AtomicValue[packet.CaptureCallback] metrics *metrics @@ -697,13 +706,15 @@ type SetIPer interface { SetIP(ipV4, ipV6 netip.Addr) error } -// SetWGConfig is called when a new NetworkMap is received. Its only -// remaining job is updating the TAP device's IP addresses; the -// per-peer route attributes arrive via [Wrapper.SetPeerRoutes]. +// SetWGConfig is called when a new NetworkMap is received. It records this +// node's own Tailscale addresses and updates the TAP device's IP addresses; +// the per-peer route attributes arrive via [Wrapper.SetPeerRoutes]. func (t *Wrapper) SetWGConfig(wcfg *wgcfg.Config) { + a4, a6 := tsaddr.FirstTailscaleAddrs(slices.All(wcfg.Addresses)) + t.SetSelfTailscaleAddrs(a4, a6) if t.isTAP { if sip, ok := t.tdev.(SetIPer); ok { - sip.SetIP(tsaddr.FirstTailscaleAddrs(slices.All(wcfg.Addresses))) + sip.SetIP(a4, a6) } } } @@ -925,12 +936,8 @@ func (t *Wrapper) Read(buffs [][]byte, sizes []int, offset int) (int, error) { // Traffic leaving the TUN toward a tailnet peer: on a subnet router // this is a response coming back out of the subnet, so it is rx. // p is already decoded here, so attribute it without re-parsing. - // - // p.TotalLen() rather than len(p.Buffer()): the buffers this path - // gets are exactly sized today, but the decoded length is the - // authoritative byte count and does not depend on that staying true. - if sc := t.subnetRouteCounters.Load(); sc != nil { - sc.countSubnetRouteTraffic(p.Src.Addr(), p.Dst.Addr(), p.TotalLen(), true) + if sc := t.subnetCountersActive(); sc != nil { + t.countSubnetRouteParsed(sc, p, true) } // Make sure to do SNAT after filtering, so that any flow tracking in @@ -1111,9 +1118,9 @@ func (t *Wrapper) injectedRead(res tunInjectedRead, outBuffs [][]byte, sizes []i } // Injected packets travel the same direction as Read: out to a tailnet // peer, i.e. rx from the subnet router's point of view. - if sc := t.subnetRouteCounters.Load(); sc != nil { + if sc := t.subnetCountersActive(); sc != nil { for i := range n { - t.countSubnetRoutePacket(outBuffs[i][offset:offset+sizes[i]], true) + t.countSubnetRoutePacket(sc, outBuffs[i][offset:offset+sizes[i]], true) } } @@ -1310,9 +1317,9 @@ func (t *Wrapper) tdevWrite(buffs [][]byte, offset int) (int, error) { } // Traffic entering the TUN from a tailnet peer: on a subnet router this is // sent onward into the subnet, so it is tx. - if sc := t.subnetRouteCounters.Load(); sc != nil { + if sc := t.subnetCountersActive(); sc != nil { for i := range buffs { - t.countSubnetRoutePacket(buffs[i][offset:], false) + t.countSubnetRoutePacket(sc, buffs[i][offset:], false) } } return t.tdev.Write(buffs, offset) @@ -1543,80 +1550,145 @@ func (t *Wrapper) SetConnectionCounter(fn netlogfunc.ConnectionCounter) { // SetSubnetRoutes sets the advertised subnet routes for which forwarded // traffic is counted, enabling per-route load metrics. // -// Passing an empty or nil slice disables counting, so callers gate the feature -// simply by not supplying routes. Counting is deliberately independent of -// network flow logging, so it works with flow logging off. +// Passing no countable routes — an empty slice, or only exit and 4via6 routes — +// disables counting, so callers gate the feature simply by not supplying +// routes. Counting is deliberately independent of network flow logging, so it +// works with flow logging off. +// +// Disabling does not discard what has been counted. Both metric views are +// counters, so a re-advertised route resumes its previous total rather than +// resetting: see [subnetCounters] for why the instance outlives a disable. func (t *Wrapper) SetSubnetRoutes(routes []netip.Prefix) { if !buildfeatures.HasUserMetrics && !buildfeatures.HasClientMetrics { return } sc := t.subnetRouteCounters.Load() if sc == nil { - if len(routes) == 0 { + if !anyCountableRoute(routes) { + // Never enabled and nothing to enable it for. Don't create the + // counters at all, so nodes that are not subnet routers, and nodes + // that have not opted in, publish no series and pay only a nil + // load on the packet path. return } sc = newSubnetCounters(t.usermetrics) t.subnetRouteCounters.Store(sc) } sc.setRoutes(routes) - if len(routes) == 0 { - t.subnetRouteCounters.Store(nil) - } } -// subnetCounters returns the active per-route counters, or nil if per-route -// counting is disabled. +// subnetCounters returns the per-route counters, or nil if they were never +// enabled. They may be present but inactive; see [Wrapper.subnetCountersActive]. func (t *Wrapper) subnetCounters() *subnetCounters { return t.subnetRouteCounters.Load() } +// subnetCountersActive returns the per-route counters if traffic should be +// counted right now, or nil if per-route counting is disabled or no countable +// route is advertised. +// +// This is the packet path's gate: two nil-able atomic loads, no decode and no +// lookup when counting is off. +func (t *Wrapper) subnetCountersActive() *subnetCounters { + sc := t.subnetRouteCounters.Load() + if sc == nil || sc.table.load() == nil { + return nil + } + return sc +} + // SubnetRouteCountingEnabledForTest reports whether per-route subnet load // metrics are currently being collected. func (t *Wrapper) SubnetRouteCountingEnabledForTest() bool { - return t.subnetRouteCounters.Load() != nil + return t.subnetCountersActive() != nil } -// countSubnetRouteTraffic attributes a packet to an advertised subnet route, -// if it is forwarded traffic for one. +// selfTailscaleAddrs holds this node's own Tailscale addresses, so that the +// subnet counters can tell traffic the node forwards from traffic it +// originates or terminates itself. +type selfTailscaleAddrs struct { + v4, v6 netip.Addr +} + +// SetSelfTailscaleAddrs tells the Wrapper this node's own Tailscale addresses. +// +// It is used only by the per-route subnet counters, to distinguish forwarded +// traffic from the node's own; a4 and a6 are typically +// [tsaddr.FirstTailscaleAddrs] of the node's wireguard config addresses. +// Callers may pass invalid addresses for either family. +func (t *Wrapper) SetSelfTailscaleAddrs(a4, a6 netip.Addr) { + if old := t.selfAddrs.Load(); old != nil && old.v4 == a4 && old.v6 == a6 { + return + } + t.selfAddrs.Store(&selfTailscaleAddrs{v4: a4, v6: a6}) +} + +// isSelfTailscaleAddr reports whether a is one of this node's own Tailscale +// addresses. +// +// It reports false when the addresses are unknown, which counts a packet the +// same way it was counted before the addresses were plumbed through. In +// practice they are set alongside the routes, from the same Reconfig. +func (t *Wrapper) isSelfTailscaleAddr(a netip.Addr) bool { + s := t.selfAddrs.Load() + return s != nil && (a == s.v4 || a == s.v6) +} + +// IsSelfTailscaleAddrForTest reports whether the Wrapper considers a to be one +// of this node's own Tailscale addresses. +func (t *Wrapper) IsSelfTailscaleAddrForTest(a netip.Addr) bool { + return t.isSelfTailscaleAddr(a) +} + +// countSubnetRouteParsed attributes an already-decoded packet to an advertised +// subnet route, if it is traffic this node forwards on a peer's behalf. // // rx reports the direction from the subnet router's point of view: true when // the packet was received from the subnet on its way to a tailnet peer, false // when it is being sent into the subnet on a peer's behalf. // -// Only traffic with exactly one Tailscale endpoint is counted: that is what -// makes it forwarded traffic rather than the node's own. Addresses outside -// every advertised route are not counted, which excludes exit node traffic. -func (sc *subnetCounters) countSubnetRouteTraffic(src, dst netip.Addr, bytes int, rx bool) { +// Addresses outside every advertised route are not counted, which excludes exit +// node traffic. +func (t *Wrapper) countSubnetRouteParsed(sc *subnetCounters, p *packet.Parsed, rx bool) { + if p.IPVersion == 0 { + // Decode bailed out. Src and Dst are not cleared on that path and p is + // pool-reused across packets, so they may hold a previous packet's + // addresses; counting them would attribute traffic to the wrong route. + return + } + src, dst := p.Src.Addr(), p.Dst.Addr() srcIsTS := tsaddr.IsTailscaleIP(src) dstIsTS := tsaddr.IsTailscaleIP(dst) if srcIsTS == dstIsTS { + // Both endpoints on the tailnet, or neither: not subnet forwarding. return } - remote := dst + remote, tailnetEnd := dst, src if dstIsTS { - remote = src + remote, tailnetEnd = src, dst + } + // Exactly one Tailscale endpoint is necessary but not sufficient: it is + // equally true of traffic the node itself originates toward, or receives + // from, a host inside one of its own advertised prefixes. Requiring the + // tailnet end to be a *peer* is what makes the packet forwarded — and + // keeps the node's own traffic from being counted in the opposite + // direction from the one it actually travelled. + if t.isSelfTailscaleAddr(tailnetEnd) { + return } if rc := sc.forAddr(remote); rc != nil { - rc.add(bytes, rx) + // p.TotalLen(), not len(p.Buffer()): the buffer may have trailing + // slack, e.g. the full-MTU buffers wireguard-go hands Write. + rc.add(p.TotalLen(), rx) } } // countSubnetRoutePacket decodes just enough of b to attribute it to an -// advertised subnet route. It is a no-op when per-route counting is disabled. -func (t *Wrapper) countSubnetRoutePacket(b []byte, rx bool) { - sc := t.subnetRouteCounters.Load() - if sc == nil { - return - } +// advertised subnet route. +func (t *Wrapper) countSubnetRoutePacket(sc *subnetCounters, b []byte, rx bool) { var p packet.Parsed p.Decode(b) - if p.IPVersion == 0 { - return - } - // p.TotalLen(), not len(b): b may have trailing slack. wireguard-go hands - // Write a full-MTU buffer per packet, so buffs[i][offset:] in tdevWrite - // runs to the end of that buffer rather than to the end of the packet. - sc.countSubnetRouteTraffic(p.Src.Addr(), p.Dst.Addr(), p.TotalLen(), rx) + t.countSubnetRouteParsed(sc, &p, rx) } var ( diff --git a/util/clientmetric/clientmetric.go b/util/clientmetric/clientmetric.go index 98068b9fa..6df8b0976 100644 --- a/util/clientmetric/clientmetric.go +++ b/util/clientmetric/clientmetric.go @@ -280,6 +280,17 @@ func (c *AggregateCounter) Register(counter *expvar.Int) { c.counters.Add(counter) } +// RegisteredCountForTest returns how many counters are registered with c. +// +// Value() is O(this), on every scrape and every logtail delta, so callers that +// register counters over a process's lifetime use it to assert they aren't +// leaking. There is no unregister-one API. +func (c *AggregateCounter) RegisteredCountForTest() int { + c.mu.RLock() + defer c.mu.RUnlock() + return len(c.counters) +} + // UnregisterAll unregisters all counters resulting in it // starting back down at zero. This is to ensure monotonicity // and respect the semantics of the counter. diff --git a/util/clientmetric/omit.go b/util/clientmetric/omit.go index 74018f12a..fb7c86d98 100644 --- a/util/clientmetric/omit.go +++ b/util/clientmetric/omit.go @@ -13,6 +13,8 @@ func (*Metric) Value() int64 { return 0 } func (*Metric) Register(expvarInt any) {} func (*Metric) UnregisterAll() {} +func (*Metric) RegisteredCountForTest() int { return 0 } + type MetricUpdate struct { Name string `json:"name"` Type string `json:"type"` diff --git a/wgengine/userspace_test.go b/wgengine/userspace_test.go index fbe00dba3..7400a6136 100644 --- a/wgengine/userspace_test.go +++ b/wgengine/userspace_test.go @@ -687,3 +687,94 @@ func TestReconfigSubnetRouteLoadMetrics(t *testing.T) { t.Error("per-route counting stayed enabled after opting out") } } + +// TestReconfigSubnetRouteLoadMetricsTransitions drives the empty -> non-empty +// -> empty -> non-empty transitions of the advertised set through Reconfig. +// +// Reconfig(&router.Config{}) happens for real, from enterStateLocked, and any +// netmap update that transiently yields no SubnetRoutes has the same shape. +func TestReconfigSubnetRouteLoadMetricsTransitions(t *testing.T) { + bus := eventbustest.NewBus(t) + ht := health.NewTracker(bus) + reg := new(usermetric.Registry) + e, err := NewFakeUserspaceEngine(t.Logf, 0, ht, reg, bus) + if err != nil { + t.Fatal(err) + } + t.Cleanup(e.Close) + + ue := e.(*userspaceEngine) + routes := []netip.Prefix{netip.MustParsePrefix("10.1.0.0/16")} + on := func(rs []netip.Prefix) *router.Config { + return &router.Config{SubnetRoutes: rs, CollectLoadMetrics: true} + } + + // Opted in, but with no routes yet: nothing to count. + if err := ue.Reconfig(&wgcfg.Config{}, on(nil), &dns.Config{}); err != nil { + t.Fatalf("Reconfig: %v", err) + } + if ue.tundev.SubnetRouteCountingEnabledForTest() { + t.Error("counting is enabled with an empty route set") + } + + // Routes arrive. + if err := ue.Reconfig(&wgcfg.Config{}, on(routes), &dns.Config{}); err != nil { + t.Fatalf("Reconfig: %v", err) + } + if !ue.tundev.SubnetRouteCountingEnabledForTest() { + t.Fatal("counting is disabled after routes were advertised") + } + + // A transient empty netmap, e.g. the reset from enterStateLocked. This must + // not decrease any counter, so the instance survives; it just goes inactive. + if err := ue.Reconfig(&wgcfg.Config{}, &router.Config{}, &dns.Config{}); err != nil { + t.Fatalf("Reconfig: %v", err) + } + if ue.tundev.SubnetRouteCountingEnabledForTest() { + t.Error("counting stayed active across a reset to an empty config") + } + + // And back: still counting, and the route is countable again. + if err := ue.Reconfig(&wgcfg.Config{}, on(routes), &dns.Config{}); err != nil { + t.Fatalf("Reconfig: %v", err) + } + if !ue.tundev.SubnetRouteCountingEnabledForTest() { + t.Error("counting did not come back after routes were re-advertised") + } +} + +// TestReconfigSubnetRouteLoadMetricsSelfAddrs verifies that the engine tells +// the wrapper this node's own Tailscale addresses, which is what lets the +// subnet counters exclude traffic the node originates itself. +func TestReconfigSubnetRouteLoadMetricsSelfAddrs(t *testing.T) { + bus := eventbustest.NewBus(t) + ht := health.NewTracker(bus) + reg := new(usermetric.Registry) + e, err := NewFakeUserspaceEngine(t.Logf, 0, ht, reg, bus) + if err != nil { + t.Fatal(err) + } + t.Cleanup(e.Close) + + ue := e.(*userspaceEngine) + self4 := netip.MustParseAddr("100.64.0.1") + self6 := netip.MustParseAddr("fd7a:115c:a1e0::1") + cfg := &wgcfg.Config{Addresses: []netip.Prefix{ + netip.PrefixFrom(self4, 32), + netip.PrefixFrom(self6, 128), + }} + if err := ue.Reconfig(cfg, &router.Config{ + SubnetRoutes: []netip.Prefix{netip.MustParsePrefix("10.1.0.0/16")}, + CollectLoadMetrics: true, + }, &dns.Config{}); err != nil { + t.Fatalf("Reconfig: %v", err) + } + for _, a := range []netip.Addr{self4, self6} { + if !ue.tundev.IsSelfTailscaleAddrForTest(a) { + t.Errorf("the wrapper does not know %v is one of this node's own addresses", a) + } + } + if ue.tundev.IsSelfTailscaleAddrForTest(netip.MustParseAddr("100.64.0.2")) { + t.Error("the wrapper thinks a peer address is one of this node's own") + } +}