diff --git a/raft/node.go b/raft/node.go index 85a2bb6de..e9d78b13d 100644 --- a/raft/node.go +++ b/raft/node.go @@ -45,7 +45,7 @@ func (n *Node) Id() int64 { return atomic.LoadInt64(&n.sm.id) } -func (n *Node) Index() int64 { return n.sm.log.lastIndex() } +func (n *Node) Index() int64 { return n.sm.index.Get() } func (n *Node) Term() int64 { return n.sm.term.Get() } diff --git a/raft/raft.go b/raft/raft.go index 3f89fb7c9..33507632d 100644 --- a/raft/raft.go +++ b/raft/raft.go @@ -112,7 +112,8 @@ type stateMachine struct { id int64 // the term we are participating in at any time - term atomicInt + term atomicInt + index atomicInt // who we voted for in term vote int64 @@ -233,7 +234,7 @@ func (sm *stateMachine) q() int { func (sm *stateMachine) appendEntry(e Entry) { e.Term = sm.term.Get() - sm.log.append(sm.log.lastIndex(), e) + sm.index.Set(sm.log.append(sm.log.lastIndex(), e)) sm.ins[sm.id].update(sm.log.lastIndex()) sm.maybeCommit() } @@ -319,6 +320,7 @@ func (sm *stateMachine) Step(m Message) (ok bool) { func (sm *stateMachine) handleAppendEntries(m Message) { if sm.log.maybeAppend(m.Index, m.LogTerm, m.Commit, m.Entries...) { + sm.index.Set(sm.log.lastIndex()) sm.send(Message{To: m.From, Type: msgAppResp, Index: sm.log.lastIndex()}) } else { sm.send(Message{To: m.From, Type: msgAppResp, Index: -1}) @@ -443,6 +445,7 @@ func (sm *stateMachine) restore(s Snapshot) { } sm.log.restore(s.Index, s.Term) + sm.index.Set(sm.log.lastIndex()) sm.ins = make(map[int64]*index) for _, n := range s.Nodes { sm.ins[n] = &index{next: sm.log.lastIndex() + 1}