Browse Source

raft: fix promotable

Yicheng Qin 11 years ago
parent
commit
15029381e1
3 changed files with 11 additions and 10 deletions
  1. 1 1
      raft/node.go
  2. 2 2
      raft/node_test.go
  3. 8 7
      raft/raft.go

+ 1 - 1
raft/node.go

@@ -195,7 +195,7 @@ func (n *Node) Next() []Entry {
 // If the current elapsed is greater or equal than the timeout,
 // node will send corresponding message to the statemachine.
 func (n *Node) Tick() {
-	if !n.sm.promotable() {
+	if n.sm.promotable == false {
 		return
 	}
 

+ 2 - 2
raft/node_test.go

@@ -13,8 +13,7 @@ const (
 func TestTickMsgHup(t *testing.T) {
 	n := New(0, defaultHeartbeat, defaultElection)
 	n.sm = newStateMachine(0, []int64{0, 1, 2})
-	// simulate to patch the join log
-	n.Step(Message{From: 1, Type: msgApp, Commit: 1, Entries: []Entry{Entry{}}})
+	n.sm.promotable = true
 
 	for i := 0; i < defaultElection*2; i++ {
 		n.Tick()
@@ -80,6 +79,7 @@ func TestResetElapse(t *testing.T) {
 	for i, tt := range tests {
 		n := New(0, defaultHeartbeat, defaultElection)
 		n.sm = newStateMachine(0, []int64{0, 1, 2})
+		n.sm.promotable = true
 		n.sm.raftLog.append(0, Entry{Type: Normal, Term: 1})
 		n.sm.term = 2
 		n.sm.raftLog.committed = 1

+ 8 - 7
raft/raft.go

@@ -158,6 +158,11 @@ type stateMachine struct {
 	pendingConf bool
 
 	unstableState State
+
+	// promotable indicates whether state machine could be promoted.
+	// New machine has to wait until it has been added to the cluster, or it
+	// may become the leader of the cluster without it.
+	promotable bool
 }
 
 func newStateMachine(id int64, peers []int64) *stateMachine {
@@ -300,13 +305,6 @@ func (sm *stateMachine) appendEntry(e Entry) {
 	sm.maybeCommit()
 }
 
-// promotable indicates whether state machine could be promoted.
-// New machine has to wait for the first log entry to be committed, or it will
-// always start as a one-node cluster.
-func (sm *stateMachine) promotable() bool {
-	return sm.raftLog.committed != 0
-}
-
 func (sm *stateMachine) becomeFollower(term int64, lead int64) {
 	sm.reset(term)
 	sm.lead.Set(lead)
@@ -408,6 +406,9 @@ func (sm *stateMachine) handleSnapshot(m Message) {
 func (sm *stateMachine) addNode(id int64) {
 	sm.addIns(id, 0, sm.raftLog.lastIndex()+1)
 	sm.pendingConf = false
+	if id == sm.id {
+		sm.promotable = true
+	}
 }
 
 func (sm *stateMachine) removeNode(id int64) {