forked from CodisLabs/codis
/
helper.go
279 lines (230 loc) · 6.48 KB
/
helper.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
// Copyright 2014 Wandoujia Inc. All Rights Reserved.
// Licensed under the MIT (MIT-LICENSE.txt) license.
package router
import (
"bufio"
"io"
"os/exec"
"strconv"
"strings"
"time"
"github.com/wandoulabs/codis/pkg/utils"
"github.com/wandoulabs/codis/pkg/models"
"github.com/wandoulabs/codis/pkg/proxy/parser"
"github.com/wandoulabs/codis/pkg/proxy/router/topology"
log "github.com/ngaut/logging"
"github.com/juju/errors"
topo "github.com/ngaut/go-zookeeper/zk"
stats "github.com/ngaut/gostats"
respcoding "github.com/ngaut/resp"
)
var blackList = []string{
"KEYS", "MOVE", "OBJECT", "RENAME", "RENAMENX", "SORT", "SCAN", "BITOP" /*"MGET",*/ /* "MSET",*/, "MSETNX", "SCAN",
"BLPOP", "BRPOP", "BRPOPLPUSH", "PSUBSCRIBE,PUBLISH", "PUNSUBSCRIBE", "SUBSCRIBE", "RANDOMKEY",
"UNSUBSCRIBE", "DISCARD", "EXEC", "MULTI", "UNWATCH", "WATCH", "SCRIPT EXISTS", "SCRIPT FLUSH", "SCRIPT KILL",
"SCRIPT LOAD" /*, "AUTH" , "ECHO"*/ /*"QUIT",*/ /*"SELECT",*/, "BGREWRITEAOF", "BGSAVE", "CLIENT KILL", "CLIENT LIST",
"CONFIG GET", "CONFIG SET", "CONFIG RESETSTAT", "DBSIZE", "DEBUG OBJECT", "DEBUG SEGFAULT", "FLUSHALL", "FLUSHDB",
"INFO", "LASTSAVE", "MONITOR", "SAVE", "SHUTDOWN", "SLAVEOF", "SLOWLOG", "SYNC", "TIME", "SLOTSMGRTONE", "SLOTSMGRT",
"SLOTSDEL",
}
var (
blackListCommand = make(map[string]struct{})
OK_BYTES = []byte("+OK\r\n")
)
func init() {
for _, k := range blackList {
blackListCommand[k] = struct{}{}
}
}
func allowOp(op string) bool {
_, black := blackListCommand[op]
return !black
}
func isMulOp(op string) bool {
if op == "MGET" || op == "DEL" || op == "MSET" {
return true
}
return false
}
func validSlot(i int) bool {
if i < 0 || i >= models.DEFAULT_SLOT_NUM {
return false
}
return true
}
func WriteMigrateKeyCmd(w io.Writer, addr string, timeoutMs int, key []byte) error {
hostPort := strings.Split(addr, ":")
if len(hostPort) != 2 {
return errors.Errorf("invalid address " + addr)
}
respW := respcoding.NewRESPWriter(w)
err := respW.WriteCommand("slotsmgrttagone", hostPort[0], hostPort[1],
strconv.Itoa(int(timeoutMs)), string(key))
return errors.Trace(err)
}
type DeadlineReadWriter interface {
io.Writer
io.Reader
SetWriteDeadline(t time.Time) error
SetReadDeadline(t time.Time) error
}
func handleSpecCommand(cmd string, clientWriter DeadlineReadWriter, keys [][]byte) (bool, bool, error) {
var b []byte
shouldClose := false
switch cmd {
case "PING":
b = []byte("+PONG\r\n")
case "QUIT":
b = OK_BYTES
shouldClose = true
case "SELECT":
b = OK_BYTES
case "AUTH":
b = OK_BYTES
case "ECHO":
if len(keys) > 0 {
var err error
b, err = respcoding.Marshal(string(keys[0]))
if err != nil {
return true, false, errors.Trace(err)
}
} else {
return true, false, nil
}
}
if len(b) > 0 {
clientWriter.SetWriteDeadline(time.Now().Add(5 * time.Second))
_, err := clientWriter.Write(b)
if err != nil {
return shouldClose, true, errors.Errorf("%s, cmd:%s", err.Error(), cmd)
}
return shouldClose, true, nil
}
return shouldClose, false, nil
}
func write2Client(redisReader *bufio.Reader, clientWriter io.Writer) (redisErr error, clientErr error) {
resp, err := parser.Parse(redisReader)
if err != nil {
return errors.Trace(err), errors.Trace(err)
}
b, err := resp.Bytes()
if err != nil {
return errors.Trace(err), errors.Trace(err)
}
_, err = clientWriter.Write(b)
return nil, errors.Trace(err)
}
func write2Redis(resp *parser.Resp, redisWriter io.Writer) error {
// get resp in bytes
b, err := resp.Bytes()
if err != nil {
return errors.Trace(err)
}
return writeBytes2Redis(b, redisWriter)
}
func writeBytes2Redis(b []byte, redisWriter io.Writer) error {
// write to redis
_, err := redisWriter.Write(b)
return errors.Trace(err)
}
type BufioDeadlineReadWriter interface {
DeadlineReadWriter
BufioReader() *bufio.Reader
}
func forward(c DeadlineReadWriter, redisConn BufioDeadlineReadWriter, resp *parser.Resp) (redisErr error, clientErr error) {
redisReader := redisConn.BufioReader()
if err := redisConn.SetWriteDeadline(time.Now().Add(5 * time.Second)); err != nil {
return errors.Trace(err), errors.Trace(err)
}
if err := write2Redis(resp, redisConn); err != nil {
return errors.Trace(err), errors.Trace(err)
}
if err := redisConn.SetReadDeadline(time.Now().Add(5 * time.Second)); err != nil {
return errors.Trace(err), errors.Trace(err)
}
if err := c.SetWriteDeadline(time.Now().Add(5 * time.Second)); err != nil {
return nil, errors.Trace(err)
}
// read and parse redis response
return write2Client(redisReader, c)
}
func StringsContain(s []string, key string) bool {
for _, val := range s {
if val == key { //need our resopnse
return true
}
}
return false
}
func GetEventPath(evt interface{}) string {
return evt.(topo.Event).Path
}
func CheckUlimit(min int) {
ulimitN, err := exec.Command("/bin/sh", "-c", "ulimit -n").Output()
if err != nil {
log.Warning("get ulimit failed", err)
}
n, err := strconv.Atoi(strings.TrimSpace(string(ulimitN)))
if err != nil || n < min {
log.Fatalf("ulimit too small: %d, should be at least %d", min, n)
}
}
func GetOriginError(err *errors.Err) error {
if err != nil {
if err.Cause() == nil && err.Underlying() == nil {
return err
} else {
return err.Underlying()
}
}
return err
}
func getOpKeys(resp *parser.Resp) ([]byte, [][]byte, error) {
op, err := resp.Op()
if err != nil {
return nil, nil, errors.Trace(err)
}
if len(op) == 0 || len(op) > 50 {
return nil, nil, errors.Errorf("error parse op %s", string(op))
}
keys, err := resp.Keys()
return op, keys, errors.Trace(err)
}
func recordResponseTime(c *stats.Counters, d time.Duration) {
switch {
case d < 5:
c.Add("0-5ms", 1)
case d >= 5 && d < 10:
c.Add("5-10ms", 1)
case d >= 10 && d < 50:
c.Add("10-50ms", 1)
case d >= 50 && d < 200:
c.Add("50-200ms", 1)
case d >= 200 && d < 1000:
c.Add("200-1000ms", 1)
case d >= 1000 && d < 5000:
c.Add("1000-5000ms", 1)
default:
c.Add(">=5000ms", 1)
}
}
type Conf struct {
proxyId string
productName string
zkAddr string
f topology.ZkFactory
}
func LoadConf(configFile string) (*Conf, error) {
srvConf := &Conf{}
conf, err := utils.InitConfigFromFile(configFile)
if err != nil {
log.Fatal(err)
}
srvConf.productName, _ = conf.ReadString("product", "test")
if len(srvConf.productName) == 0 {
log.Fatalf("invalid config: %+v", srvConf)
}
srvConf.zkAddr, _ = conf.ReadString("zk", "localhost:2181")
srvConf.proxyId, _ = conf.ReadString("proxy_id", "proxy_1")
return srvConf, nil
}