/
circuit_breaker.go
259 lines (232 loc) · 6.19 KB
/
circuit_breaker.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
// a simple golang breaker according to https://docs.microsoft.com/en-us/previous-versions/msp-n-p/dn589784(v=pandp.10)
package common
import (
"errors"
"strings"
"sync"
"time"
)
const (
defaultBackupEndpoint = "ap-guangzhou.tencentcloudapi.com"
defaultMaxFailNum = 5
defaultMaxFailPercentage = 75
defaultWindowLength = 1 * 60 * time.Second
defaultTimeout = 60 * time.Second
)
var (
// ErrOpenState is returned when the CB state is open
errOpenState = errors.New("circuit breaker is open")
)
// counter use atomic operations to ensure consistency
// Atomic operations perform better than mutex
type counter struct {
failures int
all int
consecutiveSuccesses int
consecutiveFailures int
}
func newRegionCounter() counter {
return counter{
failures: 0,
all: 0,
consecutiveSuccesses: 0,
consecutiveFailures: 0,
}
}
func (c *counter) onSuccess() {
c.all++
c.consecutiveSuccesses++
c.consecutiveFailures = 0
}
func (c *counter) onFailure() {
c.all++
c.failures++
c.consecutiveSuccesses = 0
c.consecutiveSuccesses = 0
}
func (c *counter) clear() {
c.all = 0
c.failures = 0
c.consecutiveSuccesses = 0
}
// State is a type that represents a state of CircuitBreaker.
type state int
// These constants are states of CircuitBreaker.
const (
StateClosed state = iota
StateHalfOpen
StateOpen
)
type breakerSetting struct {
// backupEndpoint
// the default is "ap-guangzhou.tencentcloudapi.com"
backupEndpoint string
// max fail nums
// the default is 5
maxFailNum int
// max fail percentage
// the default is 75/100
maxFailPercentage int
// windowInterval decides when to reset counter if the state is StateClosed
// the default is 5minutes
windowInterval time.Duration
// timeout decides when to turn StateOpen to StateHalfOpen
// the default is 60s
timeout time.Duration
// maxRequests decides when to turn StateHalfOpen to StateClosed
maxRequests int
}
type circuitBreaker struct {
// settings
breakerSetting
// read and write lock
mu sync.Mutex
// the breaker's state: closed, open, half-open
state state
// expiry time determines whether to enter the next generation
// if in StateClosed, it will be now + windowInterval
// if in StateOpen, it will be now + timeout
// if in StateHalfOpen. it will be zero
expiry time.Time
// generation decide whether add the afterRequest's request to counter
generation uint64
// counter
counter counter
}
func newRegionBreaker(set breakerSetting) (re *circuitBreaker) {
re = new(circuitBreaker)
re.breakerSetting = set
return
}
func defaultRegionBreaker() *circuitBreaker {
defaultSet := breakerSetting{
backupEndpoint: defaultBackupEndpoint,
maxFailNum: defaultMaxFailNum,
maxFailPercentage: defaultMaxFailPercentage,
windowInterval: defaultWindowLength,
timeout: defaultTimeout,
}
return newRegionBreaker(defaultSet)
}
// currentState return the current state.
// if in StateClosed and now is over expiry time, it will turn to a new generation.
// if in StateOpen and now is over expiry time, it will turn to StateHalfOpen
func (s *circuitBreaker) currentState(now time.Time) (state, uint64) {
switch s.state {
case StateClosed:
if s.expiry.Before(now) {
s.toNewGeneration(now)
}
case StateOpen:
if s.expiry.Before(now) {
s.setState(StateHalfOpen, now)
}
}
return s.state, s.generation
}
// setState set the circuitBreaker's state to newState
// and turn to new generation
func (s *circuitBreaker) setState(newState state, now time.Time) {
if s.state == newState {
return
}
s.state = newState
s.toNewGeneration(now)
}
// toNewGeneration will increase the generation and clear the counter.
// it also will reset the expiry
func (s *circuitBreaker) toNewGeneration(now time.Time) {
s.generation++
s.counter.clear()
var zero time.Time
switch s.state {
case StateClosed:
s.expiry = now.Add(s.windowInterval)
case StateOpen:
s.expiry = now.Add(s.timeout)
default: // StateHalfOpen
s.expiry = zero
}
}
// beforeRequest return the current generation; if the breaker is in StateOpen, it will also return an errOpenState
func (s *circuitBreaker) beforeRequest() (uint64, error) {
s.mu.Lock()
defer s.mu.Unlock()
now := time.Now()
state, generation := s.currentState(now)
//log.Println(s.counter)
if state == StateOpen {
return generation, errOpenState
}
return generation, nil
}
func (s *circuitBreaker) afterRequest(before uint64, success bool) {
s.mu.Lock()
defer s.mu.Unlock()
now := time.Now()
state, generation := s.currentState(now)
// the breaker has entered the next generation, the current results abandon.
if generation != before {
return
}
if success {
s.onSuccess(state, now)
} else {
s.onFailure(state, now)
}
}
func (s *circuitBreaker) onSuccess(state state, now time.Time) {
switch state {
case StateClosed:
s.counter.onSuccess()
case StateHalfOpen:
s.counter.onSuccess()
// The conditions for closing breaker are met
if s.counter.all-s.counter.failures >= s.maxRequests {
s.setState(StateClosed, now)
}
}
}
func (s *circuitBreaker) readyToOpen(c counter) bool {
failPre := float64(c.failures) / float64(c.all)
return (c.failures >= s.maxFailNum && failPre >= float64(s.maxFailPercentage)/100.0) ||
c.consecutiveFailures > 5
}
func (s *circuitBreaker) onFailure(state state, now time.Time) {
switch state {
case StateClosed:
s.counter.onFailure()
if f := s.readyToOpen(s.counter); f {
s.setState(StateOpen, now)
}
case StateHalfOpen:
s.setState(StateOpen, now)
}
}
// checkEndpoint
// valid: cvm.ap-shanghai.tencentcloudapi.com, cvm.ap-shenzhen-fs.tencentcloudapi.com,cvm.tencentcloudapi.com
// invalid: cvm.tencentcloud.com
func checkEndpoint(endpoint string) bool {
ss := strings.Split(endpoint, ".")
if len(ss) != 4 && len(ss) != 3 {
return false
}
if ss[len(ss)-2] != "tencentcloudapi" {
return false
}
// ap-beijing
if len(ss) == 4 && len(strings.Split(ss[1], "-")) < 2 {
return false
}
return true
}
func renewUrl(oldDomain, region string) string {
ss := strings.Split(oldDomain, ".")
if len(ss) == 3 {
ss = append([]string{ss[0], region}, ss[1:]...)
} else if len(ss) == 4 {
ss[1] = region
}
newDomain := strings.Join(ss, ".")
return newDomain
}