-
Notifications
You must be signed in to change notification settings - Fork 0
/
cluster.go
377 lines (344 loc) · 9.03 KB
/
cluster.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
package xcache
import (
"context"
"fmt"
"net"
"sync"
"time"
"go.uber.org/zap"
"xcache/protocol"
)
type ClusterEvent interface {
OnFail(node *protocol.Node)
OnPFail(node *protocol.Node)
OnActive(node *protocol.Node)
}
var (
pingTimeout = time.Second * 15
dialTimeout = time.Second * 3
)
type pendingPing struct {
conn *connection
expire time.Time
ctime time.Time
}
func newCluster(ctx context.Context, id uint64, addr string, handler RequestHandler) *cluster {
cl := &cluster{
ctx: ctx,
myself: &protocol.Node{
Addr: addr,
Id: id,
},
nodes: make(map[uint64]*protocol.Node),
node2conn: make(map[uint64]*connection),
conn2node: make(map[*connection]*protocol.Node),
pendingPings: make(map[uint64]*pendingPing),
pfails: make(map[uint64]map[uint64]struct{}),
handler: handler,
}
// 把自己节点加入到nodes中
cl.nodes[cl.myself.Id] = cl.myself
return cl
}
type cluster struct {
rw sync.RWMutex
ctx context.Context
myself *protocol.Node
nodes map[uint64]*protocol.Node // nodes
node2conn map[uint64]*connection // node-client
conn2node map[*connection]*protocol.Node // client-node
pendingPings map[uint64]*pendingPing
pfails map[uint64]map[uint64]struct{} // 可能下线的节点投票记录
handler RequestHandler
}
func (cl *cluster) Myself() *protocol.Node {
return cl.myself
}
func (cl *cluster) Join(target *protocol.Node) error {
cl.rw.RLock()
if _, ok := cl.nodes[target.Id]; ok {
cl.rw.RUnlock()
return fmt.Errorf("join target id: %d already exists", target.Id)
}
cl.rw.RUnlock()
node := &protocol.Node{
Addr: target.Addr,
Id: target.Id,
}
cc, err := net.DialTimeout("tcp", node.Addr, dialTimeout)
if err != nil {
return err
}
cl.rw.Lock()
defer cl.rw.Unlock()
client := &connection{
Conn: cc,
handler: cl.handler,
side: SideClient,
}
cl.nodes[node.Id] = node
cl.node2conn[node.Id] = client
cl.conn2node[client] = node
go client.serve(cl.ctx)
reqId := genId()
data := client.encode(&Frame{
ReqId: reqId,
Cmd: protocol.CMDType_TPing,
Message: &protocol.Ping{
Nodes: []*protocol.Node{cl.myself},
Self: cl.myself,
},
})
_, err = client.Write(data)
if err != nil {
return err
}
now := time.Now()
expire := now.Add(pingTimeout)
cl.pendingPings[reqId] = &pendingPing{
conn: client,
expire: expire,
ctime: now,
}
return nil
}
func (cl *cluster) Len() int {
cl.rw.RLock()
defer cl.rw.RUnlock()
l := 0
for _, n := range cl.nodes {
if n.State < protocol.NodeState_NSPFail {
l++
}
}
return l
}
func (cl *cluster) Nodes() []*protocol.Node {
cl.rw.RLock()
defer cl.rw.RUnlock()
nodes := make([]*protocol.Node, 0, len(cl.nodes))
for _, n := range cl.nodes {
if n.State < protocol.NodeState_NSFail {
nodes = append(nodes, n)
}
}
return nodes
}
func (cl *cluster) HandleDisconnected(conn *connection, err error) {
cl.rw.Lock()
defer cl.rw.Unlock()
if log.Level().Enabled(zap.DebugLevel) {
log.Debugf("cluster handle error myself id: %d addr: %s local-addr: %s remote-addr: %s, side: %d, err: %v",
cl.myself.Id,
cl.myself.Addr,
conn.LocalAddr(),
conn.RemoteAddr(),
conn.Side(),
err)
}
// 删除连接
node, ok := cl.conn2node[conn]
if ok {
delete(cl.conn2node, conn)
delete(cl.node2conn, node.Id)
// 更新节点信息成PFail
if node.State < protocol.NodeState_NSPFail {
node.State = protocol.NodeState_NSPFail
cl.pfails[node.Id] = make(map[uint64]struct{})
cl.pfails[node.Id][cl.myself.Id] = struct{}{}
cl.OnPFail(node)
}
}
}
func (cl *cluster) HandlePing(conn *connection, msg *protocol.Ping) *protocol.Pong {
// server端收到ping包, 然后响应pong包
cl.rw.Lock()
defer cl.rw.Unlock()
sender := cl.conn2node[conn]
cl.processNodes(sender, msg.Nodes)
// 向ping的目标节点写回pong消息
// 在当前节点集群中随机出3个节点响应到pong中
nodes := cl.randNodes(3, msg.Self.Id)
return &protocol.Pong{Nodes: nodes}
}
func (cl *cluster) HandlePong(conn *connection, reqId uint64, msg *protocol.Pong) {
// client端接收到pong包, 删除等待pong包的request id
// 对当前节点不存在的集群节点发起连接
cl.rw.Lock()
defer cl.rw.Unlock()
delete(cl.pendingPings, reqId)
sender := cl.conn2node[conn]
cl.processNodes(sender, msg.Nodes)
}
func (cl *cluster) OnActive(node *protocol.Node) {
if log.Level().Enabled(zap.DebugLevel) {
log.Debugf("OnActive myself id: %d addr: %s node: %d addr: %s",
cl.myself.Id,
cl.myself.Addr,
node.Id,
node.Addr)
}
}
func (cl *cluster) OnFail(node *protocol.Node) {
if log.Level().Enabled(zap.DebugLevel) {
log.Debugf("OnFail myself id: %d addr: %s node: %d addr: %s",
cl.myself.Id,
cl.myself.Addr,
node.Id,
node.Addr)
}
}
func (cl *cluster) OnPFail(node *protocol.Node) {
if log.Level().Enabled(zap.DebugLevel) {
log.Debugf("OnPFail myself id: %d addr: %s node: %d addr: %s",
cl.myself.Id,
cl.myself.Addr,
node.Id,
node.Addr)
}
}
// processNodes 处理响应的nodes, 如果当前集群中不存在就发起连接
func (cl *cluster) processNodes(sender *protocol.Node, nodes []*protocol.Node) {
for _, node := range nodes {
if nd, ok := cl.nodes[node.Id]; ok {
// 更新节点信息
if sender != nil && node.State >= protocol.NodeState_NSPFail {
if pfail, ok := cl.pfails[node.Id]; ok {
// 如果sender节点跟当前节点都认为node已经PFail, 就给他投票
pfail[sender.Id] = struct{}{}
if len(cl.pfails[node.Id]) >= (len(cl.nodes)/2 + 1) {
// 如果超过半数, 都认为这个节点下线了, 那么就把节点状态从PFail -> Fail
nd.State = protocol.NodeState_NSFail
// 移除PFail的队列
delete(cl.pfails, node.Id)
if log.Level().Enabled(zap.DebugLevel) {
log.Debugf("node state change to Fail id: %d addr: %s", nd.Id, nd.Addr)
}
// 通知变成Fail
// TODO: 并且进行主从切换
cl.OnFail(nd)
}
}
}
continue
}
// 新的集群节点
cl.nodes[node.Id] = node
if node.State < protocol.NodeState_NSPFail {
// 新的节点, 并且不是PFail, Fail节点, 建立client去连接对端节点
cc, err := net.DialTimeout("tcp", node.Addr, dialTimeout)
if err != nil {
log.Errorf("node: %d addr: %s dial err: %v", node.Id, node.Addr, err)
continue
}
// 保存连接节点之间的对应关系
client := &connection{Conn: cc, handler: cl.handler, side: SideClient}
cl.node2conn[node.Id] = client
cl.conn2node[client] = node
node.State = protocol.NodeState_NSActive
cl.OnActive(node)
go client.serve(cl.ctx)
}
}
}
func (cl *cluster) randNodes(limit int, filters ...uint64) []*protocol.Node {
nodes := make([]*protocol.Node, 0, limit)
for _, node := range cl.nodes {
if cl.contains(node.Id, filters) {
continue
}
nodes = append(nodes, node)
}
return nodes
}
func (cl *cluster) contains(id uint64, ids []uint64) bool {
for _, v := range ids {
if v == id {
return true
}
}
return false
}
func (cl *cluster) workLoop() {
after := time.After(time.Second)
for {
select {
case <-cl.ctx.Done():
return
case <-after:
cl.processPending()
cl.processPing()
after = time.After(time.Second)
}
}
}
func (cl *cluster) processPending() {
cl.rw.Lock()
defer cl.rw.Unlock()
now := time.Now()
for reqId, pending := range cl.pendingPings {
if now.After(pending.expire) {
if log.Level().Enabled(zap.DebugLevel) {
log.Debugf("ping timeout reqId: %d myself: %s local-addr: %s remote-addr: %s",
reqId,
cl.myself.Addr,
pending.conn.LocalAddr(),
pending.conn.RemoteAddr(),
)
}
delete(cl.pendingPings, reqId)
_ = pending.conn.Close()
}
}
}
func (cl *cluster) processPing() {
cl.rw.Lock()
defer cl.rw.Unlock()
nodes := cl.randNodes(3, cl.myself.Id)
now := time.Now()
expire := now.Add(pingTimeout)
for _, node := range nodes {
pingNodes := cl.randNodes(3, node.Id)
conn := cl.node2conn[node.Id]
if conn != nil {
reqId := genId()
data := conn.encode(&Frame{
ReqId: reqId,
Cmd: protocol.CMDType_TPing,
Message: &protocol.Ping{
Nodes: pingNodes,
Self: cl.myself,
},
})
_, err := conn.Write(data)
if err != nil {
log.Errorf("process ping failed, myself id: %d addr: %s conn write err: %v", cl.myself.Id, cl.myself.Addr, err)
_ = conn.Close()
continue
}
cl.pendingPings[reqId] = &pendingPing{
conn: conn,
expire: expire,
ctime: now,
}
} else {
// 没有建立连接的, 需要尝试进行连接
cc, err := net.DialTimeout("tcp", node.Addr, dialTimeout)
if err != nil {
log.Errorf("process ping dial node id: %d addr: %s err: %v", node.Id, node.Addr, err)
continue
}
// 成功建立连接
client := &connection{Conn: cc, handler: cl.handler, side: SideClient}
// 加入连接中
cl.node2conn[node.Id] = client
cl.conn2node[client] = node
node.State = protocol.NodeState_NSActive
go client.serve(cl.ctx)
// 如果在PFail队列中需要移除了
delete(cl.pfails, node.Id)
// fire OnActive
cl.OnActive(node)
}
}
}