forked from absolute8511/ZanRedisDB
/
raft.go
1448 lines (1355 loc) · 42.8 KB
/
raft.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
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2015 The etcd Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package node
import (
"errors"
"fmt"
"io"
"os"
"runtime"
"sort"
"strconv"
"sync"
"time"
"encoding/json"
"sync/atomic"
ps "github.com/prometheus/client_golang/prometheus"
"github.com/youzan/ZanRedisDB/common"
"github.com/youzan/ZanRedisDB/metric"
"github.com/youzan/ZanRedisDB/pkg/fileutil"
"github.com/youzan/ZanRedisDB/pkg/idutil"
"github.com/youzan/ZanRedisDB/pkg/types"
"github.com/youzan/ZanRedisDB/raft"
"github.com/youzan/ZanRedisDB/raft/raftpb"
"github.com/youzan/ZanRedisDB/settings"
"github.com/youzan/ZanRedisDB/snap"
"github.com/youzan/ZanRedisDB/transport/rafthttp"
"github.com/youzan/ZanRedisDB/wal"
"github.com/youzan/ZanRedisDB/wal/walpb"
"golang.org/x/net/context"
)
var (
// DefaultSnapCount is the count for trigger snapshot
DefaultSnapCount = int(settings.Soft.DefaultSnapCount)
// HealthInterval is the minimum time the cluster should be healthy
// before accepting add member requests.
HealthInterval = time.Duration(settings.Soft.HealthIntervalSec) * time.Second
// max number of in-flight snapshot messages allows to have
maxInFlightMsgSnap = int(settings.Soft.MaxInFlightMsgSnap)
maxInflightMsgs = settings.Soft.MaxInflightMsgs
)
const (
releaseDelayAfterSnapshot = 30 * time.Second
)
var errWALMetaMismatch = errors.New("wal meta mismatch config (maybe reused old deleted data)")
type Snapshot interface {
GetData() ([]byte, error)
}
type IRaftPersistStorage interface {
// Save function saves ents and state to the underlying stable storage.
// Save MUST block until st and ents are on stable storage.
Save(st raftpb.HardState, ents []raftpb.Entry) error
// SaveSnap function saves snapshot to the underlying stable storage.
SaveSnap(snap raftpb.Snapshot) error
Load() (*raftpb.Snapshot, error)
LoadNewestAvailable(walSnaps []walpb.Snapshot) (*raftpb.Snapshot, error)
// Close closes the Storage and performs finalization.
Close() error
// Release releases the locked wal files older than the provided snapshot.
Release(snap raftpb.Snapshot) error
// Sync WAL
Sync() error
}
type DataStorage interface {
CleanData() error
RestoreFromSnapshot(raftpb.Snapshot) error
PrepareSnapshot(raftpb.Snapshot) error
GetSnapshot(term uint64, index uint64) (Snapshot, error)
UpdateSnapshotState(term uint64, index uint64)
Stop()
}
type applyInfo struct {
ents []raftpb.Entry
snapshot raftpb.Snapshot
applySnapshotResult chan error
raftDone chan struct{}
applyWaitDone chan struct{}
}
// A key-value stream backed by raft
type raftNode struct {
commitC chan<- applyInfo // entries committed to log (k,v)
config *RaftConfig
memMutex sync.Mutex
members map[uint64]*common.MemberInfo
learnerMems map[uint64]*common.MemberInfo
join bool // node is joining an existing cluster
lastIndex uint64 // index of log at start
lead uint64
// raft backing for the commit/error channel
node raft.Node
raftStorage raft.IExtRaftStorage
wal *wal.WAL
persistStorage IRaftPersistStorage
transport rafthttp.Transporter
stopc chan struct{} // signals proposal channel closed
reqIDGen *idutil.Generator
wgAsync sync.WaitGroup
wgServe sync.WaitGroup
ds DataStorage
msgSnapC chan raftpb.Message
inflightSnapshots int64
description string
readStateC chan raft.ReadState
memberCnt int32
newLeaderChan chan string
lastLeaderChangedTs int64
stopping int32
replayRunning int32
busySnapshot int32
loopServering int32
lastPublished uint64
slowLimiter *SlowLimiter
}
// newRaftNode initiates a raft instance and returns a committed log entry
// channel and error channel. Proposals for log updates are sent over the
// provided the proposal channel. All log entries are replayed over the
// commit channel, followed by a nil message (to indicate the channel is
// current), then new log entries.
func newRaftNode(rconfig *RaftConfig, transport *rafthttp.Transport,
join bool, ds DataStorage, rs raft.IExtRaftStorage, newLeaderChan chan string) (<-chan applyInfo, *raftNode, error) {
commitC := make(chan applyInfo, settings.Soft.CommitBufferLen)
if rconfig.SnapCount <= 0 {
rconfig.SnapCount = DefaultSnapCount
}
if rconfig.SnapCatchup <= 0 {
rconfig.SnapCatchup = rconfig.SnapCount / 2
}
rc := &raftNode{
commitC: commitC,
config: rconfig,
members: make(map[uint64]*common.MemberInfo),
learnerMems: make(map[uint64]*common.MemberInfo),
join: join,
raftStorage: rs,
stopc: make(chan struct{}),
ds: ds,
reqIDGen: idutil.NewGenerator(uint16(rconfig.ID), time.Now()),
msgSnapC: make(chan raftpb.Message, maxInFlightMsgSnap),
transport: transport,
readStateC: make(chan raft.ReadState, 3),
newLeaderChan: newLeaderChan,
}
snapDir := rc.config.SnapDir
if !fileutil.Exist(snapDir) {
if err := os.MkdirAll(snapDir, common.DIR_PERM); err != nil {
nodeLog.Errorf("cannot create dir for snapshot (%v)", err)
return nil, nil, err
}
}
rc.persistStorage = NewRaftPersistStorage(nil, snap.New(snapDir))
rc.description = rc.config.GroupName + "-" + strconv.Itoa(int(rc.config.ID))
return commitC, rc, nil
}
// openWAL returns a WAL ready for reading.
func (rc *raftNode) openWAL(snapshot *raftpb.Snapshot, readOld bool) (*wal.WAL, []byte, raftpb.HardState, []raftpb.Entry, error) {
var hardState raftpb.HardState
if !wal.Exist(rc.config.WALDir) {
if err := os.MkdirAll(rc.config.WALDir, common.DIR_PERM); err != nil {
rc.Errorf("cannot create dir for wal (%v)", err)
return nil, nil, hardState, nil, err
}
var m common.MemberInfo
m.ID = uint64(rc.config.ID)
m.GroupName = rc.config.GroupName
m.GroupID = rc.config.GroupID
d, _ := json.Marshal(m)
w, err := wal.Create(rc.config.WALDir, d, rc.config.OptimizedFsync)
if err != nil {
rc.Errorf("create wal error (%v)", err)
}
return w, d, hardState, nil, err
}
var walsnap walpb.Snapshot
if snapshot != nil {
walsnap.Index, walsnap.Term = snapshot.Metadata.Index, snapshot.Metadata.Term
}
repaired := false
var err error
var w *wal.WAL
for {
w, err = wal.Open(rc.config.WALDir, walsnap, rc.config.OptimizedFsync)
if err != nil {
rc.Errorf("error loading wal (%v)", err)
return w, nil, hardState, nil, err
}
if readOld {
meta, st, ents, err := w.ReadAll()
if err != nil {
w.Close()
rc.Errorf("failed to read WAL (%s)", err)
if repaired {
rc.Errorf("read wal error and cannot be repaire")
} else {
if !wal.Repair(rc.config.WALDir) {
rc.Errorf("read wal error and cannot be repaire")
} else {
rc.Infof("wal repaired")
repaired = true
continue
}
}
}
return w, meta, st, ents, err
} else {
break
}
}
return w, nil, hardState, nil, err
}
func (rc *raftNode) replayWALForSyncLearner(snapshot *raftpb.Snapshot) error {
// TODO: for sync learner, we do not need replay any logs before the remote synced term-index
// and also, to avoid snapshot from leader while new sync learner started, we can get the remote
// cluster the newest synced term-index, and add faked to wal with that term-index. In this way we can force the leader
// to send just logs after term-index.
return nil
}
// replayWAL replays WAL entries into the raft instance.
func (rc *raftNode) replayWAL(snapshot *raftpb.Snapshot, forceStandalone bool) error {
w, meta, st, ents, err := rc.openWAL(snapshot, true)
if err != nil {
return err
}
rc.Infof("wal meta: %v, restart with: %v, ents: %v", string(meta), st.String(), len(ents))
var m common.MemberInfo
err = json.Unmarshal(meta, &m)
if err != nil {
w.Close()
rc.Errorf("meta is wrong: %v", err)
return err
}
if m.ID != uint64(rc.config.ID) ||
m.GroupID != rc.config.GroupID {
w.Close()
rc.Errorf("meta starting mismatch config: %v, %v", m, rc.config)
return errWALMetaMismatch
}
if rs, ok := rc.persistStorage.(*raftPersistStorage); ok {
rs.WAL = w
}
if forceStandalone {
// discard the previously uncommitted entries
for i, ent := range ents {
if ent.Index > st.Commit {
rc.Infof("discarding %d uncommitted WAL entries ", len(ents)-i)
ents = ents[:i]
break
}
}
ids, grps := getIDsAndGroups(snapshot, ents)
m := common.MemberInfo{
ID: rc.config.ID,
NodeID: rc.config.nodeConfig.NodeID,
GroupName: rc.config.GroupName,
GroupID: rc.config.GroupID,
}
m.RaftURLs = append(m.RaftURLs, rc.config.RaftAddr)
ctx, _ := json.Marshal(m)
// force add self node groups
if _, ok := grps[rc.config.ID]; !ok {
grps[rc.config.ID] = raftpb.Group{
NodeId: rc.config.nodeConfig.NodeID,
Name: rc.config.GroupName,
GroupId: rc.config.GroupID,
RaftReplicaId: rc.config.ID,
}
}
// force append the configuration change entries
toAppEnts := createConfigChangeEnts(ctx, ids, grps, rc.config.ID, st.Term, st.Commit)
ents = append(ents, toAppEnts...)
// force commit newly appended entries
err := w.Save(raftpb.HardState{}, toAppEnts)
if err != nil {
rc.Errorf("force commit error: %v", err)
return err
}
if len(ents) != 0 {
st.Commit = ents[len(ents)-1].Index
}
}
if snapshot != nil {
rc.raftStorage.ApplySnapshot(*snapshot)
}
rc.raftStorage.SetHardState(st)
// append to storage so raft starts at the right place in log
rc.raftStorage.Append(ents)
// send nil once lastIndex is published so client knows commit channel is current
if len(ents) > 0 {
rc.lastIndex = ents[len(ents)-1].Index
atomic.StoreInt32(&rc.replayRunning, 1)
} else {
atomic.StoreInt32(&rc.replayRunning, 0)
}
rc.Infof("replaying WAL (%v) at lastIndex : %v", len(ents), rc.lastIndex)
return nil
}
func (rc *raftNode) IsReplayFinished() bool {
return atomic.LoadInt32(&rc.replayRunning) == 0
}
func (rc *raftNode) MarkReplayFinished() {
atomic.StoreInt32(&rc.replayRunning, 0)
}
func (rc *raftNode) startRaft(ds DataStorage, standalone bool) error {
walDir := rc.config.WALDir
oldwal := wal.Exist(walDir)
elecTick := rc.config.nodeConfig.ElectionTick
if elecTick < 10 {
elecTick = 10
}
c := &raft.Config{
ID: uint64(rc.config.ID),
ElectionTick: elecTick,
HeartbeatTick: elecTick / 10,
Storage: rc.raftStorage,
MaxSizePerMsg: settings.Soft.MaxSizePerMsg,
MaxInflightMsgs: int(maxInflightMsgs),
MaxCommittedSizePerReady: settings.Soft.MaxCommittedSizePerReady,
CheckQuorum: true,
PreVote: true,
Logger: nodeLog,
Group: raftpb.Group{NodeId: rc.config.nodeConfig.NodeID,
Name: rc.config.GroupName, GroupId: rc.config.GroupID,
RaftReplicaId: uint64(rc.config.ID)},
}
if oldwal {
rc.Infof("loading from old wal: %s", walDir)
// Find a snapshot to start/restart a raft node
walSnaps, err := wal.ValidSnapshotEntries(walDir)
if err != nil {
return err
}
// snapshot files can be orphaned if etcd crashes after writing them but before writing the corresponding
// wal log entries
snapshot, err := rc.persistStorage.LoadNewestAvailable(walSnaps)
if err != nil && err != snap.ErrNoSnapshot {
nodeLog.Warning(err)
return err
}
if err == snap.ErrNoSnapshot || raft.IsEmptySnap(*snapshot) {
rc.Infof("loading no snapshot \n")
rc.ds.CleanData()
} else {
rc.Infof("loading snapshot at term %d and index %d, snap: %v",
snapshot.Metadata.Term,
snapshot.Metadata.Index, snapshot.Metadata.ConfState)
// update the latest snapshot index for statemachine
rc.ds.UpdateSnapshotState(snapshot.Metadata.Term, snapshot.Metadata.Index)
err := rc.ds.PrepareSnapshot(*snapshot)
if err == nil {
if err := rc.ds.RestoreFromSnapshot(*snapshot); err != nil {
rc.Errorf("failed to restore from snapshot: %s", err)
return err
}
} else if err == errNobackupAvailable {
if common.IsConfSetted(common.ConfIgnoreStartupNoBackup) {
rc.Infof("ignore failed at startup for no any backup from anyware")
} else {
return err
}
} else {
return err
}
}
if standalone {
err = rc.restartAsStandaloneNode(c, snapshot)
} else {
err = rc.restartNode(c, snapshot)
}
if err != nil {
rc.Infof("restarting node failed: %v", err.Error())
return err
}
} else {
rc.ds.CleanData()
w, _, _, _, err := rc.openWAL(nil, false)
if err != nil {
return err
}
if rs, ok := rc.persistStorage.(*raftPersistStorage); ok {
rs.WAL = w
}
rpeers := make([]raft.Peer, 0, len(rc.config.RaftPeers))
for _, v := range rc.config.RaftPeers {
var m common.MemberInfo
m.GroupID = rc.config.GroupID
m.GroupName = rc.config.GroupName
m.ID = v.ReplicaID
m.RaftURLs = append(m.RaftURLs, v.RaftAddr)
m.NodeID = v.NodeID
d, _ := json.Marshal(m)
rpeers = append(rpeers,
raft.Peer{ReplicaID: v.ReplicaID, NodeID: v.NodeID, Context: d})
}
isLearner := rc.config.nodeConfig.LearnerRole != ""
startPeers := rpeers
if rc.join {
startPeers = nil
}
if len(startPeers) == 0 {
rc.Infof("loading empty wal: %s without peers", walDir)
rc.node = raft.RestartNode(c)
} else {
rc.Infof("loading empty wal: %s with peers: %v", walDir, startPeers)
rc.node = raft.StartNode(c, startPeers, isLearner)
}
}
rc.initForTransport()
rc.wgServe.Add(1)
go func() {
defer rc.wgServe.Done()
rc.serveChannels()
}()
return nil
}
func (rc *raftNode) initForTransport() {
if len(rc.members) == 0 {
for _, v := range rc.config.RaftPeers {
if v.NodeID != rc.config.nodeConfig.NodeID {
if rc.join {
rc.transport.AddRemote(types.ID(v.NodeID), []string{v.RaftAddr})
} else {
rc.transport.UpdatePeer(types.ID(v.NodeID), []string{v.RaftAddr})
}
}
}
}
for _, m := range rc.members {
if m.NodeID != uint64(rc.config.nodeConfig.NodeID) {
rc.transport.UpdatePeer(types.ID(m.NodeID), m.RaftURLs)
}
}
for _, m := range rc.learnerMems {
if m.NodeID != uint64(rc.config.nodeConfig.NodeID) {
rc.transport.UpdatePeer(types.ID(m.NodeID), m.RaftURLs)
}
}
}
func (rc *raftNode) restartNode(c *raft.Config, snapshot *raftpb.Snapshot) error {
err := rc.replayWAL(snapshot, false)
if err != nil {
rc.Infof("restarting node failed to replay wal: %v", err.Error())
return err
}
rc.node = raft.RestartNode(c)
advanceTicksForElection(rc.node, c.ElectionTick)
return nil
}
func (rc *raftNode) restartAsStandaloneNode(cfg *raft.Config, snapshot *raftpb.Snapshot) error {
err := rc.replayWAL(snapshot, true)
if err != nil {
return err
}
rc.node = raft.RestartNode(cfg)
return nil
}
// returns an ordered set of IDs included in the given snapshot and
// the entries. The given snapshot/entries can contain two kinds of
// ID-related entry:
// - ConfChangeAddNode, in which case the contained ID will be added into the set.
// - ConfChangeRemoveNode, in which case the contained ID will be removed from the set.
// - ConfChangeAddLearnerNode, in which the contained ID will be added into the set.
func getIDsAndGroups(snap *raftpb.Snapshot, ents []raftpb.Entry) ([]uint64, map[uint64]raftpb.Group) {
ids := make(map[uint64]bool)
grps := make(map[uint64]raftpb.Group)
if snap != nil {
for _, id := range snap.Metadata.ConfState.Nodes {
ids[id] = true
}
for _, grp := range snap.Metadata.ConfState.Groups {
grps[grp.RaftReplicaId] = *grp
}
for _, id := range snap.Metadata.ConfState.Learners {
ids[id] = true
}
for _, grp := range snap.Metadata.ConfState.LearnerGroups {
grps[grp.RaftReplicaId] = *grp
}
}
for _, e := range ents {
if e.Type != raftpb.EntryConfChange {
continue
}
var cc raftpb.ConfChange
cc.Unmarshal(e.Data)
switch cc.Type {
case raftpb.ConfChangeAddLearnerNode:
// https://github.com/etcd-io/etcd/pull/12288
ids[cc.ReplicaID] = true
grps[cc.NodeGroup.RaftReplicaId] = cc.NodeGroup
case raftpb.ConfChangeAddNode:
ids[cc.ReplicaID] = true
grps[cc.NodeGroup.RaftReplicaId] = cc.NodeGroup
case raftpb.ConfChangeRemoveNode:
delete(ids, cc.ReplicaID)
delete(grps, cc.NodeGroup.RaftReplicaId)
case raftpb.ConfChangeUpdateNode:
// do nothing
default:
nodeLog.Errorf("ConfChange Type should be either ConfChangeAddNode or ConfChangeRemoveNode!")
}
}
sids := make(types.Uint64Slice, 0, len(ids))
for id := range ids {
sids = append(sids, id)
}
sort.Sort(sids)
return []uint64(sids), grps
}
// createConfigChangeEnts creates a series of Raft entries (i.e.
// EntryConfChange) to remove the set of given IDs from the cluster. The ID
// `self` is _not_ removed, even if present in the set.
// If `self` is not inside the given ids, it creates a Raft entry to add a
// default member with the given `self`.
func createConfigChangeEnts(ctx []byte, ids []uint64, grps map[uint64]raftpb.Group,
self uint64, term, index uint64) []raftpb.Entry {
ents := make([]raftpb.Entry, 0)
next := index + 1
found := false
for _, id := range ids {
if id == self {
found = true
continue
}
cc := &raftpb.ConfChange{
Type: raftpb.ConfChangeRemoveNode,
ReplicaID: id,
NodeGroup: grps[id],
}
d, _ := cc.Marshal()
e := raftpb.Entry{
Type: raftpb.EntryConfChange,
Data: d,
Term: term,
Index: next,
}
ents = append(ents, e)
next++
}
if !found {
cc := &raftpb.ConfChange{
Type: raftpb.ConfChangeAddNode,
ReplicaID: self,
NodeGroup: grps[self],
Context: ctx,
}
d, _ := cc.Marshal()
e := raftpb.Entry{
Type: raftpb.EntryConfChange,
Data: d,
Term: term,
Index: next,
}
ents = append(ents, e)
}
return ents
}
func advanceTicksForElection(n raft.Node, electionTicks int) {
for i := 0; i < electionTicks-1; i++ {
n.Tick()
}
}
func (rc *raftNode) StopNode() {
if !atomic.CompareAndSwapInt32(&rc.stopping, 0, 1) {
return
}
close(rc.stopc)
rc.wgServe.Wait()
rc.Infof("raft node stopped")
}
func newSnapshotReaderCloser() io.ReadCloser {
pr, pw := io.Pipe()
go func() {
// TODO: write state machine snapshot data to pw
pw.CloseWithError(nil)
}()
return pr
}
func (rc *raftNode) handleSendSnapshot(np *nodeProgress) {
select {
case m := <-rc.msgSnapC:
snapData, err := rc.persistStorage.Load()
if err != nil {
rc.Infof("load snapshot error : %v", err)
rc.ReportSnapshot(m.To, m.ToGroup, raft.SnapshotFailure)
return
}
if snapData.Metadata.Index > np.appliedi {
rc.Infof("load snapshot error, snapshot index should not great than applied: %v, %v", snapData.Metadata, np)
rc.ReportSnapshot(m.To, m.ToGroup, raft.SnapshotFailure)
return
}
atomic.AddInt64(&rc.inflightSnapshots, 1)
m.Snapshot = *snapData
snapRC := newSnapshotReaderCloser()
//TODO: copy snapshot data and send snapshot to follower
snapMsg := snap.NewMessage(m, snapRC, 0)
rc.Infof("begin send snapshot: %v", snapMsg.String())
rc.transport.SendSnapshot(*snapMsg)
rc.wgAsync.Add(1)
go func() {
defer rc.wgAsync.Done()
select {
case isOK := <-snapMsg.CloseNotify():
if isOK {
select {
case <-time.After(releaseDelayAfterSnapshot):
case <-rc.stopc:
}
}
atomic.AddInt64(&rc.inflightSnapshots, -1)
case <-rc.stopc:
return
}
}()
default:
}
}
func (rc *raftNode) beginSnapshot(snapTerm uint64, snapi uint64, confState raftpb.ConfState) error {
// here we can just begin snapshot, to freeze the state of storage
// and we can copy data async below
rc.Infof("begin get snapshot at: %v-%v", snapTerm, snapi)
sn, err := rc.ds.GetSnapshot(snapTerm, snapi)
if err != nil {
return err
}
rc.Infof("get snapshot object done: %v, state: %v", snapi, confState.String())
rc.wgAsync.Add(1)
go func() {
defer rc.wgAsync.Done()
data, err := sn.GetData()
if err != nil {
rc.Errorf("get snapshot data at index %d failed: %v", snapi, err)
return
}
rc.Infof("snapshot data : %v\n", string(data))
rc.Infof("create snapshot with conf : %v\n", confState)
// now we can do the actually snapshot for copy
snap, err := rc.raftStorage.CreateSnapshot(snapi, &confState, data)
if err != nil {
if err == raft.ErrSnapOutOfDate {
return
}
rc.Errorf("create snapshot at index %d failed: %v", snapi, err)
return
}
// SaveSnap saves the snapshot to file and appends the corresponding WAL entry.
if err := rc.persistStorage.SaveSnap(snap); err != nil {
rc.Errorf("save snapshot at index %v failed: %v", snap.Metadata, err)
return
}
err = rc.persistStorage.Sync()
if err != nil {
rc.Errorf("failed to sync wal: %s", err)
return
}
if err = rc.persistStorage.Release(snap); err != nil {
rc.Errorf("failed to release wal: %s", err)
return
}
// update the latest snapshot index for statemachine
rc.ds.UpdateSnapshotState(snap.Metadata.Term, snap.Metadata.Index)
compactIndex := uint64(1)
if snapi > uint64(rc.config.SnapCatchup) {
compactIndex = snapi - uint64(rc.config.SnapCatchup)
}
rc.Infof("saved snapshot at index %d, compact to: %v", snap.Metadata.Index, compactIndex)
if err := rc.raftStorage.Compact(compactIndex); err != nil {
if err == raft.ErrCompacted {
return
}
rc.Errorf("compact log at index %v failed: %v", compactIndex, err)
return
}
rc.Infof("compacted log at index %d", compactIndex)
}()
return nil
}
// publishEntries writes committed log entries to commit channel and returns
// whether all entries could be published.
func (rc *raftNode) publishEntries(ents []raftpb.Entry, snapshot raftpb.Snapshot, snapResult chan error,
raftDone chan struct{}, applyWaitDone chan struct{}) {
select {
case rc.commitC <- applyInfo{
ents: ents,
snapshot: snapshot,
applySnapshotResult: snapResult,
raftDone: raftDone,
applyWaitDone: applyWaitDone,
}:
case <-rc.stopc:
return
}
}
func (rc *raftNode) maybeTryElection() {
// to avoid election at the same time, we only allow the smallest node to elect
smallest := rc.config.ID
for _, v := range rc.config.RaftPeers {
if v.ReplicaID < smallest {
smallest = v.ReplicaID
}
}
rc.Infof("replica %v should advance to elect, mine is: %v", smallest, rc.config.ID)
if smallest == rc.config.ID {
advanceTicksForElection(rc.node, rc.config.nodeConfig.ElectionTick*2)
}
}
// return (self removed, any conf changed, error)
func (rc *raftNode) applyConfChange(cc raftpb.ConfChange, confState *raftpb.ConfState) (bool, bool, error) {
// TODO: validate configure change here
*confState = *rc.node.ApplyConfChange(cc)
confChanged := false
switch cc.Type {
case raftpb.ConfChangeAddNode:
rc.Infof("conf change : node add : %v\n", cc.String())
if len(cc.Context) > 0 {
var m common.MemberInfo
err := json.Unmarshal(cc.Context, &m)
if err != nil {
rc.Errorf("error conf context: %v", err)
go rc.ds.Stop()
return false, false, err
} else {
m.ID = cc.ReplicaID
if m.NodeID == 0 {
rc.Errorf("invalid member info: %v", m)
go rc.ds.Stop()
return false, confChanged, errors.New("add member should include node id ")
}
rc.memMutex.Lock()
memNum := len(rc.members)
if _, ok := rc.members[m.ID]; ok {
rc.Infof("node already exist in cluster: %v\n", m)
rc.memMutex.Unlock()
} else {
confChanged = true
rc.members[m.ID] = &m
memNum++
atomic.StoreInt32(&rc.memberCnt, int32(memNum))
rc.memMutex.Unlock()
if m.NodeID != rc.config.nodeConfig.NodeID {
rc.transport.UpdatePeer(types.ID(m.NodeID), m.RaftURLs)
}
rc.Infof("node added to the cluster: %v\n", m)
}
if rc.Lead() == raft.None && memNum >= 2 && memNum >= len(rc.config.RaftPeers) {
rc.maybeTryElection()
}
}
}
case raftpb.ConfChangeRemoveNode:
rc.memMutex.Lock()
rc.Infof("raft replica %v removed from the cluster!", cc.String())
delete(rc.members, cc.ReplicaID)
delete(rc.learnerMems, cc.ReplicaID)
confChanged = true
atomic.StoreInt32(&rc.memberCnt, int32(len(rc.members)))
rc.memMutex.Unlock()
if cc.ReplicaID == uint64(rc.config.ID) {
rc.Infof("I've been removed from the cluster! Shutting down. %v", cc.String())
return true, confChanged, nil
}
case raftpb.ConfChangeUpdateNode:
var m common.MemberInfo
json.Unmarshal(cc.Context, &m)
rc.Infof("node updated to the cluster: %v-%v\n", cc.String(), m)
rc.memMutex.Lock()
oldm := rc.members[cc.ReplicaID]
rc.members[cc.ReplicaID] = &m
if oldm != nil && !oldm.IsEqual(&m) {
confChanged = true
}
atomic.StoreInt32(&rc.memberCnt, int32(len(rc.members)))
rc.memMutex.Unlock()
if cc.NodeGroup.NodeId != uint64(rc.config.nodeConfig.NodeID) {
rc.transport.UpdatePeer(types.ID(cc.NodeGroup.NodeId), m.RaftURLs)
}
case raftpb.ConfChangeAddLearnerNode:
rc.Infof("got add learner change: %v", cc.String())
var m common.MemberInfo
err := json.Unmarshal(cc.Context, &m)
if err != nil {
rc.Errorf("error conf context: %v", err)
return false, false, err
}
m.ID = cc.ReplicaID
if m.NodeID == 0 {
rc.Errorf("invalid member info: %v", m)
return false, confChanged, errors.New("add member should include node id ")
}
rc.memMutex.Lock()
if _, ok := rc.learnerMems[cc.ReplicaID]; !ok {
rc.learnerMems[cc.ReplicaID] = &m
}
rc.memMutex.Unlock()
confChanged = true
if m.NodeID != rc.config.nodeConfig.NodeID {
rc.transport.UpdatePeer(types.ID(m.NodeID), m.RaftURLs)
}
}
return false, confChanged, nil
}
func (rc *raftNode) isServerRunning() bool {
return atomic.LoadInt32(&rc.loopServering) == 1
}
func (rc *raftNode) serveChannels() {
purgeDone := make(chan struct{})
raftReadyLoopC := make(chan struct{})
go rc.purgeFile(purgeDone, raftReadyLoopC)
atomic.StoreInt32(&rc.loopServering, 1)
defer atomic.StoreInt32(&rc.loopServering, 0)
defer func() {
if e := recover(); e != nil {
buf := make([]byte, 4096)
n := runtime.Stack(buf, false)
buf = buf[0:n]
rc.Errorf("handle raft loop panic: %s:%v", buf, e)
go rc.ds.Stop()
<-rc.stopc
}
// wait purge stopped to avoid purge the files after wal closed
close(raftReadyLoopC)
<-purgeDone
close(rc.commitC)
rc.Infof("raft node stopping")
// wait all async operation done
rc.wgAsync.Wait()
rc.node.Stop()
rc.persistStorage.Close()
rc.raftStorage.Close()
rc.raftStorage = nil
}()
// event loop on raft state machine updates
for {
select {
case <-rc.stopc:
return
case <-rc.node.EventNotifyCh():
metric.QueueLen.With(ps.Labels{
"namespace": rc.Descrp(),
"queue_name": "apply_commit_queue",
}).Set(float64(len(rc.commitC)))
moreEntriesToApply := cap(rc.commitC)-len(rc.commitC) > 3
// we should slow down raft logs receiving while applying is slow, otherwise we
// may have too much logs in memory if the applying is slow.
busy := rc.IsBusySnapshot()
if !busy {
// note: if the lastIndex and FirstIndex is slow, we should avoid call it in every step
// and this may cause the raft log send some overflowed messages because the raft logs will
// send as much as MaxInflights*MaxSizePerMsg in pipeline (may increase the network bandwidth), so if we replaced the memory raft
// storage we can remove this to allow receiving all logs from leader.
last, err := rc.raftStorage.LastIndex()
if err == nil {
fi, _ := rc.raftStorage.FirstIndex()
fi = fi - 1
if last > fi && last-fi >= uint64(rc.config.SnapCatchup+rc.config.SnapCount)*10 {
busy = true
metric.EventCnt.With(ps.Labels{
"namespace": rc.Descrp(),
"event_name": "raft_too_much_logs_unapplied",
}).Inc()
}
}
}
if !moreEntriesToApply && !busy {
// apply buffer nearly full, should slow down and refuse some slow write proposal
if rc.slowLimiter != nil {
rc.slowLimiter.MarkHeavySlow()
}
metric.EventCnt.With(ps.Labels{
"namespace": rc.Descrp(),
"event_name": "raft_apply_buffer_full",
}).Inc()
} else if len(rc.commitC) <= 10 {
}
rd, hasUpdate := rc.node.StepNode(moreEntriesToApply, busy)
if !hasUpdate {
continue
}
rc.processReady(rd)
if rd.MoreCommittedEntries {
rc.node.NotifyEventCh()
}
}
}
}
func (rc *raftNode) processReady(rd raft.Ready) {
isMeNewLeader := false
if rd.SoftState != nil {
isMeNewLeader = (rd.RaftState == raft.StateLeader)
oldLead := atomic.LoadUint64(&rc.lead)
isMeLosingLeader := (oldLead == uint64(rc.config.ID)) && !isMeNewLeader
if rd.SoftState.Lead != raft.None && oldLead != rd.SoftState.Lead {
rc.Infof("leader changed from %v to %v", oldLead, rd.SoftState)
atomic.StoreInt64(&rc.lastLeaderChangedTs, time.Now().UnixNano())
metric.EventCnt.With(ps.Labels{
"namespace": rc.Descrp(),
"event_name": "raft_leader_changed",
}).Inc()
}
if rd.SoftState.Lead == raft.None && oldLead != raft.None {
// TODO: handle proposal drop if leader is lost
//rc.triggerLeaderLost()
}
if isMeNewLeader || isMeLosingLeader {
rc.triggerLeaderChanged()
}
atomic.StoreUint64(&rc.lead, rd.SoftState.Lead)
}
rc.processReadStates(&rd)
raftDone := make(chan struct{}, 1)
var applyWaitDone chan struct{}
waitApply := false
if !isMeNewLeader {
// Candidate or follower needs to wait for all pending configuration
// changes to be applied before sending messages.
// Otherwise we might incorrectly count votes (e.g. votes from removed members).
// Also slow machine's follower raft-layer could proceed to become the leader
// on its own single-node cluster, before apply-layer applies the config change.
// We simply wait for ALL pending entries to be applied for now.
// We might improve this later on if it causes unnecessary long blocking issues.
for _, ent := range rd.CommittedEntries {
if ent.Type == raftpb.EntryConfChange {
waitApply = true
rc.Infof("need wait apply for config changed: %v", ent.String())
break
}
}
if waitApply {