Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions pkg/packet/bgp/bgp.go
Original file line number Diff line number Diff line change
Expand Up @@ -17953,6 +17953,15 @@ func NewBGPKeepAliveMessage() *BGPMessage {
}
}

// Message Subtype of ROUTE-REFRESH (RFC 7313 Section 3.2): a normal
// request, the Beginning of Route Refresh (BoRR) and the End of Route
// Refresh (EoRR).
const (
BGP_ROUTE_REFRESH_NORMAL uint8 = 0
BGP_ROUTE_REFRESH_BORR uint8 = 1
BGP_ROUTE_REFRESH_EORR uint8 = 2
)

type BGPRouteRefresh struct {
AFI uint16
Demarcation uint8
Expand Down
28 changes: 28 additions & 0 deletions pkg/server/fsm.go
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,9 @@ type fsmMsg struct {

type fsmOutgoingMsg struct {
Paths []*table.Path
// Message is sent as it is, after the UPDATEs of the messages queued
// before it, for example a ROUTE-REFRESH with BoRR or EoRR.
Message *bgp.BGPMessage
}

const (
Expand Down Expand Up @@ -1423,6 +1426,7 @@ func capabilitiesFromConfig(pConf *oc.Neighbor) []bgp.ParameterCapabilityInterfa
fqdn, _ := os.Hostname()
caps := make([]bgp.ParameterCapabilityInterface, 0, 4)
caps = append(caps, bgp.NewCapRouteRefresh())
caps = append(caps, bgp.NewCapEnhancedRouteRefresh())
caps = append(caps, bgp.NewCapFQDN(fqdn, ""))

if pConf.Config.SendSoftwareVersion || pConf.Config.PeerType == oc.PEER_TYPE_INTERNAL {
Expand Down Expand Up @@ -2183,6 +2187,12 @@ func (h *fsmHandler) sendMessageloop(ctx context.Context, conn net.Conn, stateRe
slog.Any("attributes", update.PathAttributes))
case bgp.BGP_MSG_KEEPALIVE:
// nothing to do
case bgp.BGP_MSG_ROUTE_REFRESH:
rr := m.Body.(*bgp.BGPRouteRefresh)
debuglog.Log(fsm.logger, "sent route refresh",
slog.Any("State", debuglog.Lazy(fsm.state.Load())),
slog.Any("Family", debuglog.Lazy(bgp.NewFamily(rr.AFI, rr.SAFI))),
slog.Int("Subtype", int(rr.Demarcation)))
default:
fsm.logger.Error("unexpected message sent",
slog.String("State", fsm.state.String()),
Expand All @@ -2199,10 +2209,19 @@ func (h *fsmHandler) sendMessageloop(ctx context.Context, conn net.Conn, stateRe
case o := <-h.outgoing.Out():
switch m := o.(type) {
case *fsmOutgoingMsg:
if m.Message != nil {
if err := send(m.Message); err != nil {
return nil
}
continue
}
const maxCoalesceMsgs = 2048 // safety cap
paths := m.Paths
coalescedMsgs := 1
// a message to send after the coalesced UPDATEs
var next *bgp.BGPMessage
// coalesce queued messages for more efficient UPDATE packing
coalesce:
for coalescedMsgs < maxCoalesceMsgs {
select {
case <-ctx.Done():
Expand All @@ -2212,6 +2231,10 @@ func (h *fsmHandler) sendMessageloop(ctx context.Context, conn net.Conn, stateRe
select {
case o2 := <-h.outgoing.Out():
if m2, ok := o2.(*fsmOutgoingMsg); ok {
if m2.Message != nil {
next = m2.Message
break coalesce
}
paths = append(paths, m2.Paths...)
coalescedMsgs++
continue
Expand All @@ -2236,6 +2259,11 @@ func (h *fsmHandler) sendMessageloop(ctx context.Context, conn net.Conn, stateRe
return nil
}
}
if next != nil {
if err := send(next); err != nil {
return nil
}
}
default:
return nil
}
Expand Down
44 changes: 44 additions & 0 deletions pkg/server/fsm_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3245,3 +3245,47 @@ func TestConnectLoopWaitsInOpenConfirm(t *testing.T) {
c.Close()
}
}

// A raw message in the outgoing queue goes out after the UPDATEs of the
// paths queued before it and before those queued after it, also when the
// send loop coalesces paths.
func TestSendMessageloop_MessageKeepsOrder(t *testing.T) {
m := NewMockConnection()
_, h := makePeerAndHandler(m)
t.Cleanup(func() { h.outgoing.Close(); m.Close() })

borr := bgp.NewBGPRouteRefreshMessage(bgp.AFI_IP, bgp.BGP_ROUTE_REFRESH_BORR, bgp.SAFI_UNICAST)
eorr := bgp.NewBGPRouteRefreshMessage(bgp.AFI_IP, bgp.BGP_ROUTE_REFRESH_EORR, bgp.SAFI_UNICAST)
h.outgoing.In() <- &fsmOutgoingMsg{Message: borr}
h.outgoing.In() <- &fsmOutgoingMsg{Paths: []*table.Path{makePath(t, "10.0.0.0/24", "192.168.1.1", 0)}}
h.outgoing.In() <- &fsmOutgoingMsg{Paths: []*table.Path{makePath(t, "10.0.1.0/24", "192.168.1.1", 0)}}
h.outgoing.In() <- &fsmOutgoingMsg{Message: eorr}
h.outgoing.In() <- &fsmOutgoingMsg{Paths: []*table.Path{makePath(t, "10.0.2.0/24", "192.168.1.1", 0)}}

ctx, cancel := context.WithCancel(context.Background())
wg := &sync.WaitGroup{}
wg.Add(1)
go h.sendMessageloop(ctx, m, make(chan fsmStateReason, 3), wg)

var order []string
require.Eventually(t, func() bool {
order = order[:0]
for _, msg := range parseBGPUpdates(t, m.GetSentMessages()) {
switch b := msg.Body.(type) {
case *bgp.BGPRouteRefresh:
order = append(order, fmt.Sprintf("rr%d", b.Demarcation))
case *bgp.BGPUpdate:
for _, n := range b.NLRI {
order = append(order, n.NLRI.String())
}
}
}
return len(order) == 5
}, 5*time.Second, 10*time.Millisecond)
cancel()
wg.Wait()

require.Equal(t, "rr1", order[0])
require.ElementsMatch(t, []string{"10.0.0.0/24", "10.0.1.0/24"}, order[1:3])
require.Equal(t, []string{"rr2", "10.0.2.0/24"}, order[3:])
}
38 changes: 38 additions & 0 deletions pkg/server/peer.go
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,9 @@ type peer struct {
grHelper gr.Helper
grRestartTimer *time.Timer
grLLGRTimers map[bgp.Family]*time.Timer
// borrTimers bounds how long the routes that a BoRR marked stale stay
// without an EoRR (RFC 7313 Section 4), per family.
borrTimers map[bgp.Family]*time.Timer // protected by fsm.lock
// Route Target Membership handler after import policy (for constrained VPN distribution).
rtmHandler *table.RouteTargetMembershipHandler
// Route refresh in progress, during an established session or route refresh, this need to be atomic to avoid out of order updates
Expand Down Expand Up @@ -514,6 +517,41 @@ func (peer *peer) setRtcEORWait(waiting bool) {
debuglog.Log(peer.fsm.logger, "Set rtcEORWait", slog.Bool("Data", waiting))
}

// eorReceived reports whether a peer that sent the graceful restart
// capability has sent End-of-RIB for rf. It is true for a peer that did not
// send the capability, whatever our own graceful restart configuration is
// (RFC 7313 Section 4).
func (peer *peer) eorReceived(rf bgp.Family) bool {
peer.fsm.lock.Lock()
_, gr := peer.fsm.capMap[bgp.BGP_CAP_GRACEFUL_RESTART]
peer.fsm.lock.Unlock()
if !gr {
return true
}
for _, a := range peer.fsm.pConf.ReadOnly().AfiSafis {
if a.State.Family == rf {
return a.MpGracefulRestart.State.EndOfRibReceived
}
}
return true
}

// stopBorrTimers stops the BoRR timers of families, or all of them, and
// reports whether one was running.
func (peer *peer) stopBorrTimers(families ...bgp.Family) bool {
peer.fsm.lock.Lock()
defer peer.fsm.lock.Unlock()
stopped := false
for rf, t := range peer.borrTimers {
if len(families) == 0 || slices.Contains(families, rf) {
t.Stop()
delete(peer.borrTimers, rf)
stopped = true
}
}
return stopped
}

func (peer *peer) configuredRFlist() []bgp.Family {
conf := peer.fsm.pConf.ReadOnly()
rfs, _ := oc.AfiSafis(conf.AfiSafis).ToRfList()
Expand Down
114 changes: 114 additions & 0 deletions pkg/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -635,6 +635,13 @@ func sendfsmOutgoingMsg(peer *peer, paths []*table.Path) {
}
}

// sendfsmOutgoingMsgRaw queues m after the paths queued before.
func sendfsmOutgoingMsgRaw(peer *peer, m *bgp.BGPMessage) {
peer.fsm.outgoingCh.In() <- &fsmOutgoingMsg{
Message: m,
}
}

func isASLoop(peer *peer, path *table.Path) bool {
return slices.Contains(path.GetAsList(), peer.AS())
}
Expand Down Expand Up @@ -1635,18 +1642,123 @@ func (s *BgpServer) handleRouteRefresh(peer *peer, e *fsmMsg) {

peer.fsm.lock.Lock()
_, ok := peer.fsm.capMap[bgp.BGP_CAP_ROUTE_REFRESH]
_, enhanced := peer.fsm.capMap[bgp.BGP_CAP_ENHANCED_ROUTE_REFRESH]
peer.fsm.lock.Unlock()
if !ok {
peer.fsm.logger.Warn("ROUTE_REFRESH received but the capability wasn't advertised")
return
}
rfList := []bgp.Family{rf}
// RFC 7313: with Enhanced Route Refresh the peer brackets its
// re-advertisement with BoRR and EoRR. The routes of the family that
// the peer does not send again by EoRR are gone.
switch rr.Demarcation {
case bgp.BGP_ROUTE_REFRESH_NORMAL:
case bgp.BGP_ROUTE_REFRESH_BORR:
if !enhanced {
peer.fsm.logger.Warn("BoRR received but the enhanced route refresh capability wasn't advertised", slog.String("Family", rf.String()))
return
}
if !peer.eorReceived(rf) {
// RFC 7313 Section 4: a BoRR from a peer that sent the
// graceful restart capability is ignored before its
// End-of-RIB.
peer.fsm.logger.Warn("BoRR before End-of-RIB from a graceful restart peer, ignored", slog.String("Family", rf.String()))
return
}
peer.adjRibIn.StaleAll(rfList)
s.startBorrTimer(peer, rf)
return
case bgp.BGP_ROUTE_REFRESH_EORR:
if !enhanced {
peer.fsm.logger.Warn("EoRR received but the enhanced route refresh capability wasn't advertised", slog.String("Family", rf.String()))
return
}
// RFC 7313 Section 4: "A BGP speaker MAY ignore any EoRR message
// received without a prior receipt of an associated BoRR
// message." Graceful restart marks routes stale too, so an EoRR
// without a BoRR must not remove them.
if !peer.stopBorrTimers(rf) {
peer.fsm.logger.Warn("EoRR without BoRR, ignored", slog.String("Family", rf.String()))
return
}
s.dropBorrStale(peer, rf)
return
default:
// RFC 7313 Section 5: ignore other subtypes.
peer.fsm.logger.Warn("ROUTE_REFRESH with an unknown subtype, ignored", slog.Int("Subtype", int(rr.Demarcation)), slog.String("Family", rf.String()))
return
}
if enhanced && (s.deferred(rf) || rf != bgp.RF_RTC_UC && peer.getRtcEORWait()) {
// The initial advertisement of rf, our own graceful restart or
// the route target membership defers it, is still to come with
// its End-of-RIB and covers the request. RFC 7313 Section 4: no
// BoRR before the End-of-RIB.
debuglog.Log(peer.fsm.logger, "route refresh before the initial End-of-RIB, the initial advertisement answers it", slog.String("Family", rf.String()))
return
}
if enhanced {
sendfsmOutgoingMsgRaw(peer, bgp.NewBGPRouteRefreshMessage(rf.Afi(), bgp.BGP_ROUTE_REFRESH_BORR, rf.Safi()))
Comment thread
MaxRink marked this conversation as resolved.
Resolved
}
s.getBestFromLocalCallback(peer, rfList, true, true, func(paths []*table.Path, filtered []*table.Path) {
if len(paths) > 0 {
peer.updateRoutes(paths...)
sendfsmOutgoingMsg(peer, paths)
}
})
if enhanced {
sendfsmOutgoingMsgRaw(peer, bgp.NewBGPRouteRefreshMessage(rf.Afi(), bgp.BGP_ROUTE_REFRESH_EORR, rf.Safi()))
}
}

// defaultBorrStaleTime is how long the routes that a BoRR marked stale stay
// without an EoRR when the neighbor has no graceful restart
// stale-routes-time, like FRR's default stalepath-time.
const defaultBorrStaleTime = 360 * time.Second

// startBorrTimer removes the routes of rf that are still stale when the peer
// sends no EoRR in time (RFC 7313 Section 4: a local upper bound on how long
// stale routes stay).
func (s *BgpServer) startBorrTimer(peer *peer, rf bgp.Family) {
d := defaultBorrStaleTime
if t := peer.fsm.pConf.ReadOnly().GracefulRestart.Config.StaleRoutesTime; t > 0 {
d = time.Duration(t * float64(time.Second))
}
peer.stopBorrTimers(rf)
peer.fsm.lock.Lock()
defer peer.fsm.lock.Unlock()
if peer.borrTimers == nil {
peer.borrTimers = make(map[bgp.Family]*time.Timer)
}
var timer *time.Timer
timer = time.AfterFunc(d, func() {
_ = s.mgmtOperation(func() error {
peer.fsm.lock.Lock()
current := peer.borrTimers[rf] == timer
if current {
delete(peer.borrTimers, rf)
}
peer.fsm.lock.Unlock()
if !current {
// stopped by an EoRR or the end of the session
return nil
}
peer.fsm.logger.Info("no EoRR after BoRR, removing the stale routes", slog.String("Family", rf.String()), slog.Duration("Duration", d))
s.dropBorrStale(peer, rf)
return nil
}, false)
})
peer.borrTimers[rf] = timer
}

// dropBorrStale removes the peer's routes of rf that are still stale after a
// BoRR and propagates the withdrawals. Like dropAdjRIBIn, it reports them to
// the pre-policy Adj-RIB-In watchers (BMP) first: the peer did not withdraw
// them on the wire.
func (s *BgpServer) dropBorrStale(peer *peer, rf bgp.Family) {
dropped := peer.adjRibIn.DropStale([]bgp.Family{rf})
s.notifyAdjInWithdrawWatcher(peer, dropped)
s.propagateUpdate(peer, dropped)
}

// dropAdjRIBIn removes the peer's Adj-RIB-In for the given families and
Expand Down Expand Up @@ -1997,6 +2109,7 @@ func (s *BgpServer) propagateUpdateToNeighbors(rib *table.TableManager, source *

func (s *BgpServer) stopNeighbor(peer *peer, oldState bgp.FSMState, e *fsmMsg) {
peer.stopGRTimers()
peer.stopBorrTimers()
// Guard against the TOCTOU window between the RUnlock and write-Lock in
// handleFSMMessage: only delete if the map still holds this exact peer
key := peer.neighborAddress()
Expand Down Expand Up @@ -2409,6 +2522,7 @@ func (s *BgpServer) handleFSMMessage(peer *peer, e *fsmMsg) {
peer.fsm.pConf.Update(&conf)
peer.prefixLimitWarned = make(map[bgp.Family]bool)
peer.fsm.lock.Unlock()
peer.stopBorrTimers()

// Publish the down state before clearing advertised-route state.
// This avoids rebuilding RIB-out bookkeeping by propagation that starts after the reset.
Expand Down
Loading