-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
383 lines (318 loc) · 11.4 KB
/
config.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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
// MIT License
//
//
// Copyright 2023 Grabtaxi Holdings Pte Ltd (GRAB), All rights reserved.
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE
package redis
import (
"context"
"crypto/tls"
"fmt"
"sort"
"strings"
"time"
"github.com/google/uuid"
"github.com/grab/grab-redis/circuitbreaker"
goredis "github.com/grab/redis/v8"
)
type ConnectorConfig struct {
Main *ClientConfig `json:"main"`
LoadTests []*ClientConfig `json:"loadTests"`
HotReload bool `json:"hotReload"`
// ProcessAllLoadTestPackets this option is for not allowing losing packets when the channel is full when you dual write in new clutser.
// It will increase the latency of requests.
ProcessAllLoadTestPackets bool `json:"processAllLoadTestPackets"`
// SchedulerWorkerNumber defines the max number of workers for load test scheduler, smaller number of workers will use less resources on the load test client.
SchedulerWorkerNumber int `json:"schedulerWorkerNumber"`
// SchedulerChannelSize specifies the max channel size for load test scheduler, it is used as a buffer for requests that are routing to load test client.
// If the channel is full, the request will be abandoned if the ConnectorProcessAllLoadTestPackets is false.
SchedulerChannelSize int `json:"schedulerChannelSize"`
// SchedulerWorkerIdleTimeout specifies the max idle time for a worker, if the worker is idle for this time, it will be terminated.
SchedulerWorkerIdleTimeoutInMs int `json:"schedulerWorkerIdleTimeout"`
}
func (c *ConnectorConfig) initAndValidate() error {
c.Main.init()
if err := c.Main.validate(); err != nil {
return err
}
for _, config := range c.LoadTests {
config.init()
}
for _, config := range c.LoadTests {
if err := config.validate(); err != nil {
return err
}
}
if c.SchedulerWorkerNumber == 0 {
c.SchedulerWorkerNumber = defaultMaxWorker
}
if c.SchedulerChannelSize == 0 {
c.SchedulerChannelSize = defaultMaxChanSize
}
if c.SchedulerWorkerIdleTimeoutInMs == 0 {
c.SchedulerWorkerIdleTimeoutInMs = defaultWorkerIdleTimeout
}
return nil
}
// ClientConfig keeps the settings to set up redis connector, for more details of those parameter, please refer to:https://wiki.grab.com/display/DBOps/Redis+Connector+Manual#RedisConnectorManual-ConfigurationParameterTable
type ClientConfig struct {
// Redis connector mode, could be ModeCluster, ModeMasterSlaveGroup or ModeSingleHost
ClientMode ClientMode `json:"clientMode"`
// Addrs in format of host:port to connect to redis.
// For ModeCluster, use a seed list of addresses of cluster nodes.
// For ModeMasterSlaveGroup, use the master address followed by addresses of all slave nodes.
// For ModeSingleHost, use only the single host address.
Addrs []string `json:"addrs"`
Username string `json:"username"`
Password string `json:"password"`
// Database to be selected after connecting to the server.
// For ModeSingleHost only.
DB int `json:"db"`
MaxRetries int `json:"maxRetries"`
MinRetryBackoffInMs int `json:"minRetryBackoffInMs"`
MaxRetryBackoffInMs int `json:"maxRetryBackoffInMs"`
DialTimeoutInMs int `json:"dialTimeoutInMs"`
ReadTimeoutInMs int `json:"readTimeoutInMs"`
WriteTimeoutInMs int `json:"writeTimeoutInMs"`
PoolSize int `json:"poolSize"`
MinIdleConns int `json:"minIdleConns"`
MaxIdleConns int `json:"maxIdleConns"`
MaxConnAgeInMs int `json:"maxConnAgeInMs"`
PoolTimeoutInMs int `json:"poolTimeoutInMs"`
IdleTimeoutInMs int `json:"idleTimeoutInMs"`
IdleCheckFrequencyInMs int `json:"idleCheckFrequencyInMs"`
// TLSEnabled will set the InsecureSkipVerify flag in TLS to negotiate during Dail
TLSEnabled bool `json:"tlsEnabled"`
// Hystrix setting that is common to all nodes.
// Each node has its own circuit breaker
HystrixEnabled bool `json:"hystrixEnabled"`
Hystrix Hystrix `json:"hystrix"`
// The maximum number of retries among nodes before giving up.
// Command is retried on network errors and MOVED/ASK redirects.
// For ModeCluster and ModeMasterSlaveGroup only.
MaxRedirects int `json:"maxRedirects"`
// Read-only commands routing option.
// For ModeCluster and ModeMasterSlaveGroup only.
ReadMode ReadMode `json:"readMode"`
// For dual write scenarios, this option is for only routing the non-readonly cmds to the new cluster to reduce traffic.
// Only support ignore read-only cmds routing to the new cluster in Do method.
// Enable this option will affect the prod Redis's request routing.
IgnoreReadOnly bool `json:"ignoreReadOnly"`
}
func (c *ClientConfig) mode() string {
return string(c.ClientMode)
}
func (c *ClientConfig) name() string {
if len(c.Addrs) == 0 {
return defaultHostAndPort
}
if c.ClientMode == ModeSingleHost {
return c.Addrs[0]
}
sort.Strings(c.Addrs)
return strings.Join(c.Addrs, ",")
}
func (c *ClientConfig) init() {
if len(c.Addrs) == 0 {
c.Addrs = []string{defaultHostAndPort}
}
if c.ReadMode == "" || c.ReadMode == ucmEmptyString {
c.ReadMode = defaultReadMode
}
if c.Username == ucmEmptyString {
c.Username = ""
}
if c.Password == ucmEmptyString {
c.Password = ""
}
if c.DialTimeoutInMs == 0 {
c.DialTimeoutInMs = defaultDialTimeoutInMs
}
if c.Hystrix.TimeoutInMs == 0 {
c.Hystrix.TimeoutInMs = defaultCBTimeoutInMS
}
if c.Hystrix.MaxConcurrentRequests == 0 {
c.Hystrix.MaxConcurrentRequests = defaultCBMaxConcurrent
}
if c.Hystrix.ErrorPercentThreshold == 0 {
c.Hystrix.ErrorPercentThreshold = defaultCBErrPercent
}
}
func (c *ClientConfig) validate() error {
if len(c.Addrs) == 0 {
return fmt.Errorf("no addrs found in config")
}
if !c.ClientMode.IsValid() {
return fmt.Errorf("client mode %s is not valid", c.ClientMode)
}
if !c.ReadMode.IsValid() {
return fmt.Errorf("read mode %s is not valid", c.ClientMode)
}
return nil
}
func (c *ClientConfig) validateReload(config *ClientConfig) error {
if err := config.validate(); err != nil {
return err
}
if c.ClientMode != config.ClientMode {
return fmt.Errorf("client mode change is not allowed in reloading")
}
if c.DB != config.DB {
return fmt.Errorf("DB change is not allowed in reloading")
}
if !isAddrsEquals(c.Addrs, config.Addrs) {
return fmt.Errorf("addrs change is not allowed in reloading")
}
return nil
}
func (c *ClientConfig) createClient(cbOptions []circuitbreaker.Option) (clientWrapper, error) {
switch c.ClientMode {
default:
return nil, fmt.Errorf("invalid client mode to init Redis client")
case ModeCluster:
return &clusterWrapperImpl{
ClusterClient: goredis.NewDynamicClusterClient(c.clusterOptions(cbOptions)),
config: c,
}, nil
case ModeMasterSlaveGroup:
return &clusterWrapperImpl{
ClusterClient: goredis.NewDynamicClusterClient(c.masterSlaveGroupOptions(cbOptions)),
config: c,
}, nil
case ModeSingleHost:
return &clientWrapperImpl{
Client: goredis.NewDynamicClient(c.singleHostOptions(cbOptions)),
config: c,
}, nil
}
}
func (c *ClientConfig) clusterOptions(cbOptions []circuitbreaker.Option) *goredis.ClusterOptions {
opt := &goredis.ClusterOptions{
Addrs: c.Addrs,
Username: c.Username,
Password: c.Password,
MaxRetries: c.MaxRetries,
MinRetryBackoff: parseDurationInMs(c.MinRetryBackoffInMs),
MaxRetryBackoff: parseDurationInMs(c.MaxRetryBackoffInMs),
DialTimeout: parseDurationInMs(c.DialTimeoutInMs),
ReadTimeout: parseDurationInMs(c.ReadTimeoutInMs),
WriteTimeout: parseDurationInMs(c.WriteTimeoutInMs),
PoolSize: c.PoolSize,
MinIdleConns: c.MinIdleConns,
MaxIdleConns: c.MaxIdleConns,
MaxConnAge: parseDurationInMs(c.MaxConnAgeInMs),
PoolTimeout: parseDurationInMs(c.PoolTimeoutInMs),
IdleTimeout: parseDurationInMs(c.IdleTimeoutInMs),
IdleCheckFrequency: parseDurationInMs(c.IdleCheckFrequencyInMs),
MaxRedirects: c.MaxRedirects,
}
switch c.ReadMode {
case ModeReadFromMaster:
opt.ReadOnly = false
case ModeReadFromSlaves:
opt.ReadOnly = true
case ModeReadRandomly:
opt.RouteRandomly = true
case ModeReadByLatency:
opt.RouteByLatency = true
}
if c.TLSEnabled {
opt.TLSConfig = &tls.Config{
InsecureSkipVerify: true,
}
}
if c.HystrixEnabled {
opt.NewClient = func(opt *goredis.Options) *goredis.Client {
cbKey := generateCBKey(opt.Addr)
configureHystrix(cbKey, c.Hystrix)
opt.Limiter = newLimiter(cbKey, cbOptions)
return goredis.NewDynamicClient(opt)
}
}
return opt
}
func (c *ClientConfig) masterSlaveGroupOptions(cbOptions []circuitbreaker.Option) *goredis.ClusterOptions {
opt := c.clusterOptions(cbOptions)
var nodes []goredis.ClusterNode
for _, addr := range opt.Addrs {
nodes = append(nodes, goredis.ClusterNode{ID: uuid.NewString(), Addr: addr})
}
opt.ClusterSlots = func(ctx context.Context) ([]goredis.ClusterSlot, error) {
return []goredis.ClusterSlot{
{Start: 0, End: 16383, Nodes: nodes},
}, nil
}
return opt
}
func (c *ClientConfig) singleHostOptions(cbOptions []circuitbreaker.Option) *goredis.Options {
addr := defaultHostAndPort
if len(c.Addrs) > 0 {
addr = c.Addrs[0]
}
opt := &goredis.Options{
Addr: addr,
Username: c.Username,
Password: c.Password,
DB: c.DB,
MaxRetries: c.MaxRetries,
MinRetryBackoff: parseDurationInMs(c.MinRetryBackoffInMs),
MaxRetryBackoff: parseDurationInMs(c.MaxRetryBackoffInMs),
DialTimeout: parseDurationInMs(c.DialTimeoutInMs),
ReadTimeout: parseDurationInMs(c.ReadTimeoutInMs),
WriteTimeout: parseDurationInMs(c.WriteTimeoutInMs),
PoolSize: c.PoolSize,
MinIdleConns: c.MinIdleConns,
MaxIdleConns: c.MaxIdleConns,
MaxConnAge: parseDurationInMs(c.MaxConnAgeInMs),
PoolTimeout: parseDurationInMs(c.PoolTimeoutInMs),
IdleTimeout: parseDurationInMs(c.IdleTimeoutInMs),
IdleCheckFrequency: parseDurationInMs(c.IdleCheckFrequencyInMs),
}
if c.TLSEnabled {
opt.TLSConfig = &tls.Config{
InsecureSkipVerify: true,
}
}
if c.HystrixEnabled {
cbKey := generateCBKey(addr)
configureHystrix(cbKey, c.Hystrix)
opt.Limiter = newLimiter(cbKey, cbOptions)
}
return opt
}
func isAddrsEquals(addrs1 []string, addrs2 []string) bool {
if len(addrs1) != len(addrs2) {
return false
}
sort.Strings(addrs1)
sort.Strings(addrs2)
for i := range addrs1 {
if addrs1[i] != addrs2[i] {
return false
}
}
return true
}
func parseDurationInMs(durationInMs int) time.Duration {
return time.Duration(durationInMs) * time.Millisecond
}