-
Notifications
You must be signed in to change notification settings - Fork 54
/
circuit_breaker.go
278 lines (260 loc) · 5.96 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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
// Copyright 2018 HenryLee. All Rights Reserved.
//
// 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 micro
import (
"sync"
"time"
"github.com/henrylee2cn/goutil"
"github.com/henrylee2cn/erpc/v6"
)
const (
// Statistical interval second
intervalSecond = 10
// The default failure rate threshold
defaultErrorPercentage = 50
// The default period of one-cycle break in milliseconds
defaultBreakDuration = 5000 * time.Millisecond
// circuitBreaker status
closedStatus = 0
halfOpenStatus = 1
openStatus = 2
)
type (
circuitBreaker struct {
linker Linker
newSessionFunc func(addr string) (*cliSession, *erpc.Status)
sessLib goutil.Map
closeCh chan struct{}
enableBreak bool
errorPercentage float64
breakDuration time.Duration
}
cliSession struct {
addr string
status int8 // 0:Closed, 1:Half-Open, 2:Open
succCount [intervalSecond]int64
failCount [intervalSecond]int64
cursor int
halfOpenTimer *time.Timer
halfOpenTesing bool
rwmu sync.RWMutex
circuitBreaker *circuitBreaker
erpc.Session
}
)
func newCircuitBreaker(
enableBreak bool,
errorPercentage int,
breakDuration time.Duration,
linker Linker,
newFn func(string) (erpc.Session, *erpc.Status),
) *circuitBreaker {
c := &circuitBreaker{
linker: linker,
sessLib: goutil.AtomicMap(),
enableBreak: enableBreak,
errorPercentage: float64(errorPercentage),
breakDuration: breakDuration,
closeCh: make(chan struct{}),
}
c.newSessionFunc = func(addr string) (*cliSession, *erpc.Status) {
sess, stat := newFn(addr)
if stat != nil {
return nil, stat
}
return &cliSession{
addr: addr,
Session: sess,
status: closedStatus,
circuitBreaker: c,
}, nil
}
return c
}
func (c *circuitBreaker) start() {
go c.watchOffline()
if c.enableBreak {
go c.work()
}
}
var notFoundService = RerrNotFound.Copy("not found service")
func (c *circuitBreaker) selectSession(serviceMethod string) (*cliSession, *erpc.Status) {
var (
uriPath = getUriPath(serviceMethod)
addr string
s *cliSession
cnt = c.linker.Len(uriPath)
exclude = make(map[string]struct{}, cnt)
stat = notFoundService
)
for i := cnt; i > 0; i-- {
addr, stat = c.linker.Select(uriPath, exclude)
if stat != nil {
return nil, stat
}
_s, ok := c.sessLib.Load(addr)
if !ok {
s, stat = c.newSessionFunc(addr)
if stat != nil {
exclude[addr] = struct{}{}
continue
}
c.sessLib.Store(addr, s)
return s, nil
}
s = _s.(*cliSession)
// circuit breaker check
if !c.enableBreak || s.check() {
return s, nil
}
exclude[addr] = struct{}{}
}
return s, stat
}
func (c *circuitBreaker) work() {
var (
test = time.NewTicker(time.Second)
state = time.NewTicker(time.Second * intervalSecond)
succTotal, failTotal int64
)
for {
select {
case <-test.C:
c.sessLib.Range(func(_, _s interface{}) bool {
s := _s.(*cliSession)
s.rwmu.Lock()
s.cursor++
if s.cursor >= intervalSecond {
s.cursor = 0
}
s.succCount[s.cursor] = 0
s.failCount[s.cursor] = 0
s.rwmu.Unlock()
return true
})
case <-state.C:
c.sessLib.Range(func(addr, _s interface{}) bool {
s := _s.(*cliSession)
s.rwmu.Lock()
defer s.rwmu.Unlock()
if s.status != closedStatus {
return true
}
succTotal, failTotal = 0, 0
for _, a := range s.failCount {
failTotal += a
}
for _, a := range s.succCount {
succTotal += a
}
if failTotal > 0 &&
(float64(failTotal)/float64(failTotal+succTotal))*100 > c.errorPercentage {
s.toOpenLocked()
return true
}
s.cursor++
if s.cursor >= intervalSecond {
s.cursor = 0
}
s.succCount[s.cursor] = 0
s.failCount[s.cursor] = 0
return true
})
case <-c.closeCh:
test.Stop()
state.Stop()
}
}
}
func (c *circuitBreaker) close() {
close(c.closeCh)
c.linker.Close()
}
func (c *circuitBreaker) watchOffline() {
ch := c.linker.WatchOffline()
for addr := range ch {
_s, ok := c.sessLib.Load(addr)
if !ok {
continue
}
c.sessLib.Delete(addr)
s := _s.(*cliSession)
if c.enableBreak && s.halfOpenTimer != nil {
s.halfOpenTimer.Stop()
}
erpc.Go(func() { s.Close() })
}
}
func (s *cliSession) toOpenLocked() {
s.status = openStatus
s.succCount = [intervalSecond]int64{}
s.failCount = [intervalSecond]int64{}
s.cursor = 0
if s.halfOpenTimer == nil {
after := time.AfterFunc(s.circuitBreaker.breakDuration, func() {
s.rwmu.Lock()
s.status = halfOpenStatus
s.halfOpenTesing = false
s.rwmu.Unlock()
})
s.halfOpenTimer = after
} else {
s.halfOpenTimer.Reset(s.circuitBreaker.breakDuration)
}
}
func (s *cliSession) check() bool {
s.rwmu.RLock()
switch s.status {
case openStatus:
s.rwmu.RUnlock()
return false
case closedStatus:
s.rwmu.RUnlock()
return true
case halfOpenStatus:
if s.halfOpenTesing {
s.rwmu.RUnlock()
return false
}
s.rwmu.RUnlock()
s.rwmu.Lock()
s.halfOpenTesing = true
s.rwmu.Unlock()
return true
default:
s.rwmu.RUnlock()
return false
}
}
func (s *cliSession) feedback(healthy bool) {
if !s.circuitBreaker.enableBreak {
return
}
s.rwmu.Lock()
defer s.rwmu.Unlock()
switch s.status {
case closedStatus:
if healthy {
s.succCount[s.cursor]++
} else {
s.failCount[s.cursor]++
}
case halfOpenStatus:
if healthy {
s.status = closedStatus
} else {
s.toOpenLocked()
}
}
}