Files
ziti/controller/handler_ctrl/bind.go
T
Paul Lorenz 444999bc5b Break the SDK terminator removal retry storm. Fixes #4156
- adds RemoveTerminatorsV2, an asynchronous control-channel removal, so a router
  no longer holds a request slot open waiting for a synchronous reply; gated on a
  new capability so routers fall back to the synchronous path against controllers
  that do not advertise it
- paces establish and remove retries with a per-terminator exponential backoff
  after a controller rejection, so a rejected operation is not re-sent on the next
  event-loop tick, which is what let a rate-limited removal sustain itself
- routes v2 removes to the leader and skips the ordered delete for a terminator the
  router confirms it created that no longer exists, so a storm of no-op retries
  cannot consume the command rate limiter
- gates that skip on the leader having applied everything committed when it took
  leadership, since a leader reports itself elected before those applies finish and
  would otherwise read a committed create as absent and drop its delete
- guards the leader term and every write to the caught-up flag with a dedicated
  lock, so a barrier completing alongside a leadership change cannot record a result
  for a term that has already ended
- scopes v2 removals to the requesting router, so a router can only remove
  terminators it owns on the asynchronous path as well as the synchronous one
- tracks in-flight removal batches on the router, resolving or requeueing them when
  the response arrives; lost responses self-heal via rate-limiter expiry and the
  retry scan
- waits for an outstanding operation before sending a terminator delete, and checks
  that before dequeuing, so a delete neither races a create the controller has
  committed but not applied nor falls out of the queue until the retry scan finds it
  minutes later
- matches a create response to the attempt that produced it, by control channel and
  reply sequence, since attempts overlap once one overruns the establishment timeout
  and every attempt carries the same terminator id; only the outstanding attempt's
  response may confirm the create or report the terminator idle
- records the attempt as the sender assigns its sequence, so a response cannot be
  processed before the request it answers is known, and withdraws an attempt whose
  send never queued
- reports a removal that succeeds past the establishment timeout as congestion
  rather than success, matching how the establish path classifies its own latency,
  since both resolve into the same limiter
- extracts the transient-error test both remove handlers share, so the v2 path
  treats a leaderless cluster as busy like v1 does instead of as a permanent
  failure, and the two cannot drift again
- applies the same delete sequencing and response correlation to the router-hosted
  (ER/T) registry, which cleared the same in-flight marker unguarded and dropped a
  deferred delete from its queue rather than leaving it there
- bounds the v2 response send with a timeout, so a router that stops draining its
  send queue cannot accumulate blocked responder goroutines on the controller
2026-09-24 13:24:51 -04:00

184 lines
7.5 KiB
Go

/*
Copyright NetFoundry Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package handler_ctrl
import (
"sync/atomic"
"time"
"github.com/openziti/ziti/v2/common/pb/ctrl_pb"
"github.com/openziti/ziti/v2/controller/model"
"github.com/sirupsen/logrus"
"github.com/michaelquigley/pfxlog"
"github.com/openziti/channel/v5"
"github.com/openziti/channel/v5/latency"
"github.com/openziti/foundation/v2/concurrenz"
"github.com/openziti/metrics"
"github.com/openziti/ziti/v2/common/trace"
"github.com/openziti/ziti/v2/controller/network"
"github.com/openziti/ziti/v2/controller/xctrl"
metrics2 "github.com/openziti/ziti/v2/router/metrics"
)
type bindHandler struct {
heartbeatOptions *channel.HeartbeatOptions
router *model.Router
network *network.Network
xctrls []xctrl.Xctrl
}
func newBindHandler(heartbeatOptions *channel.HeartbeatOptions, router *model.Router, network *network.Network, xctrls []xctrl.Xctrl) channel.BindHandler {
return &bindHandler{
heartbeatOptions: heartbeatOptions,
router: router,
network: network,
xctrls: xctrls,
}
}
func (self *bindHandler) BindChannel(binding channel.Binding) error {
log := pfxlog.Logger().WithFields(map[string]interface{}{
"routerId": self.router.Id,
"routerVersion": self.router.VersionInfo.Version,
})
log.Debug("binding router channel")
channel.AddReceiveHandlers(binding, newAlertHandler(self.router, self.network))
channel.AddReceiveHandlers(binding, newCircuitRequestHandler(self.router, self.network))
channel.AddReceiveHandlers(binding, newRouteResultHandler(self.network, self.router))
channel.AddReceiveHandlers(binding, newCircuitConfirmationHandler(self.network, self.router))
channel.AddReceiveHandlers(binding, newCreateTerminatorHandler(self.network, self.router))
channel.AddReceiveHandlers(binding, newRemoveTerminatorHandler(self.network, self.router))
channel.AddReceiveHandlers(binding, newRemoveTerminatorsHandler(self.network, self.router))
channel.AddReceiveHandlers(binding, newRemoveTerminatorsV2Handler(self.network, self.router))
channel.AddReceiveHandlers(binding, newUpdateTerminatorHandler(self.network, self.router))
channel.AddReceiveHandlers(binding, newLinkStateHandler(self.router, self.network))
channel.AddReceiveHandlers(binding, newRouterLinkHandler(self.router, self.network))
channel.AddReceiveHandlers(binding, newUpdateLinkListenersHandler(self.router, self.network))
channel.AddReceiveHandlers(binding, newVerifyRouterHandler(self.router, self.network))
channel.AddReceiveHandlers(binding, newFaultHandler(self.router, self.network))
channel.AddReceiveHandlers(binding, newMetricsHandler(self.network))
channel.AddReceiveHandlers(binding, newTraceHandler(self.network.GetTraceController()))
channel.AddReceiveHandlers(binding, newInspectHandler(self.network))
channel.AddReceiveHandlers(binding, newQuiesceRouterHandler(self.router, self.network))
channel.AddReceiveHandlers(binding, newDequiesceRouterHandler(self.router, self.network))
channel.AddReceiveHandlers(binding, newDecommissionRouterHandler(self.router, self.network))
channel.AddReceiveHandlers(binding, newUpdateRouterInterfacesHandler(self.router, self.network))
channel.AddReceiveHandlers(binding, newPingHandler())
channel.AddReceiveHandlers(binding, &channel.AsyncFunctionReceiveAdapter{
Type: int32(ctrl_pb.ContentType_ValidateTerminatorsV2ResponseType),
Handler: self.network.RouterMessaging.NewValidationResponseHandler(self.network, self.router),
})
channel.AddReceiveHandlers(binding, newSendClusterMembersHandler(self.router, self.network))
binding.AddPeekHandler(trace.NewChannelPeekHandler(self.network.GetAppId(), binding.GetChannel(), self.network.GetTraceController()))
binding.AddPeekHandler(metrics2.NewCtrlChannelPeekHandler(self.router.Id, self.network.GetMetricsRegistry()))
roundTripHistogram := self.network.GetMetricsRegistry().Histogram("ctrl.latency:" + self.router.Id)
queueTimeHistogram := self.network.GetMetricsRegistry().Histogram("ctrl.queue_time:" + self.router.Id)
binding.AddCloseHandler(channel.CloseHandlerF(func(ch channel.Channel) {
roundTripHistogram.Dispose()
queueTimeHistogram.Dispose()
}))
cb := &heartbeatCallback{
latencyMetric: roundTripHistogram,
queueTimeMetric: queueTimeHistogram,
ch: binding.GetChannel(),
latencySemaphore: concurrenz.NewSemaphore(2),
closeUnresponsiveTimeout: self.heartbeatOptions.CloseUnresponsiveTimeout,
}
cb.lastResponse.Store(time.Now().Add(self.heartbeatOptions.CloseUnresponsiveTimeout * 2).UnixMilli()) // wait at least 2x timeout before closing
channel.ConfigureHeartbeat(binding, self.heartbeatOptions.SendInterval, self.heartbeatOptions.CheckInterval, cb)
xctrlDone := make(chan struct{})
for _, x := range self.xctrls {
if err := x.BindChannel(binding); err != nil {
return err
}
if err := x.Run(binding.GetChannel(), self.network.GetDb(), xctrlDone); err != nil {
return err
}
}
if len(self.xctrls) > 0 {
binding.AddCloseHandler(newXctrlCloseHandler(xctrlDone))
}
binding.AddCloseHandler(newCloseHandler(self.router, self.network))
return nil
}
type heartbeatCallback struct {
latencyMetric metrics.Histogram
queueTimeMetric metrics.Histogram
lastResponse atomic.Int64
ch channel.Channel
latencySemaphore concurrenz.Semaphore
closeUnresponsiveTimeout time.Duration
}
func (self *heartbeatCallback) HeartbeatTx(int64) {}
func (self *heartbeatCallback) HeartbeatRx(int64) {}
func (self *heartbeatCallback) HeartbeatRespTx(int64) {}
func (self *heartbeatCallback) HeartbeatRespRx(ts int64) {
now := time.Now()
self.lastResponse.Store(now.UnixMilli())
self.latencyMetric.Update(now.UnixNano() - ts)
}
func (self *heartbeatCallback) timeSinceLastResponse(nowUnixMillis int64) time.Duration {
return time.Duration(nowUnixMillis-self.lastResponse.Load()) * time.Millisecond
}
func (self *heartbeatCallback) CheckHeartBeat() {
now := time.Now().UnixMilli()
if self.timeSinceLastResponse(now) > self.closeUnresponsiveTimeout {
log := self.logger()
log.Error("heartbeat not received in time, closing control channel connection")
if err := self.ch.Close(); err != nil {
log.WithError(err).Error("error while closing control channel connection")
}
}
go self.checkQueueTime()
}
func (self *heartbeatCallback) checkQueueTime() {
if !self.latencySemaphore.TryAcquire() {
self.logger().Warn("unable to check queue time, too many check already running")
return
}
defer self.latencySemaphore.Release()
sendTracker := &latency.SendTimeTracker{
Handler: func(latencyType latency.Type, latency time.Duration) {
self.queueTimeMetric.Update(latency.Nanoseconds())
},
StartTime: time.Now(),
}
if err := self.ch.Send(sendTracker); err != nil && !self.ch.IsClosed() {
self.logger().WithError(err).Error("unable to send queue time tracer")
}
}
func (self *heartbeatCallback) logger() *logrus.Entry {
return pfxlog.Logger().WithField("channelType", "router").WithField("channelId", self.ch.Id())
}