package maintnotifications
import (
"context"
"errors"
"net"
"sync"
"sync/atomic"
"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"
)
const PoolNameMain = "main"
type handoffWorkerManager struct {
handoffQueue chan HandoffRequest
shutdown chan struct {}
shutdownOnce sync .Once
workerWg sync .WaitGroup
maxWorkers int
activeWorkers atomic .Int32
workerTimeout time .Duration
workersScaling atomic .Bool
pending sync .Map
config *Config
poolHook *PoolHook
circuitBreakerManager *CircuitBreakerManager
}
func newHandoffWorkerManager(config *Config , poolHook *PoolHook ) *handoffWorkerManager {
return &handoffWorkerManager {
handoffQueue : make (chan HandoffRequest , config .HandoffQueueSize ),
shutdown : make (chan struct {}),
maxWorkers : config .MaxWorkers ,
activeWorkers : atomic .Int32 {},
workerTimeout : 15 * time .Second ,
config : config ,
poolHook : poolHook ,
circuitBreakerManager : newCircuitBreakerManager (config ),
}
}
func (hwm *handoffWorkerManager ) getCurrentWorkers () int {
return int (hwm .activeWorkers .Load ())
}
func (hwm *handoffWorkerManager ) getPendingMap () *sync .Map {
return &hwm .pending
}
func (hwm *handoffWorkerManager ) getMaxWorkers () int {
return hwm .maxWorkers
}
func (hwm *handoffWorkerManager ) getHandoffQueue () chan HandoffRequest {
return hwm .handoffQueue
}
func (hwm *handoffWorkerManager ) getCircuitBreakerStats () []CircuitBreakerStats {
return hwm .circuitBreakerManager .GetAllStats ()
}
func (hwm *handoffWorkerManager ) resetCircuitBreakers () {
hwm .circuitBreakerManager .Reset ()
}
func (hwm *handoffWorkerManager ) isHandoffPending (conn *pool .Conn ) bool {
_ , pending := hwm .pending .Load (conn .GetID ())
return pending
}
func (hwm *handoffWorkerManager ) ensureWorkerAvailable () {
select {
case <- hwm .shutdown :
return
default :
if hwm .workersScaling .CompareAndSwap (false , true ) {
defer hwm .workersScaling .Store (false )
currentWorkers := hwm .activeWorkers .Load ()
workersWas := currentWorkers
for currentWorkers < int32 (hwm .maxWorkers ) {
hwm .workerWg .Add (1 )
go hwm .onDemandWorker ()
currentWorkers ++
}
hwm .activeWorkers .Add (currentWorkers - workersWas )
}
}
}
func (hwm *handoffWorkerManager ) onDemandWorker () {
defer func () {
if r := recover (); r != nil {
internal .Logger .Printf (context .Background (), "%s" , logs .WorkerPanicRecovered (r ))
}
hwm .activeWorkers .Add (-1 )
hwm .workerWg .Done ()
}()
timer := time .NewTimer (hwm .workerTimeout )
defer timer .Stop ()
for {
if !timer .Stop () {
select {
case <- timer .C :
default :
}
}
timer .Reset (hwm .workerTimeout )
select {
case <- hwm .shutdown :
if internal .LogLevel .InfoOrAbove () {
internal .Logger .Printf (context .Background (), "%s" , logs .WorkerExitingDueToShutdown ())
}
return
case <- timer .C :
if internal .LogLevel .InfoOrAbove () {
internal .Logger .Printf (context .Background (), "%s" , logs .WorkerExitingDueToInactivityTimeout (hwm .workerTimeout ))
}
return
case request := <- hwm .handoffQueue :
select {
case <- hwm .shutdown :
if internal .LogLevel .InfoOrAbove () {
internal .Logger .Printf (context .Background (), "%s" , logs .WorkerExitingDueToShutdownWhileProcessing ())
}
hwm .pending .Delete (request .ConnID )
return
default :
hwm .processHandoffRequest (request )
}
}
}
}
func (hwm *handoffWorkerManager ) processHandoffRequest (request HandoffRequest ) {
if internal .LogLevel .InfoOrAbove () {
internal .Logger .Printf (context .Background (), "%s" , logs .HandoffStarted (request .Conn .GetID (), request .Endpoint ))
}
handoffTimeout := 15 * time .Second
if hwm .config != nil && hwm .config .HandoffTimeout > 0 {
handoffTimeout = hwm .config .HandoffTimeout
}
ctx , cancel := context .WithTimeout (context .Background (), handoffTimeout )
defer cancel ()
shutdownCtx , shutdownCancel := context .WithCancel (ctx )
defer shutdownCancel ()
go func () {
select {
case <- hwm .shutdown :
shutdownCancel ()
case <- shutdownCtx .Done ():
}
}()
shouldRetry , err := hwm .performConnectionHandoff (shutdownCtx , request .Conn )
minRetryBackoff := 500 * time .Millisecond
if err != nil {
if shouldRetry {
now := time .Now ()
deadline , ok := shutdownCtx .Deadline ()
thirdOfTimeout := handoffTimeout / 3
if !ok || deadline .Before (now ) {
deadline = now .Add (thirdOfTimeout )
}
afterTime := deadline .Sub (now )
if afterTime < minRetryBackoff {
afterTime = minRetryBackoff
}
if internal .LogLevel .InfoOrAbove () {
currentRetries := request .Conn .HandoffRetries ()
maxRetries := 3
if hwm .config != nil {
maxRetries = hwm .config .MaxHandoffRetries
}
internal .Logger .Printf (context .Background (), "%s" , logs .HandoffFailed (request .ConnID , request .Endpoint , currentRetries , maxRetries , err ))
}
time .AfterFunc (afterTime , func () {
if err := hwm .queueHandoff (request .Conn ); err != nil {
if internal .LogLevel .WarnOrAbove () {
internal .Logger .Printf (context .Background (), "%s" , logs .CannotQueueHandoffForRetry (err ))
}
hwm .pending .Delete (request .Conn .GetID ())
hwm .closeConnFromRequest (context .Background (), request , err )
} else {
hwm .pending .Delete (request .Conn .GetID ())
}
})
return
} else {
hwm .pending .Delete (request .Conn .GetID ())
go hwm .closeConnFromRequest (ctx , request , err )
}
seqID := request .Conn .GetMovingSeqID ()
connID := request .Conn .GetID ()
if hwm .poolHook .operationsManager != nil {
hwm .poolHook .operationsManager .UntrackOperationWithConnID (seqID , connID )
}
} else {
hwm .pending .Delete (request .Conn .GetID ())
}
}
func (hwm *handoffWorkerManager ) queueHandoff (conn *pool .Conn ) error {
shouldHandoff , endpoint , seqID := conn .GetHandoffInfo ()
if !shouldHandoff && conn .HandoffRetries () == 0 {
if internal .LogLevel .InfoOrAbove () {
internal .Logger .Printf (context .Background (), "%s" , logs .ConnectionNotMarkedForHandoff (conn .GetID ()))
}
return errors .New (logs .ConnectionNotMarkedForHandoffError (conn .GetID ()))
}
request := HandoffRequest {
Conn : conn ,
ConnID : conn .GetID (),
Endpoint : endpoint ,
SeqID : seqID ,
Pool : hwm .poolHook .pool ,
}
select {
case <- hwm .shutdown :
return ErrShutdown
default :
select {
case <- hwm .shutdown :
return ErrShutdown
case hwm .handoffQueue <- request :
hwm .pending .Store (request .ConnID , request .SeqID )
hwm .ensureWorkerAvailable ()
return nil
default :
select {
case <- hwm .shutdown :
return ErrShutdown
case hwm .handoffQueue <- request :
hwm .pending .Store (request .ConnID , request .SeqID )
hwm .ensureWorkerAvailable ()
return nil
case <- time .After (100 * time .Millisecond ):
queueLen := len (hwm .handoffQueue )
queueCap := cap (hwm .handoffQueue )
if internal .LogLevel .WarnOrAbove () {
internal .Logger .Printf (context .Background (), "%s" , logs .HandoffQueueFull (queueLen , queueCap ))
}
}
}
}
hwm .ensureWorkerAvailable ()
return ErrHandoffQueueFull
}
func (hwm *handoffWorkerManager ) shutdownWorkers (ctx context .Context ) error {
hwm .shutdownOnce .Do (func () {
close (hwm .shutdown )
if hwm .circuitBreakerManager != nil {
hwm .circuitBreakerManager .Shutdown ()
}
})
done := make (chan struct {})
go func () {
hwm .workerWg .Wait ()
close (done )
}()
select {
case <- done :
return nil
case <- ctx .Done ():
return ctx .Err ()
}
}
func (hwm *handoffWorkerManager ) performConnectionHandoff (ctx context .Context , conn *pool .Conn ) (shouldRetry bool , err error ) {
connID := conn .GetID ()
newEndpoint := conn .GetHandoffEndpoint ()
if newEndpoint == "" {
return false , ErrConnectionInvalidHandoffState
}
circuitBreaker := hwm .circuitBreakerManager .GetCircuitBreaker (newEndpoint )
if circuitBreaker .IsOpen () {
internal .Logger .Printf (ctx , "%s" , logs .CircuitBreakerOpen (connID , newEndpoint ))
return false , ErrCircuitBreakerOpen
}
shouldRetry , err = hwm .performHandoffInternal (ctx , conn , newEndpoint , connID )
if err != nil {
if shouldRetry {
circuitBreaker .recordFailure ()
}
return shouldRetry , err
}
circuitBreaker .recordSuccess ()
return false , nil
}
func (hwm *handoffWorkerManager ) performHandoffInternal (
ctx context .Context ,
conn *pool .Conn ,
newEndpoint string ,
connID uint64 ,
) (shouldRetry bool , err error ) {
retries := conn .IncrementAndGetHandoffRetries (1 )
internal .Logger .Printf (ctx , "%s" , logs .HandoffRetryAttempt (connID , retries , newEndpoint , conn .RemoteAddr ().String ()))
maxRetries := 3
if hwm .config != nil {
maxRetries = hwm .config .MaxHandoffRetries
}
if retries > maxRetries {
if internal .LogLevel .WarnOrAbove () {
internal .Logger .Printf (ctx , "%s" , logs .ReachedMaxHandoffRetries (connID , newEndpoint , maxRetries ))
}
return false , ErrMaxHandoffRetriesReached
}
endpointDialer := hwm .createEndpointDialer (newEndpoint )
newNetConn , err := endpointDialer (ctx )
if err != nil {
internal .Logger .Printf (ctx , "%s" , logs .FailedToDialNewEndpoint (connID , newEndpoint , err ))
return true , err
}
oldConn := conn .GetNetConn ()
if hwm .config != nil && hwm .config .PostHandoffRelaxedDuration > 0 {
relaxedTimeout := hwm .config .RelaxedTimeout
deadline := time .Now ().Add (hwm .config .PostHandoffRelaxedDuration )
conn .SetRelaxedTimeoutWithDeadline (relaxedTimeout , relaxedTimeout , deadline )
if relaxedTimeoutCallback := pool .GetMetricConnectionRelaxedTimeoutCallback (); relaxedTimeoutCallback != nil {
relaxedTimeoutCallback (ctx , 1 , conn , PoolNameMain , "HANDOFF" )
}
if internal .LogLevel .InfoOrAbove () {
internal .Logger .Printf (context .Background (), "%s" , logs .ApplyingRelaxedTimeoutDueToPostHandoff (connID , relaxedTimeout , deadline .Format ("15:04:05.000" )))
}
}
err = conn .SetNetConnAndInitConn (ctx , newNetConn )
if err != nil {
return false , err
}
defer func () {
if oldConn != nil {
oldConn .Close ()
}
}()
conn .ClearHandoffState ()
internal .Logger .Printf (ctx , "%s" , logs .HandoffSucceeded (connID , newEndpoint ))
if handoffCallback := pool .GetMetricConnectionHandoffCallback (); handoffCallback != nil {
handoffCallback (ctx , conn , PoolNameMain )
}
return false , nil
}
func (hwm *handoffWorkerManager ) createEndpointDialer (endpoint string ) func (context .Context ) (net .Conn , error ) {
return func (ctx context .Context ) (net .Conn , error ) {
host , port , err := net .SplitHostPort (endpoint )
if err != nil {
host = endpoint
if port == "" {
port = "6379"
}
}
return hwm .poolHook .baseDialer (ctx , hwm .poolHook .network , net .JoinHostPort (host , port ))
}
}
func (hwm *handoffWorkerManager ) closeConnFromRequest (ctx context .Context , request HandoffRequest , err error ) {
pooler := request .Pool
conn := request .Conn
conn .ClearHandoffState ()
if pooler != nil {
pooler .RemoveWithoutTurn (ctx , conn , err )
if internal .LogLevel .WarnOrAbove () {
internal .Logger .Printf (ctx , "%s" , logs .RemovingConnectionFromPool (conn .GetID (), err ))
}
} else {
errClose := conn .Close ()
if errClose != nil {
internal .Logger .Printf (ctx , "redis: failed to close connection: %v" , errClose )
}
if internal .LogLevel .WarnOrAbove () {
internal .Logger .Printf (ctx , "%s" , logs .NoPoolProvidedCannotRemove (conn .GetID (), err ))
}
}
}
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 .