diff --git a/feature/routecheck/routecheck.go b/feature/routecheck/routecheck.go index 5e6f88bc1..4ac22a1b1 100644 --- a/feature/routecheck/routecheck.go +++ b/feature/routecheck/routecheck.go @@ -15,14 +15,17 @@ package routecheck import ( "context" "fmt" + "sync" + "tailscale.com/ipn" "tailscale.com/ipn/ipnext" + "tailscale.com/ipn/ipnstate" "tailscale.com/net/netmon" "tailscale.com/net/routecheck" "tailscale.com/tailcfg" "tailscale.com/types/logger" - "tailscale.com/types/netmap" "tailscale.com/util/eventbus" + "tailscale.com/util/set" ) // FeatureName is the name of the feature implemented by this package. @@ -44,9 +47,36 @@ type Extension struct { logf logger.Logf backend ipnext.SafeBackend + watcher ipnext.NotifyWatcher eventClient *eventbus.Client nb nodeBackender nm routecheck.NetMapper + + mu sync.Mutex + cancelWatch context.CancelFunc // non-nil iff the IPN bus watcher is running + watchDone chan struct{} // closed by the watcher goroutine when it exits + watchSelf selfNodeKey // identity of self the running watcher was started for + shutdown bool +} + +// selfNodeKey identifies a self node for the purpose of detecting profile +// switches. It mirrors the producer-side identity used in +// [ipnlocal.sameSelfNode]. +type selfNodeKey struct { + id tailcfg.NodeID + stableID tailcfg.StableNodeID + user tailcfg.UserID +} + +func selfKeyOf(self tailcfg.NodeView) selfNodeKey { + if !self.Valid() { + return selfNodeKey{} + } + return selfNodeKey{ + id: self.ID(), + stableID: self.StableID(), + user: self.User(), + } } var _ ipnext.Extension = new(Extension) @@ -70,6 +100,12 @@ func (e *Extension) Init(h ipnext.Host) error { } e.nm = nm + watcher, ok := e.backend.(ipnext.NotifyWatcher) + if !ok { + return fmt.Errorf("backend %T does not implement ipnext.NotifyWatcher", e.backend) + } + e.watcher = watcher + pinger := e.backend.Sys().Engine.Get() logf := logger.WithPrefix(e.logf, "routecheck: ") @@ -83,10 +119,13 @@ func (e *Extension) Init(h ipnext.Host) error { e.eventClient = bus.Client("routecheck") eventbus.SubscribeFunc(e.eventClient, e.onNetMonChange) - h.Hooks().OnNetMapToggle.Add(e.onNetMapToggle) - h.Hooks().OnRoutersChange.Add(e.onRoutersChange) h.Hooks().OnSelfChange.Add(e.onSelfChange) + // Catch the case where self is already valid (e.g., from a cached + // netmap) at extension Init time: OnSelfChange would not fire later + // for that pre-existing state. + e.syncWatchSubscription(e.nb.NodeBackend().Self()) + go func() { if err := e.Client.Start(context.Background()); err != nil { logf("background client failed: %v", err) @@ -97,16 +136,153 @@ func (e *Extension) Init(h ipnext.Host) error { // Shutdown implements the [ipnext.Extension.Shutdown] interface method. func (e *Extension) Shutdown() error { + e.mu.Lock() + e.shutdown = true + e.stopWatcherLocked() + e.mu.Unlock() e.eventClient.Close() - err := e.Client.Close() - return err + return e.Client.Close() } -func (e *Extension) onNetMapToggle(nm *netmap.NetworkMap) { - if nm == nil { +// onSelfChange runs when the LocalBackend's self node changes (including +// when its capabilities change), so we can start or stop the IPN bus +// watcher in response to the routecheck node attributes being toggled +// on or off for this tailnet. +func (e *Extension) onSelfChange(self tailcfg.NodeView) { + e.syncWatchSubscription(self) +} + +// syncWatchSubscription starts the IPN bus watcher when routecheck is +// enabled for self and stops it when it is not. It also restarts the +// watcher when the self node's identity changes (e.g., a profile +// switch) so the new watcher rebootstraps its router set from a fresh +// InitialStatus, instead of carrying stale NodeIDs from the previous +// account. +// +// It is safe to call from any goroutine. +func (e *Extension) syncWatchSubscription(self tailcfg.NodeView) { + enabled := routecheck.IsEnabled(self) + key := selfKeyOf(self) + e.mu.Lock() + defer e.mu.Unlock() + if e.shutdown { return } - e.Client.NotifyNetMapAvailable(nm) + running := e.cancelWatch != nil + switch { + case enabled && !running: + e.startWatcherLocked(key) + case !enabled && running: + e.stopWatcherLocked() + case enabled && running && key != e.watchSelf: + // Profile switch (or other self-node identity change). + // Restart so the bootstrap from InitialStatus replaces the + // router set in full. + e.stopWatcherLocked() + e.startWatcherLocked(key) + } +} + +// startWatcherLocked launches the IPN bus watcher goroutine. +// e.mu must be held and the watcher must not already be running. +func (e *Extension) startWatcherLocked(key selfNodeKey) { + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan struct{}) + e.cancelWatch = cancel + e.watchDone = done + e.watchSelf = key + go e.watchIPNBus(ctx, done) +} + +// stopWatcherLocked cancels the watcher goroutine and waits for it to +// exit. e.mu must be held. It is a no-op when no watcher is running. +// +// Blocking under e.mu is safe because the watcher's callback never +// acquires e.mu. +func (e *Extension) stopWatcherLocked() { + if e.cancelWatch == nil { + return + } + e.cancelWatch() + <-e.watchDone + e.cancelWatch = nil + e.watchDone = nil + e.watchSelf = selfNodeKey{} +} + +// watchIPNBus subscribes to the IPN bus to learn about peer additions, +// removals, and modifications, computes whether the set of routers among +// those peers has changed, and signals the [routecheck.Client] to refresh +// when it has. +// +// It tracks the set of router peer IDs internally instead of relying on a +// LocalBackend hook so that peer churn is processed via the existing +// constant-time delta path. See tailscale/tailscale#12542. +func (e *Extension) watchIPNBus(ctx context.Context, done chan<- struct{}) { + defer close(done) + routers := make(set.Set[tailcfg.NodeID]) + const mask = ipn.NotifyInitialStatus | ipn.NotifyPeerChanges + e.watcher.WatchNotifications(ctx, mask, nil, func(n *ipn.Notify) bool { + refresh := false + if s := n.InitialStatus; s != nil { + // Bootstrap the router set from the initial Status. This + // is the modern, scalable replacement for reading peers + // off [ipn.Notify.NetMap] under NotifyInitialNetMap. + if nm := e.nm.NetMapNoPeers(); nm != nil { + e.Client.NotifyNetMapAvailable(nm) + } + for _, ps := range s.Peer { + if peerStatusIsRouter(ps) { + if !routers.Contains(ps.NodeID) { + routers.Add(ps.NodeID) + refresh = true + } + } + } + } + for _, p := range n.PeersChanged { + isRouter := p.IsRouter() + wasRouter := routers.Contains(p.ID) + switch { + case isRouter && !wasRouter: + routers.Add(p.ID) + refresh = true + case !isRouter && wasRouter: + routers.Delete(p.ID) + refresh = true + case isRouter && wasRouter: + // A known router was modified; routes or other + // reachability-relevant fields may have changed. + refresh = true + } + } + for _, id := range n.PeersRemoved { + if routers.Contains(id) { + routers.Delete(id) + refresh = true + } + } + if n.SelfChange != nil { + refresh = true + } + if refresh { + e.needsRefresh() + } + return true + }) +} + +// peerStatusIsRouter reports whether ps describes a peer that routes +// addresses beyond its own. It is the [ipnstate.PeerStatus] analogue of +// [tailcfg.Node.IsRouter]: TailscaleIPs are the peer's own host +// addresses and AllowedIPs is a superset that also includes any subnet +// routes or exit routes the peer advertises, so the peer is a router +// when AllowedIPs has more entries than TailscaleIPs. +func peerStatusIsRouter(ps *ipnstate.PeerStatus) bool { + if ps == nil || ps.AllowedIPs == nil { + return false + } + return ps.AllowedIPs.Len() > len(ps.TailscaleIPs) } func (e *Extension) onNetMonChange(delta netmon.ChangeDelta) { @@ -115,16 +291,6 @@ func (e *Extension) onNetMonChange(delta netmon.ChangeDelta) { } } -func (e *Extension) onRoutersChange(added, modified, removed []tailcfg.NodeView) { - // TODO(sfllaw): This refresh could be incremental, - // based on the added, modified, and removed nodes. - e.needsRefresh() -} - -func (e *Extension) onSelfChange(self tailcfg.NodeView) { - e.needsRefresh() -} - func (e *Extension) needsRefresh() { if !routecheck.IsEnabled(e.nb.NodeBackend().Self()) { return diff --git a/ipn/ipnext/ipnext.go b/ipn/ipnext/ipnext.go index 1bd0faa1b..97ae107f6 100644 --- a/ipn/ipnext/ipnext.go +++ b/ipn/ipnext/ipnext.go @@ -6,6 +6,7 @@ package ipnext import ( + "context" "errors" "fmt" "iter" @@ -22,7 +23,6 @@ import ( "tailscale.com/types/key" "tailscale.com/types/logger" "tailscale.com/types/mapx" - "tailscale.com/types/netmap" "tailscale.com/types/views" "tailscale.com/wgengine/filter" ) @@ -226,6 +226,21 @@ type SafeBackend interface { TailscaleVarRoot() string } +// NotifyWatcher is the subset of [ipnlocal.LocalBackend] that subscribes +// to the IPN notification bus. It is implemented by [*ipnlocal.LocalBackend] +// and is exposed to extensions that want to consume the bus from within +// tailscaled. +// +// Unlike [SafeBackend], its methods acquire LocalBackend's internal mutex +// and must not be called from extension hooks; call them from a goroutine +// (typically one started during [Extension.Init]). +type NotifyWatcher interface { + // WatchNotifications behaves like [ipnlocal.LocalBackend.WatchNotifications]: + // it subscribes to the IPN bus, calls fn for each notification, and + // blocks until ctx is done. + WatchNotifications(ctx context.Context, mask ipn.NotifyWatchOpt, onWatchAdded func(), fn func(roNotify *ipn.Notify) (keepGoing bool)) +} + // ExtensionServices provides access to the [Host]'s extension management services, // such as fetching active extensions. type ExtensionServices interface { @@ -376,16 +391,6 @@ type Hooks struct { // is created. It is called with the LocalBackend locked. NewControlClient feature.Hooks[NewControlClientCallback] - // OnNetMapToggle is called (with LocalBackend.mu held) when the network map - // is toggled from nil to non-nil, or non-nil to nil. This usually happens - // when the client connects to the control plane and receives the initial MapResponse, - // or when the client disconnects and the network map is cleared. - OnNetMapToggle feature.Hooks[func(*netmap.NetworkMap)] - - // OnRoutersChange is called (with LocalBackend.mu held) when one or more peer nodes, - // which function as routers, have been added, modified, or removed. - OnRoutersChange feature.Hooks[func(added, modified, removed []tailcfg.NodeView)] - // OnSelfChange is called (with LocalBackend.mu held) when the self node // changes, including changing to nothing (an invalid view). OnSelfChange feature.Hooks[func(tailcfg.NodeView)] diff --git a/ipn/ipnlocal/local.go b/ipn/ipnlocal/local.go index dcfb8d2ab..b49c5ffef 100644 --- a/ipn/ipnlocal/local.go +++ b/ipn/ipnlocal/local.go @@ -2441,21 +2441,6 @@ func (b *LocalBackend) UpdateNetmapDelta(muts []netmap.NodeMutation) (handled bo } } - if cn.NetMap() != nil { - // Are any of the mutated nodes also routers? - if hooks := b.extHost.Hooks().OnRoutersChange; len(hooks) > 0 { - if routers := mutatedRouters(muts, cn); len(routers) > 0 { - for _, f := range hooks { - f(nil, routers, nil) - } - } - } - } - - // TODO(sfllaw): If the above OnRoutesChange hook has fired - // while [buildfeatures.HasRouteCheck] is enabled, - // a probe will be triggered for an updated routecheck reachability report, - // which influences which exit nodes are considered valid to suggest. if cn.NetMap() != nil && mutationsAreWorthyOfRecalculatingSuggestedExitNode(muts, cn, b.lastSuggestedExitNode) { // Recompute the suggested exit node b.suggestExitNodeLocked() @@ -2582,22 +2567,6 @@ func (b *LocalBackend) UpdateUserProfiles(profiles map[tailcfg.UserID]tailcfg.Us return true } -// MutatedRouters returns a slice of routers that were mutated by muts. -func mutatedRouters(muts []netmap.NodeMutation, cn *nodeBackend) (routers []tailcfg.NodeView) { - for _, m := range muts { - n, ok := cn.NodeByID(m.NodeIDBeingMutated()) - if !ok { - // The node being mutated is not in the netmap. - continue - } - - if n.IsRouter() { - routers = append(routers, n) - } - } - return routers -} - // mustationsAreWorthyOfRecalculatingSuggestedExitNode reports whether any mutation type in muts is // worthy of recalculating the suggested exit node. func mutationsAreWorthyOfRecalculatingSuggestedExitNode(muts []netmap.NodeMutation, cn *nodeBackend, sid tailcfg.StableNodeID) bool { @@ -7055,15 +7024,7 @@ func (b *LocalBackend) setNetMapLocked(nm *netmap.NetworkMap) { }() } - // OnRoutersChange needs to compare the old and new peers. - needsNetMapWithPeers := len(b.extHost.Hooks().OnRoutersChange) > 0 - - var oldNetMap *netmap.NetworkMap - if needsNetMapWithPeers { - oldNetMap = b.currentNode().netMapWithPeers() - } else { - oldNetMap = b.currentNode().NetMap() - } + oldNetMap := b.currentNode().NetMap() oldSelf := oldNetMap.SelfNodeOrZero() b.dialer.SetNetMap(nm) @@ -7092,28 +7053,6 @@ func (b *LocalBackend) setNetMapLocked(nm *netmap.NetworkMap) { } b.pauseOrResumeControlClientLocked() - if hooks := b.extHost.Hooks().OnRoutersChange; len(hooks) > 0 { - routers := func(nodes []tailcfg.NodeView) (ret []tailcfg.NodeView) { - for _, n := range nodes { - if n.IsRouter() { - ret = append(ret, n) - } - } - return ret - } - var oldRouters []tailcfg.NodeView - if oldNetMap != nil { - oldRouters = routers(oldNetMap.Peers) - } - newRouters := routers(b.currentNode().Peers()) - added, modified, removed := diffNodeViews(oldRouters, newRouters) - if len(added) > 0 || len(modified) > 0 || len(removed) > 0 { - for _, f := range hooks { - f(added, modified, removed) - } - } - } - if nm != nil { messages := make(map[tailcfg.DisplayMessageID]tailcfg.DisplayMessage) for id, msg := range nm.DisplayMessages { @@ -7170,12 +7109,6 @@ func (b *LocalBackend) setNetMapLocked(nm *netmap.NetworkMap) { } - if oldNetMap != nm && (oldNetMap == nil || nm == nil) { - for _, f := range b.extHost.Hooks().OnNetMapToggle { - f(nm) - } - } - if !oldSelf.Equal(nm.SelfNodeOrZero()) { for _, f := range b.extHost.Hooks().OnSelfChange { f(nm.SelfNode) diff --git a/ipn/ipnlocal/tailcfg.go b/ipn/ipnlocal/tailcfg.go deleted file mode 100644 index ffacbd861..000000000 --- a/ipn/ipnlocal/tailcfg.go +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright (c) Tailscale Inc & contributors -// SPDX-License-Identifier: BSD-3-Clause - -package ipnlocal - -import ( - "cmp" - "slices" - - "tailscale.com/tailcfg" - _ "tailscale.com/types/netmap" -) - -// DiffNodeViews compares two slices of old and new nodes -// and returns the nodes that were added, modified, and removed. -// The returned slices are sorted by [Node.ID]. -// -// BUG(sfllaw): This function should be used sparingly as a stopgap measure, -// because the incremental processing in [LocalBackend.UpdateNetmapDelta] only -// handles modifications and not additions or removals as of 2026-05-13. -// See tailscale/tailscale#1909 and tailscale/tailscale#12542. -// -// TODO(sfllaw): After tailscale/tailscale#19607 is merged, use its mechanism -// for handling [netmap.NodeMutationAdd] and [netmap.NodeMutationRemove] instead. -func diffNodeViews(old, new []tailcfg.NodeView) (added, modified, removed []tailcfg.NodeView) { - sortedByID := func(nodes []tailcfg.NodeView) []tailcfg.NodeView { - ret := slices.Clone(nodes) - slices.SortFunc(ret, func(a, b tailcfg.NodeView) int { - return cmp.Compare(a.ID(), b.ID()) - }) - return ret - } - old = sortedByID(old) - new = sortedByID(new) - - i, j := 0, 0 - for i < len(old) && j < len(new) { - switch oid, nid := old[i].ID(), new[j].ID(); { - case oid < nid: - removed = append(removed, old[i]) - i++ - case oid > nid: - added = append(added, new[j]) - j++ - case oid == nid: - if !old[i].Equal(new[j]) { - modified = append(modified, new[j]) - } - i++ - j++ - } - } - removed = append(removed, old[i:]...) - added = append(added, new[j:]...) - return added, modified, removed -}