-
Notifications
You must be signed in to change notification settings - Fork 818
/
cbsuite.go
360 lines (319 loc) · 10.1 KB
/
cbsuite.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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
/*
* Copyright 2021 CloudWeGo 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 circuitbreak
import (
"context"
"fmt"
"strings"
"sync"
"time"
"github.com/bytedance/gopkg/cloud/circuitbreaker"
"github.com/cloudwego/kitex/pkg/discovery"
"github.com/cloudwego/kitex/pkg/endpoint"
"github.com/cloudwego/kitex/pkg/event"
"github.com/cloudwego/kitex/pkg/kerrors"
"github.com/cloudwego/kitex/pkg/rpcinfo"
)
const (
serviceCBKey = "service"
instanceCBKey = "instance"
cbConfig = "cb_config"
)
var defaultCBConfig = CBConfig{Enable: true, ErrRate: 0.5, MinSample: 200}
// GetDefaultCBConfig return defaultConfig of CircuitBreaker.
func GetDefaultCBConfig() CBConfig {
return defaultCBConfig
}
// CBConfig is policy config of CircuitBreaker.
// DON'T FORGET to update DeepCopy() and Equals() if you add new fields.
type CBConfig struct {
Enable bool `json:"enable"`
ErrRate float64 `json:"err_rate"`
MinSample int64 `json:"min_sample"`
}
// DeepCopy returns a full copy of CBConfig.
func (c *CBConfig) DeepCopy() *CBConfig {
if c == nil {
return nil
}
return &CBConfig{
Enable: c.Enable,
ErrRate: c.ErrRate,
MinSample: c.MinSample,
}
}
func (c *CBConfig) Equals(other *CBConfig) bool {
if c == nil && other == nil {
return true
}
if c == nil || other == nil {
return false
}
return c.Enable == other.Enable && c.ErrRate == other.ErrRate && c.MinSample == other.MinSample
}
// GenServiceCBKeyFunc to generate circuit breaker key through rpcinfo.
// You can customize the config key according to your config center.
type GenServiceCBKeyFunc func(ri rpcinfo.RPCInfo) string
type instanceCBConfig struct {
CBConfig
sync.RWMutex
}
// CBSuite is default wrapper of CircuitBreaker. If you don't have customized policy, you can specify CircuitBreaker
// middlewares like this:
//
// cbs := NewCBSuite(GenServiceCBKeyFunc)
// opts = append(opts, client.WithCircuitBreaker(cbs))
type CBSuite struct {
servicePanel circuitbreaker.Panel
serviceControl *Control
instancePanel circuitbreaker.Panel
instanceControl *Control
genServiceCBKey GenServiceCBKeyFunc
serviceCBConfig sync.Map // map[serviceCBKey]CBConfig
instanceCBConfig instanceCBConfig
events event.Queue
}
// NewCBSuite to build a new CBSuite.
// Notice: Should NewCBSuite for every client in this version,
// because event.Queue and event.Bus are not shared with all clients now.
func NewCBSuite(genKey GenServiceCBKeyFunc) *CBSuite {
s := &CBSuite{genServiceCBKey: genKey}
s.instanceCBConfig = instanceCBConfig{CBConfig: defaultCBConfig}
return s
}
// ServiceCBMW return a new service level CircuitBreakerMW.
func (s *CBSuite) ServiceCBMW() endpoint.Middleware {
if s == nil {
return endpoint.DummyMiddleware
}
s.initServiceCB()
return NewCircuitBreakerMW(*s.serviceControl, s.servicePanel)
}
// InstanceCBMW return a new instance level CircuitBreakerMW.
func (s *CBSuite) InstanceCBMW() endpoint.Middleware {
if s == nil {
return endpoint.DummyMiddleware
}
s.initInstanceCB()
return NewCircuitBreakerMW(*s.instanceControl, s.instancePanel)
}
// ServicePanel return return cb Panel of service
func (s *CBSuite) ServicePanel() circuitbreaker.Panel {
if s.servicePanel == nil {
s.initServiceCB()
}
return s.servicePanel
}
// ServiceControl return cb Control of service
func (s *CBSuite) ServiceControl() *Control {
if s.serviceControl == nil {
s.initServiceCB()
}
return s.serviceControl
}
// UpdateServiceCBConfig is to update service CircuitBreaker config.
// This func is suggested to be called in remote config module.
func (s *CBSuite) UpdateServiceCBConfig(key string, cfg CBConfig) {
s.serviceCBConfig.Store(key, cfg)
}
// UpdateInstanceCBConfig is to update instance CircuitBreaker param.
// This func is suggested to be called in remote config module.
func (s *CBSuite) UpdateInstanceCBConfig(cfg CBConfig) {
s.instanceCBConfig.Lock()
s.instanceCBConfig.CBConfig = cfg
s.instanceCBConfig.Unlock()
}
// SetEventBusAndQueue is to make CircuitBreaker relate to event change.
func (s *CBSuite) SetEventBusAndQueue(bus event.Bus, events event.Queue) {
s.events = events
if bus != nil {
bus.Watch(discovery.ChangeEventName, s.discoveryChangeHandler)
}
}
// Dump is to dump CircuitBreaker info for debug query.
func (s *CBSuite) Dump() interface{} {
return map[string]interface{}{
serviceCBKey: cbDebugInfo(s.servicePanel),
instanceCBKey: cbDebugInfo(s.instancePanel),
cbConfig: s.configInfo(),
}
}
// Close circuitbreaker.Panel to release associated resources.
func (s *CBSuite) Close() error {
if s.servicePanel != nil {
s.servicePanel.Close()
s.servicePanel = nil
s.serviceControl = nil
}
if s.instancePanel != nil {
s.instancePanel.Close()
s.instancePanel = nil
s.instanceControl = nil
}
return nil
}
func (s *CBSuite) initServiceCB() {
if s.servicePanel != nil && s.serviceControl != nil {
return
}
if s.genServiceCBKey == nil {
s.genServiceCBKey = RPCInfo2Key
}
opts := circuitbreaker.Options{
ShouldTripWithKey: s.svcTripFunc,
}
s.servicePanel, _ = circuitbreaker.NewPanel(s.onServiceStateChange, opts)
svcKey := func(ctx context.Context, request interface{}) (serviceCBKey string, enabled bool) {
ri := rpcinfo.GetRPCInfo(ctx)
serviceCBKey = s.genServiceCBKey(ri)
cbConfig, _ := s.serviceCBConfig.LoadOrStore(serviceCBKey, defaultCBConfig)
enabled = cbConfig.(CBConfig).Enable
return
}
s.serviceControl = &Control{
GetKey: svcKey,
GetErrorType: ErrorTypeOnServiceLevel,
DecorateError: func(ctx context.Context, request interface{}, err error) error {
return kerrors.ErrServiceCircuitBreak
},
}
}
func (s *CBSuite) initInstanceCB() {
if s.instancePanel != nil && s.instanceControl != nil {
return
}
opts := circuitbreaker.Options{
ShouldTripWithKey: s.insTripFunc,
}
s.instancePanel, _ = circuitbreaker.NewPanel(s.onInstanceStateChange, opts)
instanceKey := func(ctx context.Context, request interface{}) (instCBKey string, enabled bool) {
ri := rpcinfo.GetRPCInfo(ctx)
instCBKey = ri.To().Address().String()
s.instanceCBConfig.RLock()
enabled = s.instanceCBConfig.Enable
s.instanceCBConfig.RUnlock()
return
}
s.instanceControl = &Control{
GetKey: instanceKey,
GetErrorType: ErrorTypeOnInstanceLevel,
DecorateError: func(ctx context.Context, request interface{}, err error) error {
return kerrors.ErrInstanceCircuitBreak
},
}
}
func (s *CBSuite) onStateChange(level, key string, oldState, newState circuitbreaker.State, m circuitbreaker.Metricer) {
if s.events == nil {
return
}
successes, failures, timeouts := m.Counts()
var errRate float64
if sum := successes + failures + timeouts; sum > 0 {
errRate = float64(failures+timeouts) / float64(sum)
}
s.events.Push(&event.Event{
Name: level + "_cb",
Time: time.Now(),
Detail: fmt.Sprintf("%s: %s -> %s, (succ: %d, err: %d, timeout: %d, rate: %f)",
key, oldState, newState, successes, failures, timeouts, errRate),
})
}
func (s *CBSuite) onServiceStateChange(key string, oldState, newState circuitbreaker.State, m circuitbreaker.Metricer) {
s.onStateChange(serviceCBKey, key, oldState, newState, m)
}
func (s *CBSuite) onInstanceStateChange(key string, oldState, newState circuitbreaker.State, m circuitbreaker.Metricer) {
s.onStateChange(instanceCBKey, key, oldState, newState, m)
}
func (s *CBSuite) discoveryChangeHandler(e *event.Event) {
if s.instancePanel == nil {
return
}
extra := e.Extra.(*discovery.Change)
for i := range extra.Removed {
instCBKey := extra.Removed[i].Address().String()
s.instancePanel.RemoveBreaker(instCBKey)
}
}
func (s *CBSuite) svcTripFunc(key string) circuitbreaker.TripFunc {
pi, _ := s.serviceCBConfig.LoadOrStore(key, defaultCBConfig)
p := pi.(CBConfig)
return circuitbreaker.RateTripFunc(p.ErrRate, p.MinSample)
}
func (s *CBSuite) insTripFunc(key string) circuitbreaker.TripFunc {
s.instanceCBConfig.RLock()
errRate := s.instanceCBConfig.ErrRate
minSample := s.instanceCBConfig.MinSample
s.instanceCBConfig.RUnlock()
return circuitbreaker.RateTripFunc(errRate, minSample)
}
func cbDebugInfo(panel circuitbreaker.Panel) map[string]interface{} {
dumper, ok := panel.(interface {
DumpBreakers() map[string]circuitbreaker.Breaker
})
if !ok {
return nil
}
cbMap := make(map[string]interface{})
for key, breaker := range dumper.DumpBreakers() {
cbState := breaker.State()
if cbState == circuitbreaker.Closed {
continue
}
cbMap[key] = map[string]interface{}{
"state": cbState,
"successes in 10s": breaker.Metricer().Successes(),
"failures in 10s": breaker.Metricer().Failures(),
"timeouts in 10s": breaker.Metricer().Timeouts(),
"error rate in 10s": breaker.Metricer().ErrorRate(),
}
}
if len(cbMap) == 0 {
cbMap["msg"] = "all circuit breakers are in closed state"
}
return cbMap
}
func (s *CBSuite) configInfo() map[string]interface{} {
svcCBMap := make(map[string]interface{})
s.serviceCBConfig.Range(func(key, value interface{}) bool {
svcCBMap[key.(string)] = value
return true
})
s.instanceCBConfig.RLock()
instCBConfig := s.instanceCBConfig.CBConfig
s.instanceCBConfig.RUnlock()
cbMap := make(map[string]interface{}, 2)
cbMap[serviceCBKey] = svcCBMap
cbMap[instanceCBKey] = instCBConfig
return cbMap
}
// RPCInfo2Key is to generate circuit breaker key through rpcinfo
func RPCInfo2Key(ri rpcinfo.RPCInfo) string {
if ri == nil {
return ""
}
fromService := ri.From().ServiceName()
toService := ri.To().ServiceName()
method := ri.To().Method()
sum := len(fromService) + len(toService) + len(method) + 2
var buf strings.Builder
buf.Grow(sum)
buf.WriteString(fromService)
buf.WriteByte('/')
buf.WriteString(toService)
buf.WriteByte('/')
buf.WriteString(method)
return buf.String()
}