mirror of
https://github.com/openziti/ziti.git
synced 2026-09-10 08:45:41 +00:00
99ca242ecc
The controller decided which of two racing connections for a router was current
by comparing router instances, but loaded one per connect by evicting the router
cache and reading back through it. Two connects could both evict, and whichever
read second was handed the instance the first had just published. A shared
instance makes the two connections indistinguishable: the connect path cannot
reject the second into an occupied slot, and when either channel dies the
disconnect path finds itself current and tears down the registration the other is
still using. The surviving channel is never re-bound, so the router stays
connected at the transport layer while absent from the model, unable to recover.
Connect and disconnect were also unserialized, so a stale or superseded
disconnect could interleave with a live connection and take its links with it.
- serializes a router's connect and disconnect with a per-router striped lock
- keeps at most one connection per router: a connect into an occupied slot is
rejected via an error from ConnectRouter, so the bind fails and NewChannel
closes it without starting rx or registering it, and the occupant is displaced;
the router redials into the freed slot
- displaces an occupant by closing its channel and also invoking the teardown
directly, since a channel that is already closed never fires its close handler
again; without this a dead but still registered connection holds the slot
forever and every redial is rejected against a slot nothing can free
- refuses a connect whose control channel is already closed rather than
registering it, so a connection no disconnect could ever remove is never
published
- gives every connection its own router instance via RouterManager.NewCtrlChanRouter,
read through readUncached so the cache neither supplies nor receives it, which
is what makes comparing instances meaningful
- moves recording the channel and connect time out of the accept path, so a
caller cannot attach the wrong channel or forget to attach one
- serializes link publication with that teardown on the same per-router stripe.
Validating currency and then publishing without it is a check-then-act: a
report can find the connection current and, by the time it reaches the link
manager, the teardown has already snapshotted and cleared the router's links,
so the link is recreated after everything that would have removed it. It is
then absent from the router's own index while still in the link table with a
disconnected source, and a reconnect reporting the same iteration can adopt
that stale source instead of rebuilding the link
- guards the entire DisconnectRouter teardown by connection currency, all or
nothing, and clears the connected flag and link index only when the
registration was actually given up, with the flag cleared under the same shard
lock as the map removal so the two cannot be observed disagreeing; the connected flag decides whether the
controller accepts a router's link reports, so clearing it for the wrong
connection silences a router that is up and reporting
- reduces MarkConnected to publishing the connection; the takeover-close moves
into ConnectRouter's reject path
- makes the per-router unlock idempotent so callers can defer it as a leak-safety
net and still unlock early before closing a channel outside the lock
- stops the replaced RouterSender in routerTxMap.Add so a takeover does not leak
the old sender's goroutine when the broker's asynchronous RouterDisconnected
loses the race to the redial's RouterConnected
- discards pending peer state changes for a router whose channel has closed,
since sending on one fails immediately and the failed send is retried as soon
as the event loop turns, spinning the loop and flooding the log
- queues the peer-state send-done event on every path, so a missing channel can
no longer leave sendInProgress set and stall that router's updates permanently
- resolves a router's version from its connected instance when validating link
conn info, since the version arrives in the hello and so is absent from an
instance loaded from the database
- normalizes both endpoints to the connected instance in shortestPath, which is
keyed and compared by pointer and so treated an endpoint held as any other
instance of the same router as absent from the graph, reporting a router as
unroutable from itself. That worked before only because the connect path
published its instance into the router cache, so a cache read and the connected
map returned the same object; nothing stated the requirement
- configures test logging once per package in TestMain, so a test no longer
writes global logger state while a previous test's shutdown logging reads it
Original issue: #4196.
(cherry picked from commit 647c4daa1e)
208 lines
7.5 KiB
Go
208 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 (
|
|
"github.com/google/uuid"
|
|
"github.com/michaelquigley/pfxlog"
|
|
"github.com/openziti/channel/v4"
|
|
"github.com/openziti/ziti/v2/common/capabilities"
|
|
"github.com/openziti/ziti/v2/common/ctrlchan"
|
|
"github.com/openziti/ziti/v2/common/pb/ctrl_pb"
|
|
"github.com/openziti/ziti/v2/controller/change"
|
|
"github.com/openziti/ziti/v2/controller/network"
|
|
"github.com/openziti/ziti/v2/controller/xctrl"
|
|
"github.com/pkg/errors"
|
|
"google.golang.org/protobuf/proto"
|
|
)
|
|
|
|
type CtrlAccepter struct {
|
|
network *network.Network
|
|
xctrls []xctrl.Xctrl
|
|
options *channel.Options
|
|
heartbeatOptions *channel.HeartbeatOptions
|
|
traceHandler *channel.TraceHandler
|
|
}
|
|
|
|
func NewCtrlAccepter(network *network.Network,
|
|
xctrls []xctrl.Xctrl,
|
|
options *channel.Options,
|
|
heartbeatOptions *channel.HeartbeatOptions,
|
|
traceHandler *channel.TraceHandler) *CtrlAccepter {
|
|
return &CtrlAccepter{
|
|
network: network,
|
|
xctrls: xctrls,
|
|
options: options,
|
|
heartbeatOptions: heartbeatOptions,
|
|
traceHandler: traceHandler,
|
|
}
|
|
}
|
|
|
|
// NewMultiListener returns an acceptor that handles both grouped (multi-underlay) and
|
|
// ungrouped (single underlay) connections from routers.
|
|
func (self *CtrlAccepter) NewMultiListener() channel.UnderlayAcceptor {
|
|
multiListener := channel.NewMultiListener(self.HandleGroupedUnderlay, self.AcceptUnderlay)
|
|
return &multiListenerAcceptor{multiListener: multiListener}
|
|
}
|
|
|
|
// multiListenerAcceptor wraps MultiListener to implement UnderlayAcceptor
|
|
type multiListenerAcceptor struct {
|
|
multiListener *channel.MultiListener
|
|
}
|
|
|
|
func (self *multiListenerAcceptor) AcceptUnderlay(underlay channel.Underlay) error {
|
|
self.multiListener.AcceptUnderlay(underlay)
|
|
return nil
|
|
}
|
|
|
|
// HandleGroupedUnderlay handles incoming grouped connections from routers that support
|
|
// multi-underlay control channels. It creates a MultiChannel with ListenerCtrlChannel.
|
|
func (self *CtrlAccepter) HandleGroupedUnderlay(underlay channel.Underlay, closeCallback func()) (channel.MultiChannel, error) {
|
|
if _, hasSecret := underlay.Headers()[channel.GroupSecretHeader]; !hasSecret {
|
|
underlay.Headers()[channel.GroupSecretHeader] = []byte(uuid.NewString())
|
|
}
|
|
|
|
listenerCtrlChan := ctrlchan.NewListenerCtrlChannel()
|
|
multiConfig := channel.MultiChannelConfig{
|
|
LogicalName: "ctrl/" + underlay.Id(),
|
|
Options: self.options,
|
|
UnderlayHandler: listenerCtrlChan,
|
|
BindHandler: channel.BindHandlerF(func(binding channel.Binding) error {
|
|
binding.AddCloseHandler(channel.CloseHandlerF(func(ch channel.Channel) {
|
|
closeCallback()
|
|
}))
|
|
return self.Bind(binding)
|
|
}),
|
|
Underlay: underlay,
|
|
}
|
|
mc, err := channel.NewMultiChannel(&multiConfig)
|
|
if err != nil {
|
|
pfxlog.Logger().WithError(err).Errorf("failure accepting ctrl channel %v with multi-underlay", underlay.Label())
|
|
return nil, err
|
|
}
|
|
return mc, nil
|
|
}
|
|
|
|
// AcceptUnderlay handles incoming ungrouped connections from routers that don't support
|
|
// multi-underlay control channels (backward compatibility).
|
|
func (self *CtrlAccepter) AcceptUnderlay(underlay channel.Underlay) error {
|
|
_, err := self.HandleGroupedUnderlay(underlay, func() {})
|
|
return err
|
|
}
|
|
|
|
func (self *CtrlAccepter) Bind(binding channel.Binding) error {
|
|
binding.GetChannel().SetLogicalName(binding.GetChannel().Id())
|
|
ch := binding.GetChannel()
|
|
|
|
log := pfxlog.Logger().WithField("routerId", ch.Id())
|
|
// A fresh instance per connection, carrying this channel: that is what lets connect and disconnect tell
|
|
// two connections for one router apart, and keeps them from writing over each other's state.
|
|
r, err := self.network.NewCtrlChanRouter(ch)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
var ctrlChanListeners map[string][]string
|
|
|
|
if ch.Underlay().Headers() != nil {
|
|
if versionValue, found := ch.Underlay().Headers()[channel.HelloVersionHeader]; found {
|
|
if versionInfo, err := self.network.VersionProvider.EncoderDecoder().Decode(versionValue); err == nil {
|
|
r.VersionInfo = versionInfo
|
|
log = log.WithField("version", r.VersionInfo.Version).
|
|
WithField("revision", r.VersionInfo.Revision).
|
|
WithField("buildDate", r.VersionInfo.BuildDate).
|
|
WithField("os", r.VersionInfo.OS).
|
|
WithField("arch", r.VersionInfo.Arch)
|
|
} else {
|
|
return errors.Wrap(err, "could not parse version info from router hello, not accepting router connection")
|
|
}
|
|
} else {
|
|
return errors.New("no version info header, not accepting router connection")
|
|
}
|
|
|
|
r.Listeners = nil
|
|
headers := ch.Underlay().Headers()
|
|
|
|
// Determine header locations based on router capabilities. 2.0+ routers
|
|
// send a CapabilitiesHeader with RouterMultiChannel set and use header IDs
|
|
// in the 1000+ range. Pre-2.0 routers use legacy IDs (10-12) and don't
|
|
// send a CapabilitiesHeader.
|
|
r.Capabilities = capabilities.GetCapabilities(headers)
|
|
useNewHeaders := capabilities.IsSet(r.Capabilities, capabilities.RouterMultiChannel)
|
|
|
|
listenersHeaderId := ctrl_pb.LegacyListenersHeader
|
|
if useNewHeaders {
|
|
listenersHeaderId = int32(ctrl_pb.ControlHeaders_ListenersHeader)
|
|
}
|
|
|
|
if val, found := headers[listenersHeaderId]; found {
|
|
listeners := &ctrl_pb.Listeners{}
|
|
if err = proto.Unmarshal(val, listeners); err != nil {
|
|
log.WithError(err).Error("unable to unmarshall listeners value")
|
|
} else {
|
|
r.SetLinkListeners(listeners.Listeners)
|
|
for _, listener := range listeners.Listeners {
|
|
log.WithField("address", listener.GetAddress()).
|
|
WithField("protocol", listener.GetProtocol()).
|
|
WithField("costTags", listener.GetCostTags()).
|
|
Debug("router listener")
|
|
}
|
|
}
|
|
} else {
|
|
log.Debug("no advertised listeners")
|
|
}
|
|
|
|
if val, found := ch.Underlay().Headers()[int32(ctrl_pb.ControlHeaders_CtrlChanListenersHeader)]; found {
|
|
ctrlListeners := &ctrl_pb.CtrlChanListeners{}
|
|
if err = proto.Unmarshal(val, ctrlListeners); err != nil {
|
|
log.WithError(err).Error("unable to unmarshal ctrl chan listeners value")
|
|
} else {
|
|
ctrlChanListeners = make(map[string][]string, len(ctrlListeners.Listeners))
|
|
for _, listener := range ctrlListeners.Listeners {
|
|
ctrlChanListeners[listener.Address] = listener.Groups
|
|
}
|
|
}
|
|
}
|
|
|
|
changeCtx := change.NewControlChannelChange(r.Id, r.Name, "router.connect", ch)
|
|
self.network.Router.UpdateCtrlChanListeners(r, ctrlChanListeners, changeCtx)
|
|
} else {
|
|
return errors.New("channel provided no headers, not accepting router connection as version info not provided")
|
|
}
|
|
|
|
if err := binding.Bind(newBindHandler(self.heartbeatOptions, r, self.network, self.xctrls)); err != nil {
|
|
return errors.Wrap(err, "error binding router")
|
|
}
|
|
|
|
if self.traceHandler != nil {
|
|
binding.AddPeekHandler(self.traceHandler)
|
|
}
|
|
|
|
if err = self.network.ConnectRouter(r); err != nil {
|
|
if network.IsConnectRejected(err) {
|
|
log.Info("router connect rejected; another connection is already current, router will redial")
|
|
}
|
|
// Returning the error fails the bind, so NewChannel closes this channel's underlay without
|
|
// starting rx or registering it. That preserves the rx-gate for a rejected connection.
|
|
return err
|
|
}
|
|
|
|
log.Info("accepted new router connection")
|
|
|
|
return nil
|
|
}
|