Browse Source

Merge pull request #6099 from sinsharat/master

raft: handling of applying old snapshots
Xiang Li 9 năm trước cách đây
mục cha
commit
6c3efde51b
2 tập tin đã thay đổi với 34 bổ sung1 xóa
  1. 7 1
      raft/storage.go
  2. 27 0
      raft/storage_test.go

+ 7 - 1
raft/storage.go

@@ -168,7 +168,13 @@ func (ms *MemoryStorage) ApplySnapshot(snap pb.Snapshot) error {
 	ms.Lock()
 	defer ms.Unlock()
 
-	// TODO: return ErrSnapOutOfDate?
+	//handle check for old snapshot being applied
+	msIndex := ms.snapshot.Metadata.Index
+	snapIndex := snap.Metadata.Index
+	if msIndex >= snapIndex {
+		return ErrSnapOutOfDate
+	}
+
 	ms.snapshot = snap
 	ms.ents = []pb.Entry{{Term: snap.Metadata.Term, Index: snap.Metadata.Index}}
 	return nil

+ 27 - 0
raft/storage_test.go

@@ -256,3 +256,30 @@ func TestStorageAppend(t *testing.T) {
 		}
 	}
 }
+
+func TestStorageApplySnapshot(t *testing.T) {
+	cs := &pb.ConfState{Nodes: []uint64{1, 2, 3}}
+	data := []byte("data")
+
+	tests := []pb.Snapshot{{Data: data, Metadata: pb.SnapshotMetadata{Index: 4, Term: 4, ConfState: *cs}},
+		{Data: data, Metadata: pb.SnapshotMetadata{Index: 3, Term: 3, ConfState: *cs}},
+	}
+
+	s := NewMemoryStorage()
+
+	//Apply Snapshot successful
+	i := 0
+	tt := tests[i]
+	err := s.ApplySnapshot(tt)
+	if err != nil {
+		t.Errorf("#%d: err = %v, want %v", i, err, nil)
+	}
+
+	//Apply Snapshot fails due to ErrSnapOutOfDate
+	i = 1
+	tt = tests[i]
+	err = s.ApplySnapshot(tt)
+	if err != ErrSnapOutOfDate {
+		t.Errorf("#%d: err = %v, want %v", i, err, ErrSnapOutOfDate)
+	}
+}