From 140fd6d6c4dd931b864d38b104b262bfdaf3f7b5 Mon Sep 17 00:00:00 2001 From: Yicheng Qin Date: Sun, 14 Sep 2014 16:45:45 -0700 Subject: [PATCH] raft: restart using last written entry also --- main.go | 2 +- raft/log.go | 5 +++++ raft/node_test.go | 3 ++- raft/raft.go | 3 +-- wal/wal.go | 1 - 5 files changed, 9 insertions(+), 5 deletions(-) diff --git a/main.go b/main.go index 368251353..15cbee4ce 100644 --- a/main.go +++ b/main.go @@ -107,7 +107,7 @@ func startRaft(id int64, peerIDs []int64, waldir string) (raft.Node, *wal.WAL) { // restart a node from previous wal // TODO(xiangli): check snapshot; not open from one - w, err := wal.OpenAtIndex(waldir, 1) + w, err := wal.OpenAtIndex(waldir, 0) if err != nil { log.Fatal(err) } diff --git a/raft/log.go b/raft/log.go index 9165d8c0b..cbfa90ee4 100644 --- a/raft/log.go +++ b/raft/log.go @@ -38,6 +38,11 @@ func (l *raftLog) isEmpty() bool { return l.offset == 0 && len(l.ents) == 1 } +func (l *raftLog) load(ents []pb.Entry) { + l.ents = ents + l.unstable = l.offset + int64(len(ents)) +} + func (l *raftLog) String() string { return fmt.Sprintf("offset=%d committed=%d applied=%d len(ents)=%d", l.offset, l.committed, l.applied, len(l.ents)) } diff --git a/raft/node_test.go b/raft/node_test.go index dbbb92cfd..eb461611a 100644 --- a/raft/node_test.go +++ b/raft/node_test.go @@ -171,6 +171,7 @@ func TestNode(t *testing.T) { func TestNodeRestart(t *testing.T) { entries := []raftpb.Entry{ + {}, {Term: 1, Index: 1}, {Term: 1, Index: 2, Data: []byte("foo")}, } @@ -179,7 +180,7 @@ func TestNodeRestart(t *testing.T) { want := Ready{ State: emptyState, // commit upto index commit index in st - CommittedEntries: entries[:st.Commit], + CommittedEntries: entries[1 : st.Commit+1], } n := Restart(1, []int64{1}, 0, 0, st, entries) diff --git a/raft/raft.go b/raft/raft.go index e8aa88cfe..4ddaf95bc 100644 --- a/raft/raft.go +++ b/raft/raft.go @@ -503,8 +503,7 @@ func (r *raft) loadEnts(ents []pb.Entry) { if !r.raftLog.isEmpty() { panic("cannot load entries when log is not empty") } - r.raftLog.append(0, ents...) - r.raftLog.unstable = r.raftLog.lastIndex() + 1 + r.raftLog.load(ents) } func (r *raft) loadState(state pb.State) { diff --git a/wal/wal.go b/wal/wal.go index 5d431b35e..57c994103 100644 --- a/wal/wal.go +++ b/wal/wal.go @@ -65,7 +65,6 @@ type WAL struct { } // Create creates a WAL ready for appending records. -// The index of first record saved MUST be 0. func Create(dirpath string) (*WAL, error) { log.Printf("path=%s wal.create", dirpath) if Exist(dirpath) {