-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathredis_proto.go
287 lines (261 loc) · 6.29 KB
/
redis_proto.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
package sentinel
import (
"bufio"
"context"
"errors"
"fmt"
"io"
"net"
"strconv"
"time"
"github.com/go-redis/redis/v8"
"github.com/tidwall/redcon"
)
func (s *Sentinel) getCurrentEpoch() int {
s.mu.Lock()
defer s.mu.Unlock()
return s.currentEpoch
}
func (s *Sentinel) updateEpochIfNeeded(newEpoch int) {
s.mu.Lock()
defer s.mu.Unlock()
if newEpoch > s.currentEpoch {
s.currentEpoch = newEpoch
}
}
func (s *Sentinel) selfID() string {
return s.runID
}
func (s *Sentinel) voteLeader(m *masterInstance, reqEpoch int, reqRunID string) (leaderEpoch int, leaderID string) {
s.updateEpochIfNeeded(reqEpoch)
selfID := s.selfID()
m.mu.Lock()
defer m.mu.Unlock()
var voteGranted bool
if m.leaderEpoch < reqEpoch {
m.leaderID = reqRunID
m.leaderEpoch = reqEpoch
// failover start at some other sentinel that we have just voted for
if m.leaderID != selfID {
m.failOverStartTime = time.Now()
}
voteGranted = true
}
leaderEpoch = m.leaderEpoch
leaderID = m.leaderID
if voteGranted {
s.logger.Debugw(logEventVotedFor,
"voted_for", leaderID,
"epoch", leaderEpoch,
)
}
return
}
func (s *Sentinel) IsMasterDownByAddr(req *IsMasterDownByAddrArgs, reply *IsMasterDownByAddrReply) error {
addr := fmt.Sprintf("%s:%s", req.IP, req.Port)
s.mu.Lock()
master, exist := s.masterInstances[addr]
s.mu.Unlock()
if !exist {
err := fmt.Errorf("master %s with addr %s does not exist or has been deleted", req.Name, addr)
s.logger.Errorf(err.Error())
return err
}
reply.MasterDown = master.getState() >= masterStateSubjDown
if req.SelfID != "" {
leaderEpoch, leaderID := s.voteLeader(master, req.CurrentEpoch, req.SelfID)
reply.LeaderEpoch = leaderEpoch
reply.VotedLeaderID = leaderID
} else {
// return its current known leader anyway
master.mu.Lock()
reply.LeaderEpoch = master.leaderEpoch
reply.VotedLeaderID = master.leaderID
master.mu.Unlock()
}
return nil
}
func (s *Sentinel) serveTCP() {
l, err := net.Listen("tcp", fmt.Sprintf(":%s", s.conf.Port))
if err != nil {
panic(err)
}
locked(s.protoMutex, func() {
s.listener = l
})
for {
//TODO check if listener is closed
conn, err := l.Accept()
if err != nil {
var shutdown bool
locked(s.protoMutex, func() {
shutdown = s.tcpDone
})
if !shutdown {
s.logger.Errorf("accepting connection: %s", err)
continue
}
return
}
go s.handleTCPConn(conn)
}
}
func (s *Sentinel) handleTCPConn(conn net.Conn) {
r := redcon.NewReader(conn)
w := redcon.NewWriter(conn)
for {
cmd, err := r.ReadCommand()
if err != nil {
if errors.Is(err, io.EOF) {
conn.Close()
return
}
}
err = s.processCmd(cmd, w)
if err != nil {
w.WriteError(err.Error())
}
err = w.Flush()
if err != nil {
s.logger.Errorf("flushing input error: %s", err)
}
// w.WriteError(err)
// err = writeRedisOutput(output, w)
// if err != nil {
// s.logger.Errorf("writing output to connection %s", err)
// }
}
}
func writeRedisOutput(output string, w *bufio.Writer) error {
written, err := w.WriteString(fmt.Sprintf("%s\n", output))
if written != len(output)+1 {
return err
}
return w.Flush()
}
func writeRedisErr(errstr string, w *bufio.Writer) error {
len, err := w.WriteString(fmt.Sprintf("-ERR %s\n", errstr))
if len != 5 {
return err
}
return w.Flush()
}
func (s *Sentinel) processCmd(cmd redcon.Command, w *redcon.Writer) error {
parts := cmd.Args
if len(parts) == 0 {
return fmt.Errorf("invalid input")
}
if string(parts[0]) != "sentinel" {
return fmt.Errorf("only sentinel command supported")
}
if len(parts) < 2 {
return fmt.Errorf("require atleast 2 arguments")
}
switch string(parts[1]) {
case "get-master-addr-by-name":
if len(parts) < 3 {
return fmt.Errorf("missing master name")
}
lines, err := s.tcpGetMasterAddrByname(string(parts[2]))
if err != nil {
return err
}
w.WriteArray(len(lines))
for _, item := range lines {
w.WriteBulkString(item)
}
return nil
case "is-master-down-by-addr":
if len(parts[2:]) != 5 {
return fmt.Errorf("is-master-down-by-addr require 5 args")
}
lines, err := s.tcpIsMasterDownByAddr(parts[2:])
if err != nil {
return err
}
w.WriteArray(len(lines))
for _, item := range lines {
w.WriteBulkString(item)
}
return nil
default:
return fmt.Errorf("unknown command %s", string(parts[1]))
}
}
// used internal only, Redis does not have this
func (s *Sentinel) tcpIsMasterDownByAddr(args [][]byte) ([]string, error) {
req := IsMasterDownByAddrArgs{}
err := req.decode(args)
if err != nil {
return nil, err
}
var reply IsMasterDownByAddrReply
err = s.IsMasterDownByAddr(&req, &reply)
if err != nil {
return nil, err
}
return reply.toLines(), nil
}
// Should be understood by redis client
func (s *Sentinel) tcpGetMasterAddrByname(name string) ([]string, error) {
s.mu.Lock()
temp := make([]*masterInstance, 0, len(s.masterInstances))
for addr := range s.masterInstances {
temp = append(temp, s.masterInstances[addr])
}
s.mu.Unlock()
var (
host string
port string
found bool
)
for idx := range temp {
curMaster := temp[idx]
locked(&curMaster.mu, func() {
if curMaster.name == name {
host = curMaster.host
port = curMaster.port
found = true
}
})
if found {
break
}
}
if !found {
return nil, fmt.Errorf("not found master")
}
return []string{host, port}, nil
}
type redisProtoInternalClient struct {
cl *redis.SentinelClient
}
// TODO
func NewRedisProtoInternalClient(host string, port string) (*redisProtoInternalClient, error) {
cl := redis.NewSentinelClient(&redis.Options{
Addr: fmt.Sprintf("%s:%s", host, port),
PoolSize: 2,
})
return &redisProtoInternalClient{
cl: cl,
}, nil
}
func (c *redisProtoInternalClient) IsMasterDownByAddr(req IsMasterDownByAddrArgs) (IsMasterDownByAddrReply, error) {
var ret IsMasterDownByAddrReply
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
cmd := redis.NewStringSliceCmd(ctx, "sentinel", "is-master-down-by-addr", req.Name, req.IP, req.Port, strconv.Itoa(req.CurrentEpoch), req.SelfID)
_ = c.cl.Process(ctx, cmd)
parts, err := cmd.Result()
if err != nil {
return ret, err
}
if len(parts) == 0 {
return ret, fmt.Errorf("protocol error: %v", parts)
}
err = ret.decode(parts)
if err != nil {
return ret, fmt.Errorf("protocol error: %s", err)
}
return ret, nil
}