package maintnotifications
import (
"context"
"errors"
"fmt"
"net"
"sync"
"sync/atomic"
"time"
"github.com/redis/go-redis/v9/internal"
"github.com/redis/go-redis/v9/internal/interfaces"
"github.com/redis/go-redis/v9/internal/maintnotifications/logs"
"github.com/redis/go-redis/v9/internal/pool"
"github.com/redis/go-redis/v9/push"
)
const (
NotificationMoving = "MOVING"
NotificationMigrating = "MIGRATING"
NotificationMigrated = "MIGRATED"
NotificationFailingOver = "FAILING_OVER"
NotificationFailedOver = "FAILED_OVER"
NotificationSMigrating = "SMIGRATING"
NotificationSMigrated = "SMIGRATED"
)
var maintenanceNotificationTypes = []string {
NotificationMoving ,
NotificationMigrating ,
NotificationMigrated ,
NotificationFailingOver ,
NotificationFailedOver ,
NotificationSMigrating ,
NotificationSMigrated ,
}
type NotificationHook interface {
PreHook (ctx context .Context , notificationCtx push .NotificationHandlerContext , notificationType string , notification []interface {}) ([]interface {}, bool )
PostHook (ctx context .Context , notificationCtx push .NotificationHandlerContext , notificationType string , notification []interface {}, result error )
}
type MovingOperationKey struct {
SeqID int64
ConnID uint64
}
func (k MovingOperationKey ) String () string {
return fmt .Sprintf ("seq:%d-conn:%d" , k .SeqID , k .ConnID )
}
type Manager struct {
client interfaces .ClientInterface
config *Config
options interfaces .OptionsInterface
pool pool .Pooler
activeMovingOps sync .Map
processedSMigratedSeqIDs sync .Map
activeOperationCount atomic .Int64
closed atomic .Bool
shutdownTimeout time .Duration
hooks []NotificationHook
hooksMu sync .RWMutex
poolHooksRef *PoolHook
additionalPoolHooks []additionalPoolHook
maintNotificationsConns sync .Map
clusterStateReloadCallback atomic .Pointer [ClusterStateReloadCallback ]
}
type MovingOperation struct {
SeqID int64
NewEndpoint string
StartTime time .Time
Deadline time .Time
}
type ClusterStateReloadCallback func (ctx context .Context , hostPort string , slotRanges []string )
func NewManager (client interfaces .ClientInterface , pool pool .Pooler , config *Config ) (*Manager , error ) {
if client == nil {
return nil , ErrInvalidClient
}
hm := &Manager {
client : client ,
pool : pool ,
options : client .GetOptions (),
config : config .Clone (),
hooks : make ([]NotificationHook , 0 ),
shutdownTimeout : 10 * time .Second ,
}
if err := hm .setupPushNotifications (); err != nil {
return nil , err
}
return hm , nil
}
func (hm *Manager ) InitPoolHook (baseDialer func (context .Context , string , string ) (net .Conn , error )) {
poolHook := hm .createPoolHook (baseDialer )
hm .pool .AddPoolHook (poolHook )
}
type additionalPoolHook struct {
pool pool .Pooler
hook *PoolHook
}
func (hm *Manager ) InitPoolHookForPool (p pool .Pooler , baseDialer func (context .Context , string , string ) (net .Conn , error )) {
if p == nil {
return
}
poolSize := 0
network := ""
if hm .options != nil {
poolSize = hm .options .GetPoolSize ()
network = hm .options .GetNetwork ()
}
hook := NewPoolHookWithPoolSize (baseDialer , network , hm .config , hm , poolSize )
hook .SetPool (p )
hm .hooksMu .Lock ()
defer hm .hooksMu .Unlock ()
if hm .closed .Load () {
return
}
hm .additionalPoolHooks = append (hm .additionalPoolHooks , additionalPoolHook {pool : p , hook : hook })
p .AddPoolHook (hook )
}
func (hm *Manager ) hookForConn (cn *pool .Conn ) *PoolHook {
if cn == nil {
return hm .poolHooksRef
}
name := cn .PoolName ()
if name == "" {
return hm .poolHooksRef
}
hm .hooksMu .RLock ()
defer hm .hooksMu .RUnlock ()
for _ , ah := range hm .additionalPoolHooks {
if np , ok := ah .pool .(interface { Name () string }); ok && np .Name () == name {
return ah .hook
}
}
return hm .poolHooksRef
}
func (hm *Manager ) setupPushNotifications () error {
processor := hm .client .GetPushProcessor ()
if processor == nil {
return ErrInvalidClient
}
handler := &NotificationHandler {manager : hm , operationsManager : hm }
for _ , notificationType := range maintenanceNotificationTypes {
if err := processor .RegisterHandler (notificationType , handler , true ); err != nil {
return errors .New (logs .FailedToRegisterHandler (notificationType , err ))
}
}
return nil
}
func (hm *Manager ) TrackMovingOperationWithConnID (ctx context .Context , newEndpoint string , deadline time .Time , seqID int64 , connID uint64 ) error {
key := MovingOperationKey {
SeqID : seqID ,
ConnID : connID ,
}
movingOp := &MovingOperation {
SeqID : seqID ,
NewEndpoint : newEndpoint ,
StartTime : time .Now (),
Deadline : deadline ,
}
if _ , loaded := hm .activeMovingOps .LoadOrStore (key , movingOp ); loaded {
if internal .LogLevel .DebugOrAbove () {
internal .Logger .Printf (context .Background (), "%s" , logs .DuplicateMovingOperation (connID , newEndpoint , seqID ))
}
return nil
}
if internal .LogLevel .DebugOrAbove () {
internal .Logger .Printf (context .Background (), "%s" , logs .TrackingMovingOperation (connID , newEndpoint , seqID ))
}
hm .activeOperationCount .Add (1 )
return nil
}
func (hm *Manager ) UntrackOperationWithConnID (seqID int64 , connID uint64 ) {
key := MovingOperationKey {
SeqID : seqID ,
ConnID : connID ,
}
if _ , loaded := hm .activeMovingOps .LoadAndDelete (key ); loaded {
if internal .LogLevel .DebugOrAbove () {
internal .Logger .Printf (context .Background (), "%s" , logs .UntrackingMovingOperation (connID , seqID ))
}
hm .activeOperationCount .Add (-1 )
} else {
if internal .LogLevel .DebugOrAbove () {
internal .Logger .Printf (context .Background (), "%s" , logs .OperationNotTracked (connID , seqID ))
}
}
}
func (hm *Manager ) GetActiveMovingOperations () map [MovingOperationKey ]*MovingOperation {
result := make (map [MovingOperationKey ]*MovingOperation )
hm .activeMovingOps .Range (func (key , value interface {}) bool {
k := key .(MovingOperationKey )
op := value .(*MovingOperation )
result [k ] = &MovingOperation {
SeqID : op .SeqID ,
NewEndpoint : op .NewEndpoint ,
StartTime : op .StartTime ,
Deadline : op .Deadline ,
}
return true
})
return result
}
func (hm *Manager ) IsHandoffInProgress () bool {
return hm .activeOperationCount .Load () > 0
}
func (hm *Manager ) GetActiveOperationCount () int64 {
return hm .activeOperationCount .Load ()
}
func (hm *Manager ) MarkSMigratedSeqIDProcessed (seqID int64 ) bool {
_ , alreadyProcessed := hm .processedSMigratedSeqIDs .LoadOrStore (seqID , true )
return !alreadyProcessed
}
func (hm *Manager ) TrackMaintNotificationsConn (cn *pool .Conn ) {
if cn == nil {
return
}
hm .maintNotificationsConns .Store (cn .GetID (), cn )
}
func (hm *Manager ) UntrackMaintNotificationsConn (connID uint64 ) {
hm .maintNotificationsConns .Delete (connID )
}
func (hm *Manager ) maintNotificationsConnSnapshot () []*pool .Conn {
var conns []*pool .Conn
hm .maintNotificationsConns .Range (func (_ , value interface {}) bool {
if cn , ok := value .(*pool .Conn ); ok {
conns = append (conns , cn )
}
return true
})
return conns
}
func (hm *Manager ) retireMaintNotificationsConns (ctx context .Context ) {
conns := hm .maintNotificationsConnSnapshot ()
if len (conns ) == 0 {
return
}
pools := make ([]pool .Pooler , 0 , 1 +len (hm .additionalPoolHooks ))
if hm .pool != nil {
pools = append (pools , hm .pool )
}
hm .hooksMu .RLock ()
for _ , ah := range hm .additionalPoolHooks {
if ah .pool != nil {
pools = append (pools , ah .pool )
}
}
hm .hooksMu .RUnlock ()
for _ , pl := range pools {
if retirer , ok := pl .(pool .ConnRetirer ); ok {
retirer .RetireConns (ctx , conns , pool .CloseReasonMaintNotificationsDisabled )
continue
}
for _ , cn := range conns {
_ = pl .CloseConn (ctx , cn , pool .CloseReasonMaintNotificationsDisabled , pool .MetricStateIdle )
}
}
}
func (hm *Manager ) Close () error {
if !hm .closed .CompareAndSwap (false , true ) {
return nil
}
hm .retireMaintNotificationsConns (context .Background ())
if hm .poolHooksRef != nil {
shutdownCtx , cancel := context .WithTimeout (context .Background (), hm .shutdownTimeout )
defer cancel ()
err := hm .poolHooksRef .Shutdown (shutdownCtx )
if err != nil {
hm .closed .Store (false )
return err
}
if hm .pool != nil {
hm .pool .RemovePoolHook (hm .poolHooksRef )
}
}
hm .hooksMu .Lock ()
additional := hm .additionalPoolHooks
hm .additionalPoolHooks = nil
hm .hooksMu .Unlock ()
for i , ah := range additional {
shutdownCtx , cancel := context .WithTimeout (context .Background (), hm .shutdownTimeout )
err := ah .hook .Shutdown (shutdownCtx )
cancel ()
if err != nil {
hm .hooksMu .Lock ()
remaining := make ([]additionalPoolHook , 0 , len (additional )-i +len (hm .additionalPoolHooks ))
remaining = append (remaining , additional [i :]...)
remaining = append (remaining , hm .additionalPoolHooks ...)
hm .additionalPoolHooks = remaining
hm .hooksMu .Unlock ()
hm .closed .Store (false )
return err
}
if ah .pool != nil {
ah .pool .RemovePoolHook (ah .hook )
}
}
hm .activeMovingOps .Range (func (key , value interface {}) bool {
hm .activeMovingOps .Delete (key )
return true
})
hm .activeOperationCount .Store (0 )
return nil
}
func (hm *Manager ) GetState () State {
if hm .activeOperationCount .Load () > 0 {
return StateMoving
}
return StateIdle
}
func (hm *Manager ) processPreHooks (ctx context .Context , notificationCtx push .NotificationHandlerContext , notificationType string , notification []interface {}) ([]interface {}, bool ) {
hm .hooksMu .RLock ()
defer hm .hooksMu .RUnlock ()
currentNotification := notification
for _ , hook := range hm .hooks {
modifiedNotification , shouldContinue := hook .PreHook (ctx , notificationCtx , notificationType , currentNotification )
if !shouldContinue {
return modifiedNotification , false
}
currentNotification = modifiedNotification
}
return currentNotification , true
}
func (hm *Manager ) processPostHooks (ctx context .Context , notificationCtx push .NotificationHandlerContext , notificationType string , notification []interface {}, result error ) {
hm .hooksMu .RLock ()
defer hm .hooksMu .RUnlock ()
for _ , hook := range hm .hooks {
hook .PostHook (ctx , notificationCtx , notificationType , notification , result )
}
}
func (hm *Manager ) createPoolHook (baseDialer func (context .Context , string , string ) (net .Conn , error )) *PoolHook {
if hm .poolHooksRef != nil {
return hm .poolHooksRef
}
poolSize := 0
if hm .options != nil {
poolSize = hm .options .GetPoolSize ()
}
hm .poolHooksRef = NewPoolHookWithPoolSize (baseDialer , hm .options .GetNetwork (), hm .config , hm , poolSize )
hm .poolHooksRef .SetPool (hm .pool )
return hm .poolHooksRef
}
func (hm *Manager ) AddNotificationHook (notificationHook NotificationHook ) {
hm .hooksMu .Lock ()
defer hm .hooksMu .Unlock ()
hm .hooks = append (hm .hooks , notificationHook )
}
func (hm *Manager ) SetClusterStateReloadCallback (callback ClusterStateReloadCallback ) {
hm .clusterStateReloadCallback .Store (&callback )
}
func (hm *Manager ) TriggerClusterStateReload (ctx context .Context , hostPort string , slotRanges []string ) {
if cb := hm .clusterStateReloadCallback .Load (); cb != nil {
(*cb )(ctx , hostPort , slotRanges )
}
}
The pages are generated with Golds v0.8.7 . (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu .
PR and bug reports are welcome and can be submitted to the issue list .
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds .