diff --git a/net/tstun/subnetmetrics_test.go b/net/tstun/subnetmetrics_test.go index 611b75dfe..3218ae850 100644 --- a/net/tstun/subnetmetrics_test.go +++ b/net/tstun/subnetmetrics_test.go @@ -8,6 +8,7 @@ import ( "testing" tsmetrics "tailscale.com/metrics" + "tailscale.com/util/eventbus/eventbustest" "tailscale.com/util/usermetric" ) @@ -221,3 +222,106 @@ func BenchmarkSubnetCountersAdd(b *testing.B) { } } } + +// 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. +func TestWrapperSubnetRouteCountingTx(t *testing.T) { + bus := eventbustest.NewBus(t) + _, tun := newFakeTUN(t.Logf, bus, false) + defer tun.Close() + + if tun.subnetCounters() != nil { + t.Fatal("counting is enabled before SetSubnetRoutes; want disabled by default") + } + tun.SetSubnetRoutes([]netip.Prefix{netip.MustParsePrefix("10.1.0.0/16")}) + sc := tun.subnetCounters() + if sc == nil { + t.Fatal("counting still disabled after SetSubnetRoutes") + } + + 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) + } + + txBytes, rxBytes, txPackets, rxPackets := routeCountsFor(t, sc, "10.1.0.0/16") + if txPackets != 1 { + t.Errorf("txPackets = %d, want 1", txPackets) + } + if txBytes != int64(len(pkt)) { + t.Errorf("txBytes = %d, want %d", txBytes, len(pkt)) + } + if rxPackets != 0 || rxBytes != 0 { + t.Errorf("rx counters moved on a tx packet: rxBytes=%d rxPackets=%d", rxBytes, rxPackets) + } + + // Traffic to an address outside every advertised route (exit node traffic) + // must not be counted. + if _, err := tun.tdevWrite([][]byte{udp4("100.64.0.1", "192.0.2.7", 1, 2)}, 0); err != nil { + t.Fatalf("tdevWrite: %v", err) + } + if _, _, gotTx, _ := routeCountsFor(t, sc, "10.1.0.0/16"); gotTx != 1 { + t.Errorf("txPackets = %d after an unrouted packet, want still 1", gotTx) + } + + // Traffic between two tailnet addresses is the node's own, not forwarded. + if _, err := tun.tdevWrite([][]byte{udp4("100.64.0.1", "100.64.0.2", 1, 2)}, 0); err != nil { + t.Fatalf("tdevWrite: %v", err) + } + if _, _, gotTx, _ := routeCountsFor(t, sc, "10.1.0.0/16"); gotTx != 1 { + t.Errorf("txPackets = %d after tailnet-only traffic, want still 1", gotTx) + } +} + +// TestWrapperSubnetRouteCountingRx checks that traffic read out of the TUN +// toward a tailnet peer is counted as rx: the router received it from the +// subnet and is returning it to the peer. +func TestWrapperSubnetRouteCountingRx(t *testing.T) { + bus := eventbustest.NewBus(t) + chtun, tun := newChannelTUN(t.Logf, bus, false) + defer tun.Close() + + tun.SetSubnetRoutes([]netip.Prefix{netip.MustParsePrefix("10.1.0.0/16")}) + sc := tun.subnetCounters() + if sc == nil { + t.Fatal("counting disabled after SetSubnetRoutes") + } + + pkt := udp4("10.1.2.3", "100.64.0.1", 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) + } + + txBytes, rxBytes, txPackets, rxPackets := routeCountsFor(t, sc, "10.1.0.0/16") + if rxPackets != 1 { + t.Errorf("rxPackets = %d, want 1", rxPackets) + } + if rxBytes != int64(len(pkt)) { + t.Errorf("rxBytes = %d, want %d", rxBytes, len(pkt)) + } + if txPackets != 0 || txBytes != 0 { + t.Errorf("tx counters moved on an rx packet: txBytes=%d txPackets=%d", txBytes, txPackets) + } +} + +// TestWrapperSubnetRouteCountingOffByDefault verifies that traffic is not +// counted, and no series exist, until routes are set. +func TestWrapperSubnetRouteCountingOffByDefault(t *testing.T) { + bus := eventbustest.NewBus(t) + _, tun := newFakeTUN(t.Logf, bus, false) + defer tun.Close() + + 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) + } + if sc := tun.subnetCounters(); sc != nil { + t.Errorf("subnetCounters is non-nil with no routes set: %v series", seriesCount(sc)) + } +} diff --git a/net/tstun/wrap.go b/net/tstun/wrap.go index e63dccd49..e46ebbaa8 100644 --- a/net/tstun/wrap.go +++ b/net/tstun/wrap.go @@ -221,10 +221,20 @@ type Wrapper struct { // connCounter maintains per-connection counters. 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. + subnetRouteCounters atomic.Pointer[subnetCounters] + captureHook syncs.AtomicValue[packet.CaptureCallback] metrics *metrics + // usermetrics is the registry the per-route subnet counters publish into + // when they are first enabled by SetSubnetRoutes. + usermetrics *usermetric.Registry + eventClient *eventbus.Client discoKeyAdvertisementPub *eventbus.Publisher[events.DiscoKeyAdvertisement] @@ -303,6 +313,7 @@ func wrap(logf logger.Logf, tdev tun.Device, isTAP bool, m *usermetric.Registry, filterFlags: filter.LogAccepts | filter.LogDrops, startCh: make(chan struct{}), metrics: registerMetrics(m), + usermetrics: m, } if buildfeatures.HasTUNDevStats { @@ -911,6 +922,12 @@ func (t *Wrapper) Read(buffs [][]byte, sizes []int, offset int) (int, error) { updateConnCounter(update, p.Buffer(), false) } } + // 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. + if sc := t.subnetRouteCounters.Load(); sc != nil { + sc.countSubnetRouteTraffic(p.Src.Addr(), p.Dst.Addr(), len(p.Buffer()), true) + } // Make sure to do SNAT after filtering, so that any flow tracking in // the filter sees the original source address. See #12133. @@ -1088,6 +1105,13 @@ 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 { + for i := range n { + t.countSubnetRoutePacket(outBuffs[i][offset:offset+sizes[i]], true) + } + } t.noteActivity() metricPacketOut.Add(int64(n)) @@ -1280,6 +1304,13 @@ 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 { + for i := range buffs { + t.countSubnetRoutePacket(buffs[i][offset:], false) + } + } return t.tdev.Write(buffs, offset) } @@ -1505,6 +1536,76 @@ 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. +func (t *Wrapper) SetSubnetRoutes(routes []netip.Prefix) { + if !buildfeatures.HasUserMetrics && !buildfeatures.HasClientMetrics { + return + } + sc := t.subnetRouteCounters.Load() + if sc == nil { + if len(routes) == 0 { + 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. +func (t *Wrapper) subnetCounters() *subnetCounters { + return t.subnetRouteCounters.Load() +} + +// countSubnetRouteTraffic attributes a packet to an advertised subnet route, +// if it is forwarded traffic for one. +// +// 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) { + srcIsTS := tsaddr.IsTailscaleIP(src) + dstIsTS := tsaddr.IsTailscaleIP(dst) + if srcIsTS == dstIsTS { + return + } + remote := dst + if dstIsTS { + remote = src + } + if rc := sc.forAddr(remote); rc != nil { + rc.add(bytes, 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 + } + var p packet.Parsed + p.Decode(b) + if p.IPVersion == 0 { + return + } + sc.countSubnetRouteTraffic(p.Src.Addr(), p.Dst.Addr(), len(b), rx) +} + var ( metricPacketIn = clientmetric.NewCounter("tstun_in_from_wg") metricPacketInDrop = clientmetric.NewCounter("tstun_in_from_wg_drop")