Browse Source

raft: add sm.Index

Xiang Li 11 years ago
parent
commit
2ff3ce74c5
2 changed files with 6 additions and 3 deletions
  1. 1 1
      raft/node.go
  2. 5 2
      raft/raft.go

+ 1 - 1
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() }
 

+ 5 - 2
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}