-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathmain.go
278 lines (223 loc) · 6.94 KB
/
main.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
package main
import (
"bufio"
"flag"
"fmt"
"io"
"log"
"net"
"os"
"regexp"
"strconv"
"strings"
)
var (
masterPort int
masterHost string
proxyPort int
proxyHost string
keyRegexp *regexp.Regexp
)
const (
bufSize = 16384
channelBuffer = 100
)
type redisCommand struct {
raw []byte
command []string
reply string
bulkSize int64
}
func readRedisCommand(reader *bufio.Reader) (*redisCommand, error) {
header, err := reader.ReadString('\n')
if err != nil {
return nil, fmt.Errorf("Failed to read command: %v", err)
}
if header == "\n" || header == "\r\n" {
// empty command
return &redisCommand{raw: []byte(header)}, nil
}
if strings.HasPrefix(header, "+") {
return &redisCommand{raw: []byte(header), reply: strings.TrimSpace(header[1:])}, nil
}
if strings.HasPrefix(header, "$") {
bulkSize, err := strconv.ParseInt(strings.TrimSpace(header[1:]), 10, 64)
if err != nil {
return nil, fmt.Errorf("Unable to decode bulk size: %v", err)
}
return &redisCommand{raw: []byte(header), bulkSize: bulkSize}, nil
}
if strings.HasPrefix(header, "*") {
cmdSize, err := strconv.Atoi(strings.TrimSpace(header[1:]))
if err != nil {
return nil, fmt.Errorf("Unable to parse command length: %v", err)
}
result := &redisCommand{raw: []byte(header), command: make([]string, cmdSize)}
for i := range result.command {
header, err = reader.ReadString('\n')
if !strings.HasPrefix(header, "$") || err != nil {
return nil, fmt.Errorf("Failed to read command: %v", err)
}
result.raw = append(result.raw, []byte(header)...)
argSize, err := strconv.Atoi(strings.TrimSpace(header[1:]))
if err != nil {
return nil, fmt.Errorf("Unable to parse argument length: %v", err)
}
argument := make([]byte, argSize)
_, err = io.ReadFull(reader, argument)
if err != nil {
return nil, fmt.Errorf("Failed to read argument: %v", err)
}
result.raw = append(result.raw, argument...)
header, err = reader.ReadString('\n')
if err != nil {
return nil, fmt.Errorf("Failed to read argument: %v", err)
}
result.raw = append(result.raw, []byte(header)...)
result.command[i] = string(argument)
}
return result, nil
}
return &redisCommand{raw: []byte(header), command: []string{strings.TrimSpace(header)}}, nil
}
// Goroutine that handles writing commands to master
func masterWriter(conn net.Conn, masterchannel <-chan []byte) {
defer conn.Close()
for data := range masterchannel {
_, err := conn.Write(data)
if err != nil {
log.Printf("Failed to write data to master: %v\n", err)
return
}
}
}
// Connect to master, request replication and filter it
func masterConnection(slavechannel chan<- []byte, masterchannel <-chan []byte) {
conn, err := net.Dial("tcp", fmt.Sprintf("%s:%d", masterHost, masterPort))
if err != nil {
log.Printf("Failed to connect to master: %v\n", err)
return
}
defer conn.Close()
go masterWriter(conn, masterchannel)
reader := bufio.NewReaderSize(conn, bufSize)
for {
command, err := readRedisCommand(reader)
if err != nil {
log.Printf("Error while reading from master: %v\n", err)
return
}
if command.reply != "" || command.command == nil && command.bulkSize == 0 {
// passthrough reply & empty command
slavechannel <- command.raw
slavechannel <- nil
} else if len(command.command) == 1 && command.command[0] == "PING" {
log.Println("Got PING from master")
slavechannel <- command.raw
slavechannel <- nil
} else if command.bulkSize > 0 {
// RDB Transfer
log.Printf("RDB size: %d\n", command.bulkSize)
slavechannel <- command.raw
err = FilterRDB(reader, slavechannel, func(key string) bool { return keyRegexp.FindStringIndex(key) != nil }, command.bulkSize)
if err != nil {
log.Printf("Unable to read RDB: %v\n", err)
return
}
log.Println("RDB filtering finished, filtering commands...")
} else {
if len(command.command) >= 2 && keyRegexp.FindStringIndex(command.command[1]) == nil {
continue
}
slavechannel <- command.raw
slavechannel <- nil
}
}
}
// Goroutine that handles writing data back to slave
func slaveWriter(conn net.Conn, slavechannel <-chan []byte) {
writer := bufio.NewWriterSize(conn, bufSize)
for data := range slavechannel {
var err error
if data == nil {
err = writer.Flush()
} else {
_, err = writer.Write(data)
}
if err != nil {
log.Printf("Failed to write data to slave: %v\n", err)
return
}
}
}
// Read commands from slave
func slaveReader(conn net.Conn) {
defer conn.Close()
log.Print("Slave connection established from ", conn.RemoteAddr().String())
reader := bufio.NewReaderSize(conn, bufSize)
// channel for writing to slave
slavechannel := make(chan []byte, channelBuffer)
defer close(slavechannel)
// channel for writing to master
masterchannel := make(chan []byte, channelBuffer)
defer close(masterchannel)
go slaveWriter(conn, slavechannel)
go masterConnection(slavechannel, masterchannel)
for {
command, err := readRedisCommand(reader)
if err != nil {
log.Printf("Error while reading from slave: %v\n", err)
return
}
if command.reply != "" || command.command == nil && command.bulkSize == 0 {
// passthrough reply & empty command
masterchannel <- command.raw
} else if len(command.command) == 1 && command.command[0] == "PING" {
log.Println("Got PING from slave")
masterchannel <- command.raw
} else if len(command.command) == 1 && command.command[0] == "SYNC" {
log.Println("Starting SYNC")
masterchannel <- command.raw
} else if len(command.command) == 3 && command.command[0] == "REPLCONF" && command.command[1] == "ACK" {
log.Println("Got ACK from slave")
masterchannel <- command.raw
} else {
// unknown command
slavechannel <- []byte("+ERR unknown command\r\n")
slavechannel <- nil
}
}
}
func main() {
flag.StringVar(&masterHost, "master-host", "localhost", "Master Redis host")
flag.IntVar(&masterPort, "master-port", 6379, "Master Redis port")
flag.StringVar(&proxyHost, "proxy-host", "", "Proxy listening interface, default is on all interfaces")
flag.IntVar(&proxyPort, "proxy-port", 6380, "Proxy port for listening")
flag.Parse()
if flag.NArg() != 1 {
flag.Usage()
fmt.Fprintln(os.Stderr, "Please specify regular expression to match against the Redis keys as the only argument.")
os.Exit(1)
}
var err error
keyRegexp, err = regexp.Compile(flag.Arg(0))
if err != nil {
fmt.Fprintf(os.Stderr, "Wrong format of regular expression: %v", err)
os.Exit(1)
}
log.Printf("Redis Resharding Proxy configured for Redis master at %s:%d\n", masterHost, masterPort)
log.Printf("Waiting for connection from slave at %s:%d\n", proxyHost, proxyPort)
// listen for incoming connection from Redis slave
ln, err := net.Listen("tcp", fmt.Sprintf("%s:%d", proxyHost, proxyPort))
if err != nil {
log.Fatalf("Unable to listen: %v\n", err)
}
for {
conn, err := ln.Accept()
if err != nil {
log.Printf("Unable to accept: %v\n", err)
continue
}
go slaveReader(conn)
}
}