Deliver link listeners to every controller until written. Fixes #4456

- tracks the link listener set owed to each controller in the link registry, marked on a listener change and after each reconnect
- sends the listener set from the registry loop with wait-for-wire once the controller's reconnect link announcement is written, retrying every tick until the write succeeds, replacing the fire-and-forget send to controllers connected at the time of the change
- fences listener completions with the reconnect generation so a send that reached an earlier connection does not count for a later one
- keeps sync state for controllers absent from a controller snapshot while they still owe the listener set
- stamps the listener set sent to controllers with the config generation read in the same snapshot, matching the hello
- makes the controller skip the peer fan-out for an UpdateLinkListeners message whose set matches the one it replaced, still recording the message generation
- makes Router.SetLinkListeners return the set it held, read under the same lock as the update
This commit is contained in:
Paul Lorenz
2026-09-23 14:26:15 -04:00
parent 043912dd47
commit a4285af743
13 changed files with 432 additions and 85 deletions
@@ -52,7 +52,19 @@ func (self *updateLinkListenersHandler) HandleReceive(msg *channel.Message, ch c
return
}
if !self.router.SetLinkListeners(listeners.Listeners, listeners.Generation) {
previous, recorded := self.router.SetLinkListeners(listeners.Listeners, listeners.Generation)
// Routers republish on connect whenever the set may have moved since their hello, so an unchanged set
// is expected here and must not fan a peer-state change out to every other router. A router with no
// link config publishes at generation zero, which the generation check always accepts.
if listenersEqual(previous, listeners.Listeners) {
log.WithField("listenerCount", len(listeners.Listeners)).
WithField("generation", listeners.Generation).
Debug("router link listeners unchanged")
return
}
if !recorded {
// Superseded by an update that arrived first. Redistributing this set
// would push peers back onto listeners the router has already replaced.
log.WithField("generation", listeners.Generation).
@@ -69,3 +81,16 @@ func (self *updateLinkListenersHandler) HandleReceive(msg *channel.Message, ch c
// their local dial decisions.
self.network.RouterMessaging.RouterListenersUpdated(self.router)
}
// listenersEqual reports whether a and b hold the same listeners in the same order.
func listenersEqual(a, b []*ctrl_pb.Listener) bool {
if len(a) != len(b) {
return false
}
for i := range a {
if !proto.Equal(a[i], b[i]) {
return false
}
}
return true
}
@@ -0,0 +1,24 @@
package handler_ctrl
import (
"testing"
"github.com/openziti/ziti/v2/common/pb/ctrl_pb"
"github.com/stretchr/testify/require"
)
func Test_listenersEqual(t *testing.T) {
listener := func(address string) *ctrl_pb.Listener {
return &ctrl_pb.Listener{Address: address, Protocol: "tls", Groups: []string{"default"}, LocalBinding: "default"}
}
req := require.New(t)
req.True(listenersEqual(nil, nil))
req.True(listenersEqual(nil, []*ctrl_pb.Listener{}))
req.True(listenersEqual([]*ctrl_pb.Listener{listener("tls:a:6000")}, []*ctrl_pb.Listener{listener("tls:a:6000")}))
req.False(listenersEqual([]*ctrl_pb.Listener{listener("tls:a:6000")}, nil))
req.False(listenersEqual([]*ctrl_pb.Listener{listener("tls:a:6000")}, []*ctrl_pb.Listener{listener("tls:b:6000")}))
req.False(listenersEqual(
[]*ctrl_pb.Listener{listener("tls:a:6000"), listener("tls:b:6000")},
[]*ctrl_pb.Listener{listener("tls:b:6000"), listener("tls:a:6000")}))
}
+31 -9
View File
@@ -27,26 +27,31 @@ func listenerSet(addr string) []*ctrl_pb.Listener {
return []*ctrl_pb.Listener{{Address: addr, Protocol: "tls"}}
}
func setListeners(r *Router, listeners []*ctrl_pb.Listener, generation uint64) bool {
_, recorded := r.SetLinkListeners(listeners, generation)
return recorded
}
func TestRouter_SetLinkListeners_DropsSupersededGeneration(t *testing.T) {
req := require.New(t)
r := &Router{}
req.True(r.SetLinkListeners(listenerSet("a"), 1))
req.True(setListeners(r, listenerSet("a"), 1))
req.Equal("a", r.GetLinkListeners()[0].Address)
req.True(r.SetLinkListeners(listenerSet("b"), 2))
req.True(setListeners(r, listenerSet("b"), 2))
req.Equal("b", r.GetLinkListeners()[0].Address)
// An update that lost the race must not push the router back onto listeners
// it has already replaced, since the set is redistributed to every peer.
req.False(r.SetLinkListeners(listenerSet("a"), 1))
req.False(setListeners(r, listenerSet("a"), 1))
req.Equal("b", r.GetLinkListeners()[0].Address, "the newer set must survive")
// The same generation is also refused: nothing new to record.
req.False(r.SetLinkListeners(listenerSet("c"), 2))
req.False(setListeners(r, listenerSet("c"), 2))
req.Equal("b", r.GetLinkListeners()[0].Address)
req.True(r.SetLinkListeners(listenerSet("d"), 3))
req.True(setListeners(r, listenerSet("d"), 3))
req.Equal("d", r.GetLinkListeners()[0].Address)
}
@@ -57,12 +62,12 @@ func TestRouter_ResetLinkListeners_AllowsRestartedRouter(t *testing.T) {
req := require.New(t)
r := &Router{}
req.True(r.SetLinkListeners(listenerSet("old"), 47))
req.False(r.SetLinkListeners(listenerSet("new"), 1), "without a reset, a restart looks superseded")
req.True(setListeners(r, listenerSet("old"), 47))
req.False(setListeners(r, listenerSet("new"), 1), "without a reset, a restart looks superseded")
r.ResetLinkListeners()
req.Empty(r.GetLinkListeners(), "reset clears the recorded set")
req.True(r.SetLinkListeners(listenerSet("new"), 1), "after a reset the new session starts fresh")
req.True(setListeners(r, listenerSet("new"), 1), "after a reset the new session starts fresh")
req.Equal("new", r.GetLinkListeners()[0].Address)
}
@@ -71,6 +76,23 @@ func TestRouter_SetLinkListeners_FirstUpdateAlwaysRecorded(t *testing.T) {
// rather than being read as "already superseded".
req := require.New(t)
r := &Router{}
req.True(r.SetLinkListeners(listenerSet("a"), 0))
req.True(setListeners(r, listenerSet("a"), 0))
req.Equal("a", r.GetLinkListeners()[0].Address)
}
func TestRouter_SetLinkListeners_ReturnsTheSetItHeld(t *testing.T) {
req := require.New(t)
r := &Router{}
previous, recorded := r.SetLinkListeners(listenerSet("a"), 1)
req.True(recorded)
req.Empty(previous)
previous, recorded = r.SetLinkListeners(listenerSet("b"), 2)
req.True(recorded)
req.Equal("a", previous[0].Address, "a recorded update returns the set it replaced")
previous, recorded = r.SetLinkListeners(listenerSet("c"), 2)
req.False(recorded)
req.Equal("b", previous[0].Address, "a refused update returns the set still held")
}
+10 -10
View File
@@ -167,22 +167,22 @@ func (entity *Router) addLinkListener(addr, linkProtocol string, groups []string
})
}
// SetLinkListeners atomically replaces the router's link listener slice.
// Callers do not mutate the previous slice — readers may still hold and
// iterate it safely after a Set.
// SetLinkListeners records listeners when generation is newer than the last
// recorded for this control channel session, and reports whether it did. Older
// generations are dropped: a multi-underlay control channel doesn't order updates
// across underlays, and a stale set would be redistributed to peers.
func (entity *Router) SetLinkListeners(listeners []*ctrl_pb.Listener, generation uint64) bool {
// SetLinkListeners records listeners when generation is newer than the one recorded for this control channel
// session, or when the recorded generation is zero, and reports whether it did. It returns the set held before
// the call either way, read under the same lock, so a caller can tell whether the update changed anything.
// Older and equal generations are dropped: a multi-underlay control channel doesn't order updates across
// underlays, and a stale set would be redistributed to peers. Slices are replaced, never mutated, so a returned
// set stays safe to iterate.
func (entity *Router) SetLinkListeners(listeners []*ctrl_pb.Listener, generation uint64) (previous []*ctrl_pb.Listener, recorded bool) {
entity.mu.Lock()
defer entity.mu.Unlock()
previous = entity.listeners
if generation <= entity.listenerGeneration && entity.listenerGeneration != 0 {
return false
return previous, false
}
entity.listeners = listeners
entity.listenerGeneration = generation
return true
return previous, true
}
// ResetLinkListeners clears the listener set and the generation it was recorded
+82 -8
View File
@@ -18,15 +18,22 @@ package link
import (
"sync"
"github.com/openziti/ziti/v2/common/pb/ctrl_pb"
"github.com/openziti/ziti/v2/router/xlink"
)
// ctrlSynchronizer tracks what the router still owes each controller. A controller it has (re)connected to owes a
// full link refresh, and until that refresh is written the controller is not synced: incremental link
// reports to it are held, since a report that lands ahead of the refresh is either pruned by it or re-adds
// a link the refresh omitted. Safe for concurrent use.
// a link the refresh omitted. Each controller also owes the current link listener set whenever that set
// has changed since it was last written there. Safe for concurrent use.
type ctrlSynchronizer struct {
lock sync.Mutex
states map[string]*ctrlSyncState
lock sync.Mutex
// listenersGen counts listener set changes. It starts at 1 so a controller that has never been sent
// the set (sentGen 0) is pending.
listenersGen uint64
states map[string]*ctrlSyncState
}
type ctrlSyncState struct {
@@ -36,11 +43,12 @@ type ctrlSyncState struct {
refreshInFlight bool
// reconnectGen counts reconnects. A refresh is built for the generation current when it was begun and
// only satisfies the debt if no reconnect happened before it was written.
reconnectGen uint64
reconnectGen uint64
listenersSentGen uint64
}
func newCtrlSynchronizer() *ctrlSynchronizer {
return &ctrlSynchronizer{states: map[string]*ctrlSyncState{}}
return &ctrlSynchronizer{listenersGen: 1, states: map[string]*ctrlSyncState{}}
}
func (self *ctrlSynchronizer) state(ctrlId string) *ctrlSyncState {
@@ -52,12 +60,13 @@ func (self *ctrlSynchronizer) state(ctrlId string) *ctrlSyncState {
return result
}
// markReconnected records that ctrlId owes a full refresh.
// markReconnected records that ctrlId owes a full refresh and the current listener set.
func (self *ctrlSynchronizer) markReconnected(ctrlId string) {
self.lock.Lock()
defer self.lock.Unlock()
state := self.state(ctrlId)
state.refreshPending = true
state.listenersSentGen = 0
state.reconnectGen++
}
@@ -113,8 +122,56 @@ func (self *ctrlSynchronizer) isSynced(ctrlId string) bool {
return !found || !state.refreshPending
}
// markListenersChanged records that the listener set changed, making it pending for every controller. It
// returns the new generation.
func (self *ctrlSynchronizer) markListenersChanged() uint64 {
self.lock.Lock()
defer self.lock.Unlock()
self.listenersGen++
return self.listenersGen
}
// currentListenersGen returns the generation a send built now should report with markListenersSent.
func (self *ctrlSynchronizer) currentListenersGen() uint64 {
self.lock.Lock()
defer self.lock.Unlock()
return self.listenersGen
}
// isListenersSendPending reports whether ctrlId has not been sent the current listener set.
func (self *ctrlSynchronizer) isListenersSendPending(ctrlId string) bool {
self.lock.Lock()
defer self.lock.Unlock()
state, found := self.states[ctrlId]
return !found || state.listenersSentGen != self.listenersGen
}
// reconnectGen returns ctrlId's current reconnect generation, for fencing a send begun now against a later
// reconnect.
func (self *ctrlSynchronizer) reconnectGen(ctrlId string) uint64 {
self.lock.Lock()
defer self.lock.Unlock()
return self.state(ctrlId).reconnectGen
}
// markListenersSent records that the listener set of generation gen was written to ctrlId over the connection
// of reconnect generation reconnectGen. A set that changed again since gen was built stays pending, and so
// does the whole set when ctrlId has reconnected since reconnectGen was taken: that write reached the previous
// connection, not the current one.
func (self *ctrlSynchronizer) markListenersSent(ctrlId string, gen uint64, reconnectGen uint64) {
self.lock.Lock()
defer self.lock.Unlock()
state := self.state(ctrlId)
if state.reconnectGen != reconnectGen {
return
}
if gen > state.listenersSentGen {
state.listenersSentGen = gen
}
}
// forget drops tracking for controllers that are no longer in known and are owed nothing. A state that owes a
// refresh is kept even when its controller is absent from known: known is a snapshot, and
// refresh or the listener set is kept even when its controller is absent from known: known is a snapshot, and
// a controller that connected after it was taken has just recorded that debt. Dropping the state would read
// as synced and nothing would ever announce to it. A settled state is safe to drop, since a controller that
// reappears records a fresh debt.
@@ -125,9 +182,26 @@ func (self *ctrlSynchronizer) forget(known map[string]struct{}) {
if _, ok := known[ctrlId]; ok {
continue
}
settled := !state.refreshPending && !state.refreshInFlight
settled := !state.refreshPending && !state.refreshInFlight && state.listenersSentGen == self.listenersGen
if settled {
delete(self.states, ctrlId)
}
}
}
// ListenersToProto converts the router's link listeners, stamped with the config generation they belong to,
// to the wire shape used in the hello ListenersHeader and in UpdateLinkListeners, in the order given. The
// generation and listeners must come from one snapshot, or a controller comparing generations may keep a stale
// set and reject the newer one.
func ListenersToProto(generation uint64, listeners []xlink.Listener) *ctrl_pb.Listeners {
result := &ctrl_pb.Listeners{Generation: generation}
for _, listener := range listeners {
result.Listeners = append(result.Listeners, &ctrl_pb.Listener{
Address: listener.GetAdvertisement(),
Protocol: listener.GetLinkProtocol(),
Groups: listener.GetGroups(),
LocalBinding: listener.GetLocalBinding(),
})
}
return result
}
+44 -1
View File
@@ -7,11 +7,12 @@ import (
)
func Test_ctrlSynchronizer(t *testing.T) {
t.Run("an unknown controller is synced and owes no refresh", func(t *testing.T) {
t.Run("an unknown controller is synced, owes no refresh, and owes the listener set", func(t *testing.T) {
sync := newCtrlSynchronizer()
require.True(t, sync.isSynced("ctrl1"))
_, ok := sync.beginRefresh("ctrl1")
require.False(t, ok)
require.True(t, sync.isListenersSendPending("ctrl1"))
})
t.Run("a reconnect owes a refresh, claimed once, and sync follows the write", func(t *testing.T) {
@@ -54,6 +55,41 @@ func Test_ctrlSynchronizer(t *testing.T) {
require.True(t, sync.isSynced("ctrl1"))
})
t.Run("listeners sent for the current generation clears the debt, an older generation does not", func(t *testing.T) {
sync := newCtrlSynchronizer()
gen := sync.currentListenersGen()
sync.markListenersChanged()
sync.markListenersSent("ctrl1", gen, sync.reconnectGen("ctrl1"))
require.True(t, sync.isListenersSendPending("ctrl1"))
sync.markListenersSent("ctrl1", sync.currentListenersGen(), sync.reconnectGen("ctrl1"))
require.False(t, sync.isListenersSendPending("ctrl1"))
})
t.Run("a reconnect makes the listener set owed again", func(t *testing.T) {
sync := newCtrlSynchronizer()
sync.markListenersSent("ctrl1", sync.currentListenersGen(), sync.reconnectGen("ctrl1"))
require.False(t, sync.isListenersSendPending("ctrl1"))
sync.markReconnected("ctrl1")
require.True(t, sync.isListenersSendPending("ctrl1"))
})
t.Run("a listener send written before a reconnect does not satisfy the new connection", func(t *testing.T) {
sync := newCtrlSynchronizer()
sync.markReconnected("ctrl1")
gen, _ := sync.beginRefresh("ctrl1")
require.True(t, sync.markRefreshWritten("ctrl1", gen))
listenersGen := sync.currentListenersGen()
staleReconnectGen := sync.reconnectGen("ctrl1")
sync.markReconnected("ctrl1") // reconnect after the write, before its completion
sync.markListenersSent("ctrl1", listenersGen, staleReconnectGen)
require.True(t, sync.isListenersSendPending("ctrl1"), "the stale completion must not mark the new connection sent")
sync.markListenersSent("ctrl1", listenersGen, sync.reconnectGen("ctrl1"))
require.False(t, sync.isListenersSendPending("ctrl1"), "a send fenced with the current generation clears the debt")
})
t.Run("forget drops only settled controllers no longer known", func(t *testing.T) {
sync := newCtrlSynchronizer()
@@ -61,10 +97,16 @@ func Test_ctrlSynchronizer(t *testing.T) {
sync.markReconnected("ctrl1")
gen, _ := sync.beginRefresh("ctrl1")
require.True(t, sync.markRefreshWritten("ctrl1", gen))
sync.markListenersSent("ctrl1", sync.currentListenersGen(), sync.reconnectGen("ctrl1"))
// ctrl2: connected after the snapshot was taken, so absent from it, but owing a refresh -> kept.
sync.markReconnected("ctrl2")
// ctrl3: refreshed but still owing the listener set -> kept.
sync.markReconnected("ctrl3")
gen3, _ := sync.beginRefresh("ctrl3")
require.True(t, sync.markRefreshWritten("ctrl3", gen3))
sync.forget(map[string]struct{}{})
_, ok1 := sync.states["ctrl1"]
@@ -72,5 +114,6 @@ func Test_ctrlSynchronizer(t *testing.T) {
require.False(t, sync.isSynced("ctrl2"), "a reconnect recorded after the snapshot keeps its refresh debt")
_, owed := sync.beginRefresh("ctrl2")
require.True(t, owed)
require.True(t, sync.isListenersSendPending("ctrl3"), "an owed listener set is kept")
})
}
+84 -7
View File
@@ -36,12 +36,16 @@ import (
"github.com/openziti/ziti/v2/router/env"
"github.com/openziti/ziti/v2/router/xlink"
"github.com/sirupsen/logrus"
"google.golang.org/protobuf/proto"
)
type Env interface {
GetRouterId() *identity.TokenId
GetNetworkControllers() env.NetworkControllers
GetXlinkDialers() []xlink.Dialer
// GetXlinkListenerSnapshot returns the current link listeners and the config generation they belong to,
// read together.
GetXlinkListenerSnapshot() (uint64, []xlink.Listener)
GetCloseNotify() <-chan struct{}
GetLinkDialerPool() goroutines.Pool
GetRateLimiterPool() goroutines.Pool
@@ -79,17 +83,18 @@ type linkRegistryImpl struct {
env Env
destinations map[string]*linkDest
// ctrlSynchronizer holds what each controller is still owed: a full refresh after a reconnect, which gates
// incremental reports to it.
// incremental reports to it, and the current link listener set.
ctrlSynchronizer *ctrlSynchronizer
// fullRefreshSendTimeout bounds one attempt at the reconnect announcement. A field so tests can reach the
// timeout, which is the only way to tell a message that was queued and then discarded from one that
// reached the wire.
fullRefreshSendTimeout time.Duration
linkStateQueue *linkStateHeap
events chan event
triggerNotifyC chan struct{}
notifyInProgress atomic.Bool
fullRefreshSendTimeout time.Duration
linkStateQueue *linkStateHeap
events chan event
triggerNotifyC chan struct{}
notifyInProgress atomic.Bool
listenerNotifyInProgress atomic.Bool
}
func (self *linkRegistryImpl) runGcLinkMetricsLoop() {
@@ -407,7 +412,7 @@ const fullRefreshSendTimeout = 5 * time.Second
// NotifyOfReconnect records that a controller has (re)connected and owes a full link announcement. The
// announcement is sent by the registry loop (see notifyControllersOfRefresh) and retried each tick until it
// is written. Until then the controller is unsynced and incremental link reports to it are held (see
// ctrlSynchronizer); once written, the held reports follow.
// ctrlSynchronizer); once written, the held reports and the current link listeners follow.
func (self *linkRegistryImpl) NotifyOfReconnect(ch channel.Channel) {
self.ctrlSynchronizer.markReconnected(ch.Id())
self.triggerNotify()
@@ -506,6 +511,76 @@ func (self *linkRegistryImpl) snapshotDialedLinks(ctrlId string) (*ctrl_pb.Route
return routerLinks, onComplete
}
// LinkListenersChanged implements xlink.Registry. The current listener set becomes pending for every
// controller and is sent by the notify loop, retrying until written.
func (self *linkRegistryImpl) LinkListenersChanged() {
self.ctrlSynchronizer.markListenersChanged()
self.triggerNotify()
}
// notifyControllersOfLinkListeners sends the current link listener set to every synced, connected
// controller that has not been sent it. Runs on the registry loop; the sends run on the rate limiter pool.
func (self *linkRegistryImpl) notifyControllersOfLinkListeners() {
if self.listenerNotifyInProgress.Load() {
return
}
targets := map[string]env.NetworkController{}
for ctrlId, ctrl := range self.ctrls.GetAll() {
if ctrl.IsConnected() && self.ctrlSynchronizer.isSynced(ctrlId) && self.ctrlSynchronizer.isListenersSendPending(ctrlId) {
targets[ctrlId] = ctrl
}
}
if len(targets) == 0 {
return
}
self.listenerNotifyInProgress.Store(true)
err := self.env.GetRateLimiterPool().QueueOrError(func() {
defer self.listenerNotifyInProgress.Store(false)
self.sendLinkListeners(targets)
})
if err != nil {
pfxlog.Logger().WithError(err).WithField("op", "link-notify").Info("unable to queue link listener notifications")
self.listenerNotifyInProgress.Store(false)
}
}
// sendLinkListeners sends the current link listener set to each target, marking the set sent for those it
// was written to. A set that changes after it is built stays pending, so the next pass sends the newer one.
func (self *linkRegistryImpl) sendLinkListeners(targets map[string]env.NetworkController) {
gen := self.ctrlSynchronizer.currentListenersGen()
listeners := ListenersToProto(self.env.GetXlinkListenerSnapshot())
buf, err := proto.Marshal(listeners)
if err != nil {
pfxlog.Logger().WithError(err).WithField("op", "link-notify").Error("unable to marshal link listeners")
return
}
for ctrlId, ctrl := range targets {
log := pfxlog.Logger().WithField("ctrlId", ctrlId).WithField("op", "link-notify").
WithField("listenerCount", len(listeners.Listeners))
// Captured before the write so a reconnect landing during it leaves the set owed to the new
// connection. A controller that went unsynced since it was chosen is skipped; it is sent after its
// refresh.
reconnectGen := self.ctrlSynchronizer.reconnectGen(ctrlId)
if !self.ctrlSynchronizer.isSynced(ctrlId) {
continue
}
// A fresh message per controller: sending mutates message state.
msg := channel.NewMessage(int32(ctrl_pb.ContentType_UpdateLinkListenersType), buf)
if err := msg.WithTimeout(10 * time.Second).SendAndWaitForWire(ctrl.Channel()); err != nil {
log.WithError(err).Warn("failed to send link listeners to controller, will retry")
continue
}
self.ctrlSynchronizer.markListenersSent(ctrlId, gen, reconnectGen)
log.Info("sent link listeners to controller")
}
}
func (self *linkRegistryImpl) GetTraceDecoders() []channel.TraceMessageDecoder {
return nil
}
@@ -592,10 +667,12 @@ func (self *linkRegistryImpl) run() {
case <-self.triggerNotifyC:
self.notifyControllersOfRefresh()
self.notifyControllersOfLinks()
self.notifyControllersOfLinkListeners()
case <-queueCheckTicker.C:
self.evaluateLinkStateQueue()
self.notifyControllersOfRefresh()
self.notifyControllersOfLinks()
self.notifyControllersOfLinkListeners()
case <-fullScanTicker.C:
self.evaluateDestinations()
self.syncRequiredLinkStates()
+106 -1
View File
@@ -40,6 +40,7 @@ import (
"github.com/openziti/ziti/v2/router/xlink"
"github.com/pkg/errors"
"github.com/stretchr/testify/require"
"google.golang.org/protobuf/proto"
)
type testEnv struct {
@@ -51,6 +52,8 @@ type testEnv struct {
dialersMu sync.Mutex
dialers []xlink.Dialer
listenerGeneration atomic.Uint64
}
func (self *testEnv) setDialers(d []xlink.Dialer) {
@@ -98,6 +101,10 @@ func (self *testEnv) GetXlinkDialers() []xlink.Dialer {
return out
}
func (self *testEnv) GetXlinkListenerSnapshot() (uint64, []xlink.Listener) {
return self.listenerGeneration.Load(), nil
}
func (self *testEnv) GetCloseNotify() <-chan struct{} {
return self.closeNotify
}
@@ -556,6 +563,7 @@ type flakySendChannel struct {
sends atomic.Int32
closed atomic.Bool
closeNotify chan struct{}
lastSent atomic.Pointer[channel.Message]
}
func newFlakySendChannel(failures int) *flakySendChannel {
@@ -575,6 +583,7 @@ func (self *flakySendChannel) Send(s channel.Sendable) error {
return errors.New("timeout waiting for space in send queue")
}
// What the tx loop does once the message is actually written.
self.lastSent.Store(s.Msg())
s.SendListener().NotifyAfterWrite()
return nil
}
@@ -647,7 +656,7 @@ func markRefreshed(t *testing.T, reg *linkRegistryImpl, ctrlId string) {
// Test_NotifyOfReconnect_RetriesUntilTheAnnouncementLands covers the retry. A router announces its full link
// set once per controller reconnect and nothing re-asks, so an announcement lost to send-queue back-pressure
// leaves that controller unable to route over the router's links, and unable to prune the ones it should have
// dropped, until the next reconnect. Once written, the controller is synced.
// dropped, until the next reconnect. Once written, the controller is synced and owes the listener set.
func Test_NotifyOfReconnect_RetriesUntilTheAnnouncementLands(t *testing.T) {
reg, _ := newReconnectTestRegistry(t)
ch := newFlakySendChannel(2)
@@ -662,6 +671,7 @@ func Test_NotifyOfReconnect_RetriesUntilTheAnnouncementLands(t *testing.T) {
require.Equal(t, int32(3), ch.sends.Load(), "the announcement should have been retried until it reached the wire")
require.True(t, reg.ctrlSynchronizer.isSynced("ctrl1"))
require.True(t, reg.ctrlSynchronizer.isListenersSendPending("ctrl1"))
tickRefresh(t, reg, "ctrl1")
require.Equal(t, int32(3), ch.sends.Load(), "a written announcement is not sent again")
@@ -845,6 +855,101 @@ func Test_linkReports_DisconnectedUnsyncedController(t *testing.T) {
})
}
// Test_sendLinkListeners covers the listener publish: a controller owes the set after a reconnect and after a
// change, a written set clears what it owes, a failed write leaves it owed, and a change made while a send is
// being built is not cleared by that send. The loop pass only sends to synced controllers.
func Test_sendLinkListeners(t *testing.T) {
t.Run("a reconnect leaves the set owed until the refresh is written and the set sent", func(t *testing.T) {
reg, _ := newReconnectTestRegistry(t)
ch := newFlakySendChannel(0)
withCtrl(reg, "ctrl1", ch)
reg.ctrlSynchronizer.markReconnected("ctrl1")
reg.notifyControllersOfLinkListeners()
require.Eventually(t, func() bool { return !reg.listenerNotifyInProgress.Load() }, time.Second, time.Millisecond)
require.Equal(t, int32(0), ch.sends.Load(), "listeners wait for the refresh")
markRefreshed(t, reg, "ctrl1")
reg.notifyControllersOfLinkListeners()
require.Eventually(t, func() bool { return !reg.ctrlSynchronizer.isListenersSendPending("ctrl1") }, time.Second, time.Millisecond)
require.Equal(t, int32(1), ch.sends.Load())
})
t.Run("the set is stamped with the config generation it was read with", func(t *testing.T) {
reg, routerEnv := newReconnectTestRegistry(t)
routerEnv.listenerGeneration.Store(7)
ch := newFlakySendChannel(0)
ctrl := withCtrl(reg, "ctrl1", ch)
reg.ctrlSynchronizer.markReconnected("ctrl1")
markRefreshed(t, reg, "ctrl1")
reg.sendLinkListeners(map[string]env.NetworkController{"ctrl1": ctrl})
msg := ch.lastSent.Load()
require.NotNil(t, msg)
sent := &ctrl_pb.Listeners{}
require.NoError(t, proto.Unmarshal(msg.Body, sent))
require.Equal(t, uint64(7), sent.Generation)
})
t.Run("a change makes the set owed again and a failed write leaves it owed", func(t *testing.T) {
reg, _ := newReconnectTestRegistry(t)
ch := newFlakySendChannel(1)
ctrl := withCtrl(reg, "ctrl1", ch)
reg.ctrlSynchronizer.markReconnected("ctrl1")
markRefreshed(t, reg, "ctrl1")
reg.ctrlSynchronizer.markListenersSent("ctrl1", reg.ctrlSynchronizer.currentListenersGen(), reg.ctrlSynchronizer.reconnectGen("ctrl1"))
require.False(t, reg.ctrlSynchronizer.isListenersSendPending("ctrl1"))
reg.LinkListenersChanged()
require.True(t, reg.ctrlSynchronizer.isListenersSendPending("ctrl1"))
reg.sendLinkListeners(map[string]env.NetworkController{"ctrl1": ctrl})
require.True(t, reg.ctrlSynchronizer.isListenersSendPending("ctrl1"), "a failed write leaves the set owed")
reg.sendLinkListeners(map[string]env.NetworkController{"ctrl1": ctrl})
require.False(t, reg.ctrlSynchronizer.isListenersSendPending("ctrl1"))
})
t.Run("a controller that reconnected since it was chosen is not sent to", func(t *testing.T) {
reg, _ := newReconnectTestRegistry(t)
ch := newFlakySendChannel(0)
ctrl := withCtrl(reg, "ctrl1", ch)
reg.ctrlSynchronizer.markReconnected("ctrl1")
markRefreshed(t, reg, "ctrl1")
reg.ctrlSynchronizer.markReconnected("ctrl1") // reconnect after the target was chosen
reg.sendLinkListeners(map[string]env.NetworkController{"ctrl1": ctrl})
require.Equal(t, int32(0), ch.sends.Load(), "an unsynced controller waits for its refresh")
require.True(t, reg.ctrlSynchronizer.isListenersSendPending("ctrl1"))
})
t.Run("a reconnect during the write leaves the new connection owed", func(t *testing.T) {
reg, _ := newReconnectTestRegistry(t)
ch := &reconnectOnSendChannel{flakySendChannel: newFlakySendChannel(0), reg: reg}
ctrl := withCtrl(reg, "ctrl1", ch)
reg.ctrlSynchronizer.markReconnected("ctrl1")
markRefreshed(t, reg, "ctrl1")
reg.sendLinkListeners(map[string]env.NetworkController{"ctrl1": ctrl})
require.Equal(t, int32(1), ch.sends.Load())
require.True(t, reg.ctrlSynchronizer.isListenersSendPending("ctrl1"), "the write reached the previous connection")
})
t.Run("a change during a send is not cleared by that send", func(t *testing.T) {
reg, _ := newReconnectTestRegistry(t)
gen := reg.ctrlSynchronizer.currentListenersGen()
reg.ctrlSynchronizer.markReconnected("ctrl1")
reg.LinkListenersChanged()
reg.ctrlSynchronizer.markListenersSent("ctrl1", gen, reg.ctrlSynchronizer.reconnectGen("ctrl1"))
require.True(t, reg.ctrlSynchronizer.isListenersSendPending("ctrl1"), "the send built before the change cannot satisfy it")
})
}
func Test_LinkRegistry_RescanDetachesRemovedDialerPairing(t *testing.T) {
req := require.New(t)
tenv := newTestEnv()
+1
View File
@@ -55,6 +55,7 @@ func (r *gcStubRegistry) GetDestinationListeners() (map[string][]*ctrl_pb.Listen
// The rest of xlink.Registry isn't exercised by RunStaleLinkGc.
func (*gcStubRegistry) UpdateLinkDest(string, string, string, bool, []*ctrl_pb.Listener) {}
func (*gcStubRegistry) RemoveLinkDest(string) {}
func (*gcStubRegistry) LinkListenersChanged() {}
func (*gcStubRegistry) GetLink(string) (xlink.Xlink, bool) { return nil, false }
func (*gcStubRegistry) GetLinkById(string) (xlink.Xlink, bool) { return nil, false }
func (*gcStubRegistry) DialSucceeded(xlink.Xlink) (xlink.Xlink, bool) { return nil, false }
+14 -47
View File
@@ -166,6 +166,12 @@ func (self *Router) GetXlinkListeners() []xlink.Listener {
return self.linkSubsystem.Listeners()
}
// GetXlinkListenerSnapshot returns the current link listeners and the config generation they belong to, read
// under one lock.
func (self *Router) GetXlinkListenerSnapshot() (uint64, []xlink.Listener) {
return self.linkSubsystem.ListenerSnapshot()
}
func (self *Router) GetXrctrls() []env.Xrctrl {
return self.xrctrls
}
@@ -861,33 +867,17 @@ func (self *Router) registerPlugins() error {
return nil
}
// currentLinkListeners builds a ctrl_pb.Listeners snapshot from the
// linkSubsystem's current listener slice. Shared between Hello-time
// header packing and the post-Apply publish path so both wire shapes
// stay aligned.
// currentLinkListeners builds the hello ListenersHeader snapshot from the link subsystem's current listeners.
func (self *Router) currentLinkListeners() *ctrl_pb.Listeners {
// Generation and listeners come from one read: an update carries the
// generation of the set it actually contains, so a controller comparing
// generations can drop a superseded one.
generation, current := self.linkSubsystem.ListenerSnapshot()
listeners := &ctrl_pb.Listeners{Generation: generation}
for _, listener := range current {
listeners.Listeners = append(listeners.Listeners, &ctrl_pb.Listener{
Address: listener.GetAdvertisement(),
Protocol: listener.GetLinkProtocol(),
Groups: listener.GetGroups(),
LocalBinding: listener.GetLocalBinding(),
})
}
return listeners
return link.ListenersToProto(self.GetXlinkListenerSnapshot())
}
// onLinkSubsystemChanged is invoked after every Apply/Remove that
// actually mutates the link subsystem. Listener changes get republished
// to every connected controller so peer routers see the new state via
// PeerStateChange. Dialer changes trigger a local rescan against known
// peers, in case the new dialer set unlocks previously-unmatched
// listeners. Under a non-preserve gcMode the change also drives an auto-GC
// actually mutates the link subsystem. Listener changes are handed to the
// link registry, which republishes them to every controller so peer
// routers see the new state via PeerStateChange. Dialer changes trigger a
// local rescan against known peers, in case the new dialer set unlocks
// previously-unmatched listeners. Under a non-preserve gcMode the change also drives an auto-GC
// pass over the xlink registry, closing entries it just made stale.
//
// The mode comes from the change rather than from the active config, so a
@@ -896,7 +886,7 @@ func (self *Router) currentLinkListeners() *ctrl_pb.Listeners {
// unsupportable, so under orphaned or changed they are all closed.
func (self *Router) onLinkSubsystemChanged(change link.ConfigurationChange) {
if change.ListenersChanged {
self.publishLinkListeners()
self.xlinkRegistry.LinkListenersChanged()
}
if change.DialersChanged {
self.xlinkRegistry.RescanForDialOpportunities()
@@ -913,29 +903,6 @@ func (self *Router) onLinkSubsystemChanged(change link.ConfigurationChange) {
link.RunStaleLinkGc(self, change.GcMode)
}
// publishLinkListeners marshals the current listener set and sends an
// UpdateLinkListeners message to every connected controller. The
// controller's handler updates Router.Listeners + triggers peer
// redistribution. Hello continues to carry the initial snapshot at
// connect time; this message handles mid-session changes.
func (self *Router) publishLinkListeners() {
listeners := self.currentLinkListeners()
buf, err := proto.Marshal(listeners)
if err != nil {
pfxlog.Logger().WithError(err).Error("unable to marshal Listeners for UpdateLinkListeners")
return
}
self.ctrls.ForEach(func(ctrlId string, ch channel.Channel) {
// Build a fresh message per controller: sending mutates message state,
// so a single shared message can't be sent to multiple channels safely.
msg := channel.NewMessage(int32(ctrl_pb.ContentType_UpdateLinkListenersType), buf)
if err := ch.Send(msg); err != nil {
pfxlog.Logger().WithError(err).WithField("ctrlId", ctrlId).
Warn("failed to send UpdateLinkListeners to controller")
}
})
}
// applyLocalLinkConfig translates the router's local YAML link config into
// the router.link.v1 JSON shape and feeds it to the managedconfig registry
// as a local-source apply. Returns immediately if no local link config is
+4
View File
@@ -54,6 +54,10 @@ type Registry interface {
// SendRouterLinkMessage will notify the given controllers about the existing link
SendRouterLinkMessage(link Xlink, channels ...channel.Channel)
// LinkListenersChanged notifies the registry that the router's link listener set changed, so it is
// republished to every controller
LinkListenersChanged()
// Inspect will return debug information about the state of links and the registry
Inspect(timeout time.Duration) *inspect.LinksInspectResult
+4
View File
@@ -71,6 +71,10 @@ func (self *testRegistryEnv) GetXlinkDialers() []xlink.Dialer {
panic("implement me")
}
func (self *testRegistryEnv) GetXlinkListenerSnapshot() (uint64, []xlink.Listener) {
return 0, nil
}
func (self *testRegistryEnv) GetCloseNotify() <-chan struct{} {
return self.closeNotify
}
+2 -1
View File
@@ -107,9 +107,10 @@ func (self *LinkStateChecker) HandleOther(msg *channel.Message, _ channel.Channe
// 5 = heartbeat
// 1007 = metrics message
// 1053 = LinkState
// 1056 = UpdateLinkListeners
// 201415 = connect events
if msg.ContentType == -33 || msg.ContentType == 5 || msg.ContentType == 1007 || msg.ContentType == 1053 ||
msg.ContentType == 20415 {
msg.ContentType == 1056 || msg.ContentType == 20415 {
logrus.Debug("ignoring heartbeats, reconnect pings and metrics")
return
}