diff --git a/raft/node.go b/raft/node.go index cca9b87e8..c1c7681c8 100644 --- a/raft/node.go +++ b/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 } diff --git a/raft/node_test.go b/raft/node_test.go index d06d5da7d..193f810ef 100644 --- a/raft/node_test.go +++ b/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 diff --git a/raft/raft.go b/raft/raft.go index bd31a2996..faaf05431 100644 --- a/raft/raft.go +++ b/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) {