-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpeer_replica.go
711 lines (600 loc) · 13.6 KB
/
peer_replica.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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
package prophet
import (
"context"
"errors"
"fmt"
"sync"
"time"
"github.com/fagongzi/util/task"
)
var (
// ErrNorLeader not leader
ErrNorLeader = errors.New("Not Leader")
// ErrDoTimeout timeout
ErrDoTimeout = errors.New("Do Timeout")
)
const (
cmdAddPeer = 1
cmdRemovePeer = 2
cmdScale = 3
cmdSend = 4
cmdHB = 5
cmdHBACK = 6
cmdRemove = 7
cmdBecomeLeader = 8
cmdBecomeFollower = 9
cmdTransferLeader = 10
cmdCustom = 11
)
type cmd struct {
cmdType int
cb func(interface{}, error)
data interface{}
}
func (c *cmd) complete(resp interface{}, err error) {
if c.cb != nil {
c.cb(resp, err)
}
}
func (c *cmd) reset() {
c.cmdType = 0
c.data = nil
c.cb = nil
}
var (
cmdPool sync.Pool
)
func acquireCMD() *cmd {
value := cmdPool.Get()
if value == nil {
return &cmd{}
}
return value.(*cmd)
}
func releaseCMD(value *cmd) {
value.reset()
cmdPool.Put(value)
}
// PeerReplicaHandler the interface to handle replica event message
type PeerReplicaHandler interface {
AddPeer(Resource, Peer)
RemovePeer(Resource, Peer) bool
Scale(Resource, interface{}) (bool, []*PeerReplica)
Heartbeat(Resource) bool
Destory(Resource)
ResourceBecomeLeader(Resource)
ResourceBecomeFollower(Resource)
}
// PeerReplica is the Resource peer replicatation.
// Every Resource has N replicatation in N stores.
type PeerReplica struct {
workerID uint64
tag string
leaderPeer uint64
peer Peer
meta Resource
store ResourceStore
localStore LocalStore
pendingPeers []Peer
tasks []uint64
heartbeatsMap *sync.Map // uint64 -> last hb time
handler PeerReplicaHandler
leader bool
elector Elector
cancel context.CancelFunc
cmds *task.RingBuffer
}
// CreatePeerReplica create a resource replica at current container
func CreatePeerReplica(store ResourceStore, meta Resource, handler PeerReplicaHandler, elector Elector) (*PeerReplica, error) {
peer, ok := FindPeer(meta.Peers(), store.Meta().ID())
if !ok {
return nil, fmt.Errorf("find no peer for store %d in resource %v",
store.Meta().ID(),
meta)
}
return NewPeerReplica(store, meta, peer, handler, elector), nil
}
// NewPeerReplica create a resource replica at current container
func NewPeerReplica(store ResourceStore, meta Resource, peer Peer, handler PeerReplicaHandler, elector Elector) *PeerReplica {
tag := fmt.Sprintf("[res-%d]:", meta.ID())
if peer.ID == 0 {
log.Fatalf("%s invalid peer id 0",
tag)
}
pr := new(PeerReplica)
pr.tag = tag
pr.meta = meta
pr.peer = peer
pr.store = store
pr.heartbeatsMap = &sync.Map{}
pr.elector = elector
pr.cmds = task.NewRingBuffer(1024) // TODO: configuration
pr.handler = handler
pr.startElector()
log.Infof("%s created with %+v",
pr.tag,
pr.meta)
return pr
}
// Tag returns the pr tag
func (pr *PeerReplica) Tag() string {
return pr.tag
}
// Peer returns the current peer of this resource
func (pr *PeerReplica) Peer() *Peer {
return &pr.peer
}
// Resource returns the meta
func (pr *PeerReplica) Resource() Resource {
return pr.meta
}
// Destroy destory the resource replica from current container
func (pr *PeerReplica) Destroy() {
pr.cmds.Dispose()
pr.cancel()
pr.elector.Stop(pr.meta.ID())
pr.handler.Destory(pr.meta)
}
// IsLeader returns the peer replica is the leader
func (pr *PeerReplica) IsLeader() bool {
return pr.leader
}
// AddPeer add a peer to this resource
func (pr *PeerReplica) AddPeer(peer Peer) {
c := acquireCMD()
c.cmdType = cmdAddPeer
c.data = peer
err := pr.cmds.Put(c)
if err != nil {
log.Fatalf("%s add peer event failed with %+v",
pr.tag,
err)
}
}
// RemovePeer remove peer
func (pr *PeerReplica) RemovePeer(peer Peer) {
c := acquireCMD()
c.cmdType = cmdRemovePeer
c.data = peer
err := pr.cmds.Put(c)
if err != nil {
log.Fatalf("%s remove peer event failed with %+v",
pr.tag,
err)
}
}
// Scale scale this pr
func (pr *PeerReplica) Scale(data interface{}) {
c := acquireCMD()
c.cmdType = cmdScale
c.data = data
err := pr.cmds.Put(c)
if err != nil {
log.Fatalf("%s scale event failed with %+v",
pr.tag,
err)
}
}
// CollectPendingPeers returns the pending peers
func (pr *PeerReplica) CollectPendingPeers() []*Peer {
var values []*Peer
for _, peer := range pr.pendingPeers {
p := peer
values = append(values, &p)
}
return values
}
// CollectDownPeers returns the down peers
func (pr *PeerReplica) CollectDownPeers(maxDuration time.Duration) []*PeerStats {
now := time.Now()
var downPeers []*PeerStats
for _, p := range pr.meta.Peers() {
if p.ID == pr.peer.ID {
continue
}
if last, ok := pr.heartbeatsMap.Load(p.ID); ok {
missing := now.Sub(last.(time.Time))
if missing >= maxDuration {
state := &PeerStats{}
state.Peer = p
state.DownSeconds = uint64(missing.Seconds())
downPeers = append(downPeers, state)
}
}
}
return downPeers
}
// Heartbeat send the hb to other peers
func (pr *PeerReplica) Heartbeat() {
c := acquireCMD()
c.cmdType = cmdSend
err := pr.cmds.Put(c)
if err != nil {
log.Fatalf("%s send hb to peers event failed with %+v",
pr.tag,
err)
}
}
// ChangeLeaderTo change leader to new leader
func (pr *PeerReplica) ChangeLeaderTo(leader uint64, cb func(interface{}, error)) {
if leader == pr.peer.ID {
if cb != nil {
cb(nil, nil)
}
return
}
c := acquireCMD()
c.cmdType = cmdTransferLeader
c.cb = cb
c.data = leader
err := pr.cmds.Put(c)
if err != nil {
log.Fatalf("%s change leader to %d event failed with %+v",
pr.tag,
leader,
err)
}
}
// Do do something async
func (pr *PeerReplica) Do(doFunc func(error), timeout time.Duration) {
completeC := make(chan struct{})
c := acquireCMD()
c.cmdType = cmdCustom
c.data = doFunc
c.cb = func(data interface{}, err error) {
completeC <- struct{}{}
}
err := pr.cmds.Put(c)
if err != nil {
close(completeC)
doFunc(err)
releaseCMD(c)
return
}
select {
case <-completeC:
close(completeC)
case <-time.After(timeout):
close(completeC)
doFunc(ErrDoTimeout)
}
}
func (pr *PeerReplica) startElector() {
ctx, cancel := context.WithCancel(context.Background())
pr.cancel = cancel
go pr.elector.ElectionLoop(ctx, pr.meta.ID(), fmt.Sprintf("peer-%d", pr.peer.ID), pr.becomeLeader, pr.becomeFollower)
}
func (pr *PeerReplica) becomeLeader() {
c := acquireCMD()
c.cmdType = cmdBecomeLeader
err := pr.cmds.Put(c)
if err != nil {
log.Fatalf("%s add become leader event failed with %+v",
pr.tag,
err)
}
}
func (pr *PeerReplica) becomeFollower() {
completeC := make(chan struct{})
c := acquireCMD()
c.cmdType = cmdBecomeFollower
c.cb = func(data interface{}, err error) {
completeC <- struct{}{}
}
err := pr.cmds.Put(c)
if err != nil {
log.Warningf("%s add become follower event failed with %+v",
pr.tag,
err)
c.cb(nil, nil)
}
select {
case <-completeC:
close(completeC)
return
case <-time.After(time.Minute):
if !pr.cmds.IsDisposed() {
log.Fatalf("%s become follower event handle timeout",
pr.tag)
}
}
close(completeC)
}
func (pr *PeerReplica) onHB(msg *hbMsg) interface{} {
completeC := make(chan interface{})
c := acquireCMD()
c.cmdType = cmdHB
c.data = msg.res
c.cb = func(data interface{}, err error) {
completeC <- data
}
err := pr.cmds.Put(c)
if err != nil {
log.Fatalf("%s add heartbeat event failed with %+v",
pr.tag,
err)
}
select {
case rsp := <-completeC:
close(completeC)
return rsp
case <-time.After(time.Minute):
if !pr.cmds.IsDisposed() {
log.Fatalf("%s add heartbeat event handle timeout",
pr.tag)
}
}
close(completeC)
return nil
}
func (pr *PeerReplica) onHBACK(msg *hbACKMsg) interface{} {
completeC := make(chan interface{})
c := acquireCMD()
c.cmdType = cmdHBACK
c.data = msg
c.cb = func(data interface{}, err error) {
completeC <- data
}
err := pr.cmds.Put(c)
if err != nil {
log.Fatalf("%s add heartbeat ack event failed with %+v",
pr.tag,
err)
}
select {
case rsp := <-completeC:
close(completeC)
return rsp
case <-time.After(time.Minute):
if !pr.cmds.IsDisposed() {
log.Fatalf("%s add heartbeat ack event handle timeout",
pr.tag)
}
}
close(completeC)
return nil
}
func (pr *PeerReplica) onRemove(msg *removeMsg) interface{} {
completeC := make(chan interface{})
c := acquireCMD()
c.cmdType = cmdRemove
c.data = msg
c.cb = func(data interface{}, err error) {
completeC <- data
}
err := pr.cmds.Put(c)
if err != nil {
log.Fatalf("%s add remove event failed with %+v",
pr.tag,
err)
}
select {
case rsp := <-completeC:
close(completeC)
return rsp
case <-time.After(time.Minute):
log.Fatalf("%s add remove ack event handle timeout",
pr.tag)
}
return nil
}
func (pr *PeerReplica) handleEvent() bool {
if pr.cmds.Len() == 0 && !pr.cmds.IsDisposed() {
return false
}
data, err := pr.cmds.Get()
if err != nil {
return false
}
c := data.(*cmd)
if c.cmdType == cmdSend {
pr.handleSendHB(c)
} else if c.cmdType == cmdHB {
pr.handleHB(c)
} else if c.cmdType == cmdHBACK {
pr.handleHBACK(c)
} else if c.cmdType == cmdRemove {
pr.handleRemove(c)
} else if c.cmdType == cmdAddPeer {
pr.handleAddPeer(c)
} else if c.cmdType == cmdScale {
pr.handleScale(c)
} else if c.cmdType == cmdRemovePeer {
pr.handleRemovePeer(c)
} else if c.cmdType == cmdBecomeLeader {
pr.handleBecomeLeader(c)
} else if c.cmdType == cmdBecomeFollower {
pr.handleBecomeFollower(c)
} else if c.cmdType == cmdTransferLeader {
pr.handleTransferLeader(c)
} else if c.cmdType == cmdCustom {
c.data.(func(error))(nil)
c.complete(nil, nil)
} else {
log.Fatalf("%s handle unknown cmd type %d, %+v",
pr.tag,
c.cmdType,
c)
}
releaseCMD(c)
return true
}
func (pr *PeerReplica) handleRemovePeer(c *cmd) {
peer := c.data.(Peer)
if pr.store.Meta().ID() == peer.ContainerID {
pr.handleRemove(c)
return
}
if pr.handler.RemovePeer(pr.meta, peer) {
pr.heartbeatsMap.Delete(peer.ID)
}
pr.store.LocalStore().MustPutResource(pr.meta)
pr.store.GetTransport().Send(peer.ContainerID, &removeMsg{
id: pr.meta.ID(),
})
log.Infof("%s peer %+v removed, after removed value %+v",
pr.tag,
peer,
pr.meta)
}
func (pr *PeerReplica) handleAddPeer(c *cmd) {
if !pr.leader {
return
}
peer := c.data.(Peer)
_, ok := FindPeer(pr.meta.Peers(), peer.ContainerID)
if ok {
return
}
pr.handler.AddPeer(pr.meta, peer)
pr.heartbeatsMap.Store(peer.ID, time.Now())
pr.pendingPeers = append(pr.pendingPeers, peer)
pr.store.LocalStore().MustPutResource(pr.meta)
log.Infof("%s new peer %+v added, after added value %+v",
pr.tag,
peer,
pr.meta)
}
func (pr *PeerReplica) handleScale(c *cmd) {
if !pr.leader {
return
}
log.Infof("%s handle scale by %+v",
pr.tag,
c.data)
changed, newPRs := pr.handler.Scale(pr.meta, c.data)
if len(newPRs) == 0 {
if changed {
pr.store.LocalStore().MustPutResource(pr.meta)
}
return
}
var saved []Resource
saved = append(saved, pr.meta)
for _, p := range newPRs {
saved = append(saved, p.meta)
}
pr.store.LocalStore().MustPutResource(saved...)
for _, p := range newPRs {
pr.store.AddReplica(p)
}
log.Infof("%s after scale %+v, create %d new resources",
pr.tag,
pr.meta,
len(newPRs))
}
func (pr *PeerReplica) handleSendHB(c *cmd) {
if !pr.leader {
return
}
for _, p := range pr.meta.Peers() {
if p.ContainerID != pr.store.Meta().ID() {
pr.store.GetTransport().Send(p.ContainerID, &hbMsg{
res: pr.meta.Clone(),
})
}
}
}
func (pr *PeerReplica) handleHB(c *cmd) {
res := c.data.(Resource)
// remote resource is stale, remove it
if pr.meta.Stale(res) {
log.Infof("%s remote res %+v is stale, current is %+v, remove it on handle hb",
pr.tag,
res,
pr.meta)
c.complete(&removeMsg{
id: pr.meta.ID(),
}, nil)
return
}
if pr.handler.Heartbeat(res) {
pr.store.LocalStore().MustPutResource(pr.meta)
log.Infof("%s updated to %+v",
pr.tag,
pr.meta)
}
c.complete(&hbACKMsg{
res: pr.meta.Clone(),
peer: pr.peer,
}, nil)
}
func (pr *PeerReplica) handleHBACK(c *cmd) {
msg := c.data.(*hbACKMsg)
// stale current peer, remove
if msg.res.Stale(pr.meta) {
log.Infof("%s current res %+v is stale, remove current",
pr.tag,
pr.meta)
pr.handleRemove(c)
return
}
pr.removePendingPeer(msg.peer)
pr.heartbeatsMap.Store(msg.peer.ID, time.Now())
c.complete(nil, nil)
}
func (pr *PeerReplica) handleRemove(c *cmd) {
pr.store.RemoveReplica(pr.meta.ID())
pr.Destroy()
c.complete(nil, nil)
log.Infof("%s destroy complete by remove",
pr.tag)
}
func (pr *PeerReplica) handleBecomeLeader(c *cmd) {
if pr.leader {
return
}
log.Infof("%s ********become leader now********",
pr.tag)
pr.leader = true
pr.handler.ResourceBecomeLeader(pr.meta)
}
func (pr *PeerReplica) handleBecomeFollower(c *cmd) {
if !pr.leader {
c.complete(nil, nil)
return
}
pr.leader = false
pr.handler.ResourceBecomeFollower(pr.meta)
c.complete(nil, nil)
log.Infof("%s ********become follower now********",
pr.tag)
}
func (pr *PeerReplica) handleTransferLeader(c *cmd) {
leader := c.data.(uint64)
log.Infof("%s my id is %d, transfer leader to peer %d",
pr.tag,
pr.peer.ID,
leader)
if !pr.leader {
c.complete(nil, ErrNorLeader)
return
}
if leader == pr.peer.ID {
c.complete(nil, nil)
return
}
err := pr.elector.ChangeLeaderTo(pr.meta.ID(),
fmt.Sprintf("peer-%d", pr.peer.ID),
fmt.Sprintf("peer-%d", leader))
if err != nil {
log.Errorf("%s transfer leader to peer %d failed with %+v",
pr.tag,
leader,
err)
c.complete(nil, err)
return
}
c.cb = nil
pr.leaderPeer = leader
pr.handleBecomeFollower(c)
}
func (pr *PeerReplica) removePendingPeer(peer Peer) {
var values []Peer
for _, p := range pr.pendingPeers {
if p.ID != peer.ID {
values = append(values, p)
}
}
pr.pendingPeers = values
}