Files
ziti/controller/command/command.go
T
Paul Lorenz 942d1a72bc Stop routers dropping controllers on a follower's stale controller list. Fixes #4573
- applies controller lists, leader announcements, controller address changes and index resets on one
  goroutine in arrival order, so checking an update's index, applying it and recording it is one
  step and no control channel's receive goroutine waits on another controller's update
- lets only a leader's list at a newer index replace the controller set; any other list at or above
  the recorded version only adds, merging into the router's stored details and connected controllers
- applies a leader's list at the recorded version as additions, so a router missing controllers
  recovers when the leader resends
- keeps an inbound controller's socket address out of the saved endpoints, and fills in a saved
  controller that has no endpoints when a later list gives some
- orders leadership claims by raft term: adds a raftTerm field to UpdateCtrlAddresses and
  UpdateClusterLeader, which controllers read together with leadership so both describe the same raft
  term; claims without one, from older controllers, still apply as they arrive
- folds the cluster leader handler into the same worker
- asks every connected controller for its list while waiting for the leader's, without waiting on a
  full send queue, one request run at a time, stopping when the router closes
- bounds the waiting updates: past the bound it drops waiting lists and announcements, keeps each
  controller's latest address change, and requests the leader's list
- fixes a router crash applying a controller's new address before any controller details were
  stored, and keeps connected controllers the router has no details for
- stops clustered controllers sending the newListener address, which the cluster's controller lists
  would undo, warns when it is configured, and notes this in the sample configs
- tests list handling, leadership ordering, overflow, the request loop, address changes and the
  controller's raft term read
- notes the fix in the changelog
2026-11-04 12:38:24 -05:00

210 lines
6.4 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 command
import (
"reflect"
"sync"
"github.com/michaelquigley/pfxlog"
"github.com/openziti/channel/v5"
"github.com/openziti/foundation/v2/debugz"
"github.com/openziti/foundation/v2/rate"
"github.com/openziti/ziti/v2/common/pb/ctrl_pb"
"github.com/openziti/ziti/v2/controller/apierror"
"github.com/openziti/ziti/v2/controller/change"
"github.com/openziti/ziti/v2/controller/storage/boltz"
"github.com/sirupsen/logrus"
)
// Command instances represent actions to be taken by the fabric controller. They are serializable,
// so they can be shipped from one controller for RAFT coordination
type Command interface {
// Apply runs the commands
Apply(ctx boltz.MutateContext) error
// GetChangeContext returns the change context associated with the command
GetChangeContext() *change.Context
// Encode returns a serialized representation of the command
Encode() ([]byte, error)
}
// CriticalCommand marks commands that establish base state (e.g. a snapshot restore). A failed apply
// of one must halt the node rather than log-and-advance the raft index, which would leave the node
// caught up on index but missing data. Ordinary commands are logged and skipped on failure.
type CriticalCommand interface {
Command
IsCriticalCommand()
}
// Validatable marks a command whose Validate runs before dispatch and again on the leader before
// the command enters the raft log. Validate reads only the command's own fields and local
// configuration, never the database: the serving controller's view may trail the leader, and on
// the leader entries already in the log apply first, so a check that depends on stored state
// belongs in Apply. It is deterministic and free of side effects, since it runs more than once.
type Validatable interface {
Validate() error
}
// Dispatcher instances will take a command and either send it to the leader to be applied, or if the current
// system is the leader, apply it locally
type Dispatcher interface {
Dispatch(command Command) error
IsLeaderOrLeaderless() bool
IsLeaderless() bool
IsLeader() bool
// IsLeaderAndCaughtUp reports whether this node is the leader and has applied everything that
// was committed when it took leadership. Required rather than IsLeader when a local read decides
// whether a replicated mutation is needed.
IsLeaderAndCaughtUp() bool
// LeadershipTerm returns a raft term and whether this node led it, read so both describe the same
// term. Without raft the term is 0.
LeadershipTerm() (term uint64, isLeader bool)
GetPeers() map[string]channel.Channel
GetRateLimiter() rate.RateLimiter
Bootstrap() error
CtrlAddresses() (uint64, []string, []*ctrl_pb.CtrlDetail)
// GetDecoders returns the command decoder registry used to decode commands dispatched
// through this dispatcher. Each dispatcher owns its own registry so multiple controllers
// in one process don't decode each other's commands.
GetDecoders() Decoders
}
// LocalDispatcher should be used when running a non-clustered system
type LocalDispatcher struct {
EncodeDecodeCommands bool
Limiter rate.RateLimiter
decodersInit sync.Once
decoders Decoders
}
func (self *LocalDispatcher) GetDecoders() Decoders {
self.decodersInit.Do(func() {
self.decoders = NewDecoders()
})
return self.decoders
}
func (self *LocalDispatcher) Bootstrap() error {
return nil
}
func (self *LocalDispatcher) IsLeader() bool {
return true
}
func (self *LocalDispatcher) LeadershipTerm() (uint64, bool) {
return 0, true
}
// IsLeaderAndCaughtUp is always true without raft: there is no log for the local view to trail.
func (self *LocalDispatcher) IsLeaderAndCaughtUp() bool {
return true
}
func (self *LocalDispatcher) IsLeaderOrLeaderless() bool {
return true
}
func (self *LocalDispatcher) IsLeaderless() bool {
return false
}
func (self *LocalDispatcher) GetPeers() map[string]channel.Channel {
return nil
}
func (self *LocalDispatcher) GetRateLimiter() rate.RateLimiter {
return self.Limiter
}
func (self *LocalDispatcher) CtrlAddresses() (uint64, []string, []*ctrl_pb.CtrlDetail) {
return 0, nil, nil
}
func (self *LocalDispatcher) Dispatch(command Command) error {
defer func() {
if p := recover(); p != nil {
pfxlog.Logger().
WithField(logrus.ErrorKey, p).
WithField("cmdType", reflect.TypeOf(command)).
Error("error while dispatching command of type")
debugz.DumpLocalStack()
panic(p)
}
}()
if validatable, ok := command.(Validatable); ok {
if err := validatable.Validate(); err != nil {
return err
}
}
changeCtx := command.GetChangeContext()
if changeCtx == nil {
changeCtx = change.New().SetSourceType("unattributed").SetChangeAuthorType(change.AuthorTypeUnattributed)
}
if self.EncodeDecodeCommands {
bytes, err := command.Encode()
if err != nil {
return err
}
cmd, err := self.GetDecoders().Decode(bytes)
if err != nil {
return err
}
command = cmd
}
return self.Limiter.RunRateLimited(func() error {
if err := CheckRequestDeadline(changeCtx); err != nil {
return err
}
ctx := changeCtx.NewMutateContext()
return command.Apply(ctx)
})
}
// CheckRequestDeadline returns a timeout error if the request that initiated a change has passed its deadline,
// so dispatchers can refuse to start a command its caller has already been told failed. changeCtx may be nil.
func CheckRequestDeadline(changeCtx *change.Context) error {
if err := changeCtx.RequestDeadlineErr(); err != nil {
timeoutErr := apierror.NewTimeoutError()
timeoutErr.Cause = err
return timeoutErr
}
return nil
}
// Decoder instances know how to decode encoded commands
type Decoder interface {
Decode(commandType int32, data []byte) (Command, error)
}
// DecoderF is a function version of the Decoder interface
type DecoderF func(commandType int32, data []byte) (Command, error)
func (self DecoderF) Decode(commandType int32, data []byte) (Command, error) {
return self(commandType, data)
}