Browse Source

raft: add clusterId to snapshot

Xiang Li 11 years ago
parent
commit
a5df254e53
4 changed files with 13 additions and 8 deletions
  1. 2 2
      raft/log.go
  2. 2 1
      raft/raft.go
  3. 7 3
      raft/raft_test.go
  4. 2 2
      raft/snapshot.go

+ 2 - 2
raft/log.go

@@ -156,8 +156,8 @@ func (l *raftLog) compact(i int64) int64 {
 	return int64(len(l.ents))
 }
 
-func (l *raftLog) snap(d []byte, index, term int64, nodes []int64) {
-	l.snapshot = Snapshot{d, nodes, index, term}
+func (l *raftLog) snap(d []byte, clusterId, index, term int64, nodes []int64) {
+	l.snapshot = Snapshot{clusterId, d, nodes, index, term}
 }
 
 func (l *raftLog) shouldCompact() bool {

+ 2 - 1
raft/raft.go

@@ -492,7 +492,7 @@ func stepFollower(sm *stateMachine, m Message) bool {
 }
 
 func (sm *stateMachine) compact(d []byte) {
-	sm.raftLog.snap(d, sm.raftLog.applied, sm.raftLog.term(sm.raftLog.applied), sm.nodes())
+	sm.raftLog.snap(d, sm.clusterId, sm.raftLog.applied, sm.raftLog.term(sm.raftLog.applied), sm.nodes())
 	sm.raftLog.compact(sm.raftLog.applied)
 }
 
@@ -505,6 +505,7 @@ func (sm *stateMachine) restore(s Snapshot) bool {
 
 	sm.raftLog.restore(s)
 	sm.index.Set(sm.raftLog.lastIndex())
+	sm.clusterId = s.ClusterId
 	sm.ins = make(map[int64]*index)
 	for _, n := range s.Nodes {
 		if n == sm.id {

+ 7 - 3
raft/raft_test.go

@@ -775,9 +775,10 @@ func TestRecvMsgBeat(t *testing.T) {
 
 func TestRestore(t *testing.T) {
 	s := Snapshot{
-		Index: defaultCompactThreshold + 1,
-		Term:  defaultCompactThreshold + 1,
-		Nodes: []int64{0, 1, 2},
+		ClusterId: 0xBEEF,
+		Index:     defaultCompactThreshold + 1,
+		Term:      defaultCompactThreshold + 1,
+		Nodes:     []int64{0, 1, 2},
 	}
 
 	sm := newStateMachine(0, []int64{0, 1})
@@ -785,6 +786,9 @@ func TestRestore(t *testing.T) {
 		t.Fatal("restore fail, want succeed")
 	}
 
+	if sm.clusterId != s.ClusterId {
+		t.Errorf("sm.cluster = %x, want %x", sm.clusterId, s.ClusterId)
+	}
 	if sm.raftLog.lastIndex() != s.Index {
 		t.Errorf("log.lastIndex = %d, want %d", sm.raftLog.lastIndex(), s.Index)
 	}

+ 2 - 2
raft/snapshot.go

@@ -3,8 +3,8 @@ package raft
 var emptySnapshot = Snapshot{}
 
 type Snapshot struct {
-	Data []byte
-
+	ClusterId int64
+	Data      []byte
 	// the configuration
 	Nodes []int64
 	// the index at which the snapshot was taken.