Skip to content

Commit

Permalink
Ensure known leader is cleared on state transition
Browse files Browse the repository at this point in the history
  • Loading branch information
armon committed Feb 16, 2015
1 parent 8610f90 commit a88bfa8
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
10 changes: 9 additions & 1 deletion raft.go
Original file line number Diff line number Diff line change
Expand Up @@ -667,8 +667,8 @@ func (r *Raft) runCandidate() {
// Check if we've become the leader
if grantedVotes >= votesNeeded {
r.logger.Printf("[INFO] raft: Election won. Tally: %d", grantedVotes)
r.setLeader(r.localAddr)
r.setState(Leader)
r.setLeader(r.localAddr)
return
}

Expand Down Expand Up @@ -1567,6 +1567,14 @@ func (r *Raft) setCurrentTerm(t uint64) {
r.raftState.setCurrentTerm(t)
}

// setState is used to update the current state. Any state
// transition causes the known leader to be cleared. This means
// that leader should be set only after updating the state.
func (r *Raft) setState(state RaftState) {
r.setLeader(nil)
r.raftState.setState(state)
}

// runSnapshots is a long running goroutine used to manage taking
// new snapshots of the FSM. It runs in parallel to the FSM and
// main goroutines, so that snapshots do not block normal operation.
Expand Down
13 changes: 13 additions & 0 deletions raft_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1279,6 +1279,14 @@ func TestRaft_LeaderLeaseExpire(t *testing.T) {
if last != follower.LastContact() {
t.Fatalf("unexpected further contact")
}

// Ensure both have cleared their leader
if l := leader.Leader(); l != nil {
t.Fatalf("bad: %v", l)
}
if l := follower.Leader(); l != nil {
t.Fatalf("bad: %v", l)
}
}

func TestRaft_Barrier(t *testing.T) {
Expand Down Expand Up @@ -1374,6 +1382,11 @@ func TestRaft_VerifyLeader_Fail(t *testing.T) {
if err := verify.Error(); err != ErrNotLeader && err != ErrLeadershipLost {
t.Fatalf("err: %v", err)
}

// Ensure the known leader is cleared
if l := leader.Leader(); l != nil {
t.Fatalf("bad: %v", l)
}
}

func TestRaft_VerifyLeader_ParitalConnect(t *testing.T) {
Expand Down

0 comments on commit a88bfa8

Please sign in to comment.