-
Notifications
You must be signed in to change notification settings - Fork 726
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
client: introduce circuit breaker for region calls #8856
Merged
Merged
Changes from 5 commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
98312a9
introduce circuit breaker for region calls
911cb56
add default circuit breaker
b7678b7
fix merge issue interface.go:67:50: undefined: pd
b993f6b
Merge branch 'master' into circuit-breaker
Tema a95b198
address PR comments
6c49334
minor tests and metrics refactoring
daffcf6
addressed more comments
01a3679
Merge branch 'master' into circuit-breaker
Tema 2ebfc1e
fix merge confilicts issues
45c805e
improve testing
4c0cc9e
Merge branch 'master' into circuit-breaker
ti-chi-bot[bot] File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,280 @@ | ||
// Copyright 2024 TiKV Project Authors. | ||
// | ||
// 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 | ||
// | ||
// http://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 circuitbreaker | ||
|
||
import ( | ||
"fmt" | ||
"strings" | ||
"sync" | ||
"time" | ||
|
||
"github.com/tikv/pd/client/errs" | ||
|
||
"github.com/prometheus/client_golang/prometheus" | ||
m "github.com/tikv/pd/client/metrics" | ||
"go.uber.org/zap" | ||
|
||
"github.com/pingcap/log" | ||
) | ||
|
||
// Overloading is a type describing service return value | ||
type Overloading bool | ||
|
||
const ( | ||
// No means the service is not overloaded | ||
No = false | ||
// Yes means the service is overloaded | ||
Yes = true | ||
) | ||
|
||
// Settings describes configuration for Circuit Breaker | ||
type Settings struct { | ||
// Defines the error rate threshold to trip the circuit breaker. | ||
ErrorRateThresholdPct uint32 | ||
// Defines the average qps over the `error_rate_window` that must be met before evaluating the error rate threshold. | ||
MinQPSForOpen uint32 | ||
// Defines how long to track errors before evaluating error_rate_threshold. | ||
ErrorRateWindow time.Duration | ||
// Defines how long to wait after circuit breaker is open before go to half-open state to send a probe request. | ||
CoolDownInterval time.Duration | ||
// Defines how many subsequent requests to test after cooldown period before fully close the circuit. | ||
HalfOpenSuccessCount uint32 | ||
} | ||
|
||
// AlwaysOpenSettings is a configuration that never trips the circuit breaker. | ||
var AlwaysOpenSettings = Settings{ | ||
ErrorRateThresholdPct: 0, // never trips | ||
ErrorRateWindow: 10 * time.Second, // effectively results in testing for new settings every 10 seconds | ||
MinQPSForOpen: 10, | ||
CoolDownInterval: 10 * time.Second, | ||
HalfOpenSuccessCount: 1, | ||
} | ||
|
||
// CircuitBreaker is a state machine to prevent sending requests that are likely to fail. | ||
type CircuitBreaker[T any] struct { | ||
config *Settings | ||
name string | ||
|
||
mutex sync.Mutex | ||
state *State[T] | ||
|
||
successCounter prometheus.Counter | ||
failureCounter prometheus.Counter | ||
fastFailCounter prometheus.Counter | ||
} | ||
|
||
// StateType is a type that represents a state of CircuitBreaker. | ||
type StateType int | ||
|
||
// States of CircuitBreaker. | ||
const ( | ||
StateClosed StateType = iota | ||
StateOpen | ||
StateHalfOpen | ||
) | ||
|
||
// String implements stringer interface. | ||
func (s StateType) String() string { | ||
switch s { | ||
case StateClosed: | ||
return "closed" | ||
case StateOpen: | ||
return "open" | ||
case StateHalfOpen: | ||
return "half-open" | ||
default: | ||
return fmt.Sprintf("unknown state: %d", s) | ||
} | ||
} | ||
|
||
var replacer = strings.NewReplacer(" ", "_", "-", "_") | ||
|
||
// NewCircuitBreaker returns a new CircuitBreaker configured with the given Settings. | ||
func NewCircuitBreaker[T any](name string, st Settings) *CircuitBreaker[T] { | ||
cb := new(CircuitBreaker[T]) | ||
cb.name = name | ||
cb.config = &st | ||
cb.state = cb.newState(time.Now(), StateClosed) | ||
|
||
metricName := replacer.Replace(name) | ||
cb.successCounter = m.CircuitBreakerCounters.WithLabelValues(metricName, "success") | ||
cb.failureCounter = m.CircuitBreakerCounters.WithLabelValues(metricName, "failure") | ||
cb.fastFailCounter = m.CircuitBreakerCounters.WithLabelValues(metricName, "fast_fail") | ||
return cb | ||
} | ||
|
||
// ChangeSettings changes the CircuitBreaker settings. | ||
// The changes will be reflected only in the next evaluation window. | ||
func (cb *CircuitBreaker[T]) ChangeSettings(apply func(config *Settings)) { | ||
cb.mutex.Lock() | ||
defer cb.mutex.Unlock() | ||
|
||
apply(cb.config) | ||
} | ||
|
||
// Execute calls the given function if the CircuitBreaker is closed and returns the result of execution. | ||
// Execute returns an error instantly if the CircuitBreaker is open. | ||
// https://github.com/tikv/rfcs/blob/master/text/0115-circuit-breaker.md | ||
func (cb *CircuitBreaker[T]) Execute(call func() (T, Overloading, error)) (T, error) { | ||
state, err := cb.onRequest() | ||
if err != nil { | ||
var defaultValue T | ||
return defaultValue, err | ||
} | ||
|
||
defer func() { | ||
e := recover() | ||
if e != nil { | ||
cb.onResult(state, Yes) | ||
panic(e) | ||
} | ||
}() | ||
|
||
result, overloaded, err := call() | ||
cb.onResult(state, overloaded) | ||
return result, err | ||
} | ||
|
||
func (cb *CircuitBreaker[T]) onRequest() (*State[T], error) { | ||
cb.mutex.Lock() | ||
defer cb.mutex.Unlock() | ||
|
||
state, err := cb.state.onRequest(cb) | ||
cb.state = state | ||
return state, err | ||
} | ||
|
||
func (cb *CircuitBreaker[T]) onResult(state *State[T], open Overloading) { | ||
cb.mutex.Lock() | ||
defer cb.mutex.Unlock() | ||
|
||
if cb.state == state { | ||
Tema marked this conversation as resolved.
Show resolved
Hide resolved
|
||
state.onResult(open) | ||
} // else the state moved forward so we don't need to update the counts | ||
} | ||
|
||
// State represents the state of CircuitBreaker. | ||
type State[T any] struct { | ||
stateType StateType | ||
cb *CircuitBreaker[T] | ||
end time.Time | ||
|
||
pendingCount uint32 | ||
successCount uint32 | ||
failureCount uint32 | ||
} | ||
|
||
// newState creates a new State with the given configuration and reset all success/failure counters. | ||
func (cb *CircuitBreaker[T]) newState(now time.Time, stateType StateType) *State[T] { | ||
var end time.Time | ||
var pendingCount uint32 | ||
switch stateType { | ||
case StateClosed: | ||
end = now.Add(cb.config.ErrorRateWindow) | ||
case StateOpen: | ||
end = now.Add(cb.config.CoolDownInterval) | ||
case StateHalfOpen: | ||
// we transition to HalfOpen state on the first request after the cooldown period, | ||
// so we start with 1 pending request | ||
pendingCount = 1 | ||
default: | ||
panic("unknown state") | ||
} | ||
return &State[T]{ | ||
cb: cb, | ||
stateType: stateType, | ||
pendingCount: pendingCount, | ||
end: end, | ||
} | ||
} | ||
|
||
// onRequest transitions the state to the next state based on the current state and the previous requests results | ||
// All state transitions happens at the request evaluation time only | ||
// The implementation represents a state machine effectively | ||
func (s *State[T]) onRequest(cb *CircuitBreaker[T]) (*State[T], error) { | ||
var now = time.Now() | ||
switch s.stateType { | ||
case StateClosed: | ||
if s.end.Before(now) { | ||
Tema marked this conversation as resolved.
Show resolved
Hide resolved
|
||
// ErrorRateWindow is over, let's evaluate the error rate | ||
total := s.failureCount + s.successCount | ||
observedErrorRatePct := s.failureCount * 100 / total | ||
Tema marked this conversation as resolved.
Show resolved
Hide resolved
|
||
if s.cb.config.ErrorRateThresholdPct > 0 && total >= uint32(s.cb.config.ErrorRateWindow.Seconds())*s.cb.config.MinQPSForOpen && observedErrorRatePct >= s.cb.config.ErrorRateThresholdPct { | ||
Tema marked this conversation as resolved.
Show resolved
Hide resolved
|
||
// the error threshold is breached, let's move to open state and start failing all requests | ||
log.Error("Circuit breaker tripped. Starting to fail all requests", | ||
zap.String("name", cb.name), | ||
zap.Uint32("observedErrorRatePct", observedErrorRatePct), | ||
zap.String("config", fmt.Sprintf("%+v", cb.config))) | ||
cb.fastFailCounter.Inc() | ||
return cb.newState(now, StateOpen), errs.ErrCircuitBreakerOpen | ||
} | ||
// the error threshold is not breached or there were not enough requests to evaluate it, | ||
// continue in the closed state and allow all requests | ||
return cb.newState(now, StateClosed), nil | ||
Tema marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
// continue in closed state till ErrorRateWindow is over | ||
return s, nil | ||
case StateOpen: | ||
if s.end.Before(now) { | ||
// CoolDownInterval is over, it is time to transition to half-open state | ||
log.Info("Circuit breaker cooldown period is over. Transitioning to half-open state to test the service", | ||
zap.String("name", cb.name), | ||
zap.String("config", fmt.Sprintf("%+v", cb.config))) | ||
return cb.newState(now, StateHalfOpen), nil | ||
} else { | ||
// continue in the open state till CoolDownInterval is over | ||
cb.fastFailCounter.Inc() | ||
return s, errs.ErrCircuitBreakerOpen | ||
} | ||
case StateHalfOpen: | ||
// do we need some expire time here in case of one of pending requests is stuck forever? | ||
if s.failureCount > 0 { | ||
// there were some failures during half-open state, let's go back to open state to wait a bit longer | ||
log.Error("Circuit breaker goes from half-open to open again as errors persist and continue to fail all requests", | ||
zap.String("name", cb.name), | ||
zap.String("config", fmt.Sprintf("%+v", cb.config))) | ||
cb.fastFailCounter.Inc() | ||
return cb.newState(now, StateOpen), errs.ErrCircuitBreakerOpen | ||
} else if s.successCount == s.cb.config.HalfOpenSuccessCount { | ||
// all probe requests are succeeded, we can move to closed state and allow all requests | ||
log.Info("Circuit breaker is closed. Start allowing all requests", | ||
zap.String("name", cb.name), | ||
zap.String("config", fmt.Sprintf("%+v", cb.config))) | ||
return cb.newState(now, StateClosed), nil | ||
} else if s.pendingCount < s.cb.config.HalfOpenSuccessCount { | ||
// allow more probe requests and continue in half-open state | ||
s.pendingCount++ | ||
return s, nil | ||
} else { | ||
// continue in half-open state till all probe requests are done and fail all other requests for now | ||
cb.fastFailCounter.Inc() | ||
return s, errs.ErrCircuitBreakerOpen | ||
} | ||
default: | ||
panic("unknown state") | ||
} | ||
} | ||
|
||
func (s *State[T]) onResult(open Overloading) { | ||
switch open { | ||
case No: | ||
s.successCount++ | ||
s.cb.successCounter.Inc() | ||
case Yes: | ||
s.failureCount++ | ||
s.cb.failureCounter.Inc() | ||
default: | ||
panic("unknown state") | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
never trips = AlwaysCloseSettings?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yes, circuit breaker trips == opens (the current can't flow anymore), meaning never trips == always closed. Or I misunderstood your question? Feel free to suggest a better comment.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
So should it be named
AlwaysCloseSettings
?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yes, thank you! Fixed.