package maintnotifications
import (
"context"
"errors"
"fmt"
"strings"
"time"
"github.com/redis/go-redis/v9/internal"
"github.com/redis/go-redis/v9/internal/maintnotifications/logs"
"github.com/redis/go-redis/v9/internal/pool"
"github.com/redis/go-redis/v9/push"
)
type NotificationHandler struct {
manager *Manager
operationsManager OperationsManagerInterface
}
func (snh *NotificationHandler ) HandlePushNotification (ctx context .Context , handlerCtx push .NotificationHandlerContext , notification []interface {}) error {
if len (notification ) == 0 {
internal .Logger .Printf (ctx , "%s" , logs .InvalidNotificationFormat (notification ))
return ErrInvalidNotification
}
notificationType , ok := notification [0 ].(string )
if !ok {
internal .Logger .Printf (ctx , "%s" , logs .InvalidNotificationTypeFormat (notification [0 ]))
return ErrInvalidNotification
}
modifiedNotification , shouldContinue := snh .manager .processPreHooks (ctx , handlerCtx , notificationType , notification )
if !shouldContinue {
return nil
}
var err error
switch notificationType {
case NotificationMoving :
err = snh .handleMoving (ctx , handlerCtx , modifiedNotification )
case NotificationMigrating :
err = snh .handleMigrating (ctx , handlerCtx , modifiedNotification )
case NotificationMigrated :
err = snh .handleMigrated (ctx , handlerCtx , modifiedNotification )
case NotificationFailingOver :
err = snh .handleFailingOver (ctx , handlerCtx , modifiedNotification )
case NotificationFailedOver :
err = snh .handleFailedOver (ctx , handlerCtx , modifiedNotification )
case NotificationSMigrating :
err = snh .handleSMigrating (ctx , handlerCtx , modifiedNotification )
case NotificationSMigrated :
err = snh .handleSMigrated (ctx , handlerCtx , modifiedNotification )
default :
err = nil
}
if maintenanceCallback := pool .GetMetricMaintenanceNotificationCallback (); maintenanceCallback != nil {
if conn , ok := handlerCtx .Conn .(*pool .Conn ); ok {
maintenanceCallback (ctx , conn , notificationType )
}
}
snh .manager .processPostHooks (ctx , handlerCtx , notificationType , modifiedNotification , err )
return err
}
func (snh *NotificationHandler ) handleMoving (ctx context .Context , handlerCtx push .NotificationHandlerContext , notification []interface {}) error {
if len (notification ) < 3 {
internal .Logger .Printf (ctx , "%s" , logs .InvalidNotification ("MOVING" , notification ))
return ErrInvalidNotification
}
seqID , ok := notification [1 ].(int64 )
if !ok {
internal .Logger .Printf (ctx , "%s" , logs .InvalidSeqIDInMovingNotification (notification [1 ]))
return ErrInvalidNotification
}
timeS , ok := notification [2 ].(int64 )
if !ok {
internal .Logger .Printf (ctx , "%s" , logs .InvalidTimeSInMovingNotification (notification [2 ]))
return ErrInvalidNotification
}
newEndpoint := ""
if len (notification ) > 3 {
newEndpoint , ok = notification [3 ].(string )
if !ok {
stringified := fmt .Sprintf ("%v" , notification [3 ])
if notification [3 ] == nil || stringified == internal .RedisNull {
newEndpoint = ""
} else {
internal .Logger .Printf (ctx , "%s" , logs .InvalidNewEndpointInMovingNotification (notification [3 ]))
return ErrInvalidNotification
}
}
}
conn := handlerCtx .Conn
if conn == nil {
internal .Logger .Printf (ctx , "%s" , logs .NoConnectionInHandlerContext ("MOVING" ))
return ErrInvalidNotification
}
var poolConn *pool .Conn
if pc , ok := conn .(*pool .Conn ); ok {
poolConn = pc
} else {
internal .Logger .Printf (ctx , "%s" , logs .InvalidConnectionTypeInHandlerContext ("MOVING" , conn , handlerCtx ))
return ErrInvalidNotification
}
if (poolConn .IsClosed () || !poolConn .IsPooled ()) && !poolConn .IsPubSub () {
return nil
}
deadline := time .Now ().Add (time .Duration (timeS ) * time .Second )
if newEndpoint == "" || newEndpoint == internal .RedisNull {
if internal .LogLevel .DebugOrAbove () {
internal .Logger .Printf (ctx , "%s" , logs .SchedulingHandoffToCurrentEndpoint (poolConn .GetID (), float64 (timeS )/2 ))
}
newEndpoint = snh .manager .options .GetAddr ()
time .AfterFunc (time .Duration (timeS /2 )*time .Second , func () {
if poolConn == nil || poolConn .IsClosed () {
return
}
if err := snh .markConnForHandoff (poolConn , newEndpoint , seqID , deadline ); err != nil {
internal .Logger .Printf (context .Background (), "%s" , logs .FailedToMarkForHandoff (poolConn .GetID (), err ))
return
}
if poolConn .GetStateMachine ().GetState () == pool .StateIdle {
owner := snh .manager .hookForConn (poolConn )
if owner != nil && owner .workerManager != nil {
if err := owner .workerManager .queueHandoff (poolConn ); err != nil {
internal .Logger .Printf (context .Background (), "%s" , logs .FailedToQueueHandoff (poolConn .GetID (), err ))
} else {
if err := poolConn .MarkQueuedForHandoff (); err != nil {
internal .Logger .Printf (context .Background (), "%s" , logs .FailedToMarkForHandoff (poolConn .GetID (), err ))
} else {
internal .Logger .Printf (context .Background (), "%s" , logs .MarkedForHandoff (poolConn .GetID ()))
}
}
}
}
})
return nil
}
return snh .markConnForHandoff (poolConn , newEndpoint , seqID , deadline )
}
func (snh *NotificationHandler ) markConnForHandoff (conn *pool .Conn , newEndpoint string , seqID int64 , deadline time .Time ) error {
if err := conn .MarkForHandoff (newEndpoint , seqID ); err != nil {
internal .Logger .Printf (context .Background (), "%s" , logs .FailedToMarkForHandoff (conn .GetID (), err ))
return nil
}
if snh .operationsManager != nil {
connID := conn .GetID ()
_ = snh .operationsManager .TrackMovingOperationWithConnID (context .Background (), newEndpoint , deadline , seqID , connID )
} else {
return errors .New (logs .ManagerNotInitialized ())
}
return nil
}
func (snh *NotificationHandler ) handleMigrating (ctx context .Context , handlerCtx push .NotificationHandlerContext , notification []interface {}) error {
if len (notification ) < 2 {
internal .Logger .Printf (ctx , "%s" , logs .InvalidNotification ("MIGRATING" , notification ))
return ErrInvalidNotification
}
if handlerCtx .Conn == nil {
internal .Logger .Printf (ctx , "%s" , logs .NoConnectionInHandlerContext ("MIGRATING" ))
return ErrInvalidNotification
}
conn , ok := handlerCtx .Conn .(*pool .Conn )
if !ok {
internal .Logger .Printf (ctx , "%s" , logs .InvalidConnectionTypeInHandlerContext ("MIGRATING" , handlerCtx .Conn , handlerCtx ))
return ErrInvalidNotification
}
if internal .LogLevel .InfoOrAbove () {
internal .Logger .Printf (ctx , "%s" , logs .RelaxedTimeoutDueToNotification (conn .GetID (), "MIGRATING" , snh .manager .config .RelaxedTimeout ))
}
conn .SetRelaxedTimeout (snh .manager .config .RelaxedTimeout , snh .manager .config .RelaxedTimeout )
if relaxedTimeoutCallback := pool .GetMetricConnectionRelaxedTimeoutCallback (); relaxedTimeoutCallback != nil {
relaxedTimeoutCallback (ctx , 1 , conn , PoolNameMain , "MIGRATING" )
}
return nil
}
func (snh *NotificationHandler ) handleMigrated (ctx context .Context , handlerCtx push .NotificationHandlerContext , notification []interface {}) error {
if len (notification ) < 2 {
internal .Logger .Printf (ctx , "%s" , logs .InvalidNotification ("MIGRATED" , notification ))
return ErrInvalidNotification
}
if handlerCtx .Conn == nil {
internal .Logger .Printf (ctx , "%s" , logs .NoConnectionInHandlerContext ("MIGRATED" ))
return ErrInvalidNotification
}
conn , ok := handlerCtx .Conn .(*pool .Conn )
if !ok {
internal .Logger .Printf (ctx , "%s" , logs .InvalidConnectionTypeInHandlerContext ("MIGRATED" , handlerCtx .Conn , handlerCtx ))
return ErrInvalidNotification
}
if internal .LogLevel .InfoOrAbove () {
connID := conn .GetID ()
internal .Logger .Printf (ctx , "%s" , logs .UnrelaxedTimeout (connID ))
}
conn .ClearRelaxedTimeout ()
return nil
}
func (snh *NotificationHandler ) handleFailingOver (ctx context .Context , handlerCtx push .NotificationHandlerContext , notification []interface {}) error {
if len (notification ) < 2 {
internal .Logger .Printf (ctx , "%s" , logs .InvalidNotification ("FAILING_OVER" , notification ))
return ErrInvalidNotification
}
if handlerCtx .Conn == nil {
internal .Logger .Printf (ctx , "%s" , logs .NoConnectionInHandlerContext ("FAILING_OVER" ))
return ErrInvalidNotification
}
conn , ok := handlerCtx .Conn .(*pool .Conn )
if !ok {
internal .Logger .Printf (ctx , "%s" , logs .InvalidConnectionTypeInHandlerContext ("FAILING_OVER" , handlerCtx .Conn , handlerCtx ))
return ErrInvalidNotification
}
if internal .LogLevel .InfoOrAbove () {
connID := conn .GetID ()
internal .Logger .Printf (ctx , "%s" , logs .RelaxedTimeoutDueToNotification (connID , "FAILING_OVER" , snh .manager .config .RelaxedTimeout ))
}
conn .SetRelaxedTimeout (snh .manager .config .RelaxedTimeout , snh .manager .config .RelaxedTimeout )
if relaxedTimeoutCallback := pool .GetMetricConnectionRelaxedTimeoutCallback (); relaxedTimeoutCallback != nil {
relaxedTimeoutCallback (ctx , 1 , conn , PoolNameMain , "FAILING_OVER" )
}
return nil
}
func (snh *NotificationHandler ) handleFailedOver (ctx context .Context , handlerCtx push .NotificationHandlerContext , notification []interface {}) error {
if len (notification ) < 2 {
internal .Logger .Printf (ctx , "%s" , logs .InvalidNotification ("FAILED_OVER" , notification ))
return ErrInvalidNotification
}
if handlerCtx .Conn == nil {
internal .Logger .Printf (ctx , "%s" , logs .NoConnectionInHandlerContext ("FAILED_OVER" ))
return ErrInvalidNotification
}
conn , ok := handlerCtx .Conn .(*pool .Conn )
if !ok {
internal .Logger .Printf (ctx , "%s" , logs .InvalidConnectionTypeInHandlerContext ("FAILED_OVER" , handlerCtx .Conn , handlerCtx ))
return ErrInvalidNotification
}
if internal .LogLevel .InfoOrAbove () {
connID := conn .GetID ()
internal .Logger .Printf (ctx , "%s" , logs .UnrelaxedTimeout (connID ))
}
conn .ClearRelaxedTimeout ()
return nil
}
func (snh *NotificationHandler ) handleSMigrating (ctx context .Context , handlerCtx push .NotificationHandlerContext , notification []interface {}) error {
if len (notification ) < 3 {
internal .Logger .Printf (ctx , "%s" , logs .InvalidNotification ("SMIGRATING" , notification ))
return ErrInvalidNotification
}
if _ , ok := notification [1 ].(int64 ); !ok {
internal .Logger .Printf (ctx , "%s" , logs .InvalidSeqIDInSMigratingNotification (notification [1 ]))
return ErrInvalidNotification
}
if handlerCtx .Conn == nil {
internal .Logger .Printf (ctx , "%s" , logs .NoConnectionInHandlerContext ("SMIGRATING" ))
return ErrInvalidNotification
}
conn , ok := handlerCtx .Conn .(*pool .Conn )
if !ok {
internal .Logger .Printf (ctx , "%s" , logs .InvalidConnectionTypeInHandlerContext ("SMIGRATING" , handlerCtx .Conn , handlerCtx ))
return ErrInvalidNotification
}
if internal .LogLevel .InfoOrAbove () {
internal .Logger .Printf (ctx , "%s" , logs .RelaxedTimeoutDueToNotification (conn .GetID (), "SMIGRATING" , snh .manager .config .RelaxedTimeout ))
}
conn .SetRelaxedTimeout (snh .manager .config .RelaxedTimeout , snh .manager .config .RelaxedTimeout )
return nil
}
func (snh *NotificationHandler ) handleSMigrated (ctx context .Context , handlerCtx push .NotificationHandlerContext , notification []interface {}) error {
if len (notification ) < 3 {
internal .Logger .Printf (ctx , "%s" , logs .InvalidNotification ("SMIGRATED" , notification ))
return ErrInvalidNotification
}
seqID , ok := notification [1 ].(int64 )
if !ok {
internal .Logger .Printf (ctx , "%s" , logs .InvalidSeqIDInSMigratedNotification (notification [1 ]))
return ErrInvalidNotification
}
triplets , ok := notification [2 ].([]interface {})
if !ok {
internal .Logger .Printf (ctx , "%s" , logs .InvalidNotification ("SMIGRATED (triplets array)" , notification [2 ]))
return ErrInvalidNotification
}
if len (triplets ) == 0 {
internal .Logger .Printf (ctx , "%s" , logs .InvalidNotification ("SMIGRATED (empty triplets)" , notification ))
return ErrInvalidNotification
}
var connectionNodeAddress string
var connectionAddr string
if snh .manager .options != nil {
connectionNodeAddress = snh .manager .options .GetNodeAddress ()
connectionAddr = snh .manager .options .GetAddr ()
}
sourceMatchesConnection := func (source string ) bool {
if source == connectionNodeAddress {
return true
}
if source == connectionAddr {
return true
}
return false
}
var matchingTriplets []struct {
source string
target string
slots string
}
var allSlotRanges []string
for _ , tripletInterface := range triplets {
triplet , ok := tripletInterface .([]interface {})
if !ok || len (triplet ) != 3 {
internal .Logger .Printf (ctx , "%s" , logs .InvalidNotification ("SMIGRATED (triplet format)" , tripletInterface ))
continue
}
source , ok := triplet [0 ].(string )
if !ok {
internal .Logger .Printf (ctx , "%s" , logs .InvalidNotification ("SMIGRATED (source)" , triplet [0 ]))
continue
}
target , ok := triplet [1 ].(string )
if !ok {
internal .Logger .Printf (ctx , "%s" , logs .InvalidNotification ("SMIGRATED (target)" , triplet [1 ]))
continue
}
slots , ok := triplet [2 ].(string )
if !ok {
internal .Logger .Printf (ctx , "%s" , logs .InvalidNotification ("SMIGRATED (slots)" , triplet [2 ]))
continue
}
if sourceMatchesConnection (source ) {
matchingTriplets = append (matchingTriplets , struct {
source string
target string
slots string
}{source , target , slots })
slotRanges := strings .Split (slots , "," )
allSlotRanges = append (allSlotRanges , slotRanges ...)
}
}
var connID uint64
if handlerCtx .Conn != nil {
conn , ok := handlerCtx .Conn .(*pool .Conn )
if ok {
if internal .LogLevel .InfoOrAbove () {
connID = conn .GetID ()
internal .Logger .Printf (ctx , "%s" , logs .UnrelaxedTimeout (connID ))
}
conn .ClearRelaxedTimeout ()
}
}
if len (matchingTriplets ) == 0 {
return nil
}
if snh .manager .MarkSMigratedSeqIDProcessed (seqID ) {
target := matchingTriplets [0 ].target
slotsForLog := allSlotRanges
if internal .LogLevel .InfoOrAbove () {
internal .Logger .Printf (ctx , "%s" , logs .TriggeringClusterStateReload (seqID , target , slotsForLog ))
}
snh .manager .TriggerClusterStateReload (ctx , target , slotsForLog )
}
return nil
}
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 .