Skip to content

Commit

Permalink
Fix to returning stale leader ID issue
Browse files Browse the repository at this point in the history
* Once a leader becomes a follower due to vote requests, its role
immediately changes, but `leader_id_` does not. It may cause an
issue returning a stale leader ID.
  • Loading branch information
greensky00 committed May 14, 2020
1 parent cbe1bee commit a67d17e
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
8 changes: 7 additions & 1 deletion include/libnuraft/raft_server.hxx
Original file line number Diff line number Diff line change
Expand Up @@ -323,7 +323,13 @@ public:
* @return Leader ID
* -1 if there is no live leader.
*/
int32 get_leader() const { return leader_; }
int32 get_leader() const {
// We should handle the case when `role_` is already
// updated, but `leader_` value is stale.
if ( leader_ == id_ &&
role_ != srv_role::leader ) return -1;
return leader_;
}

/**
* Check if this server is leader.
Expand Down
8 changes: 7 additions & 1 deletion src/handle_vote.cxx
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ void raft_server::request_prevote() {
}

hb_alive_ = false;
leader_ = -1;
pre_vote_.reset(state_->get_term());
// Count for myself.
pre_vote_.dead_++;
Expand Down Expand Up @@ -147,7 +148,12 @@ void raft_server::initiate_vote(bool ignore_priority) {
ctx_->state_mgr_->save_state(*state_);
request_vote(ignore_priority);
}
hb_alive_ = false;

if ( peers_.size() &&
get_quorum_for_election() ) {
hb_alive_ = false;
leader_ = -1;
} // Skip resetting above variables for single-node cluster.
}

void raft_server::request_vote(bool ignore_priority) {
Expand Down

0 comments on commit a67d17e

Please sign in to comment.