Handle incoming RequestVote RPC. Learners and observers never grant votes: by definition they are not members of the voting set for this term, and granting a vote could let an incorrect quorum form.
(&mut self, req: &RequestVoteRequest)
| 16 | /// members of the voting set for this term, and granting a vote could |
| 17 | /// let an incorrect quorum form. |
| 18 | pub fn handle_request_vote(&mut self, req: &RequestVoteRequest) -> RequestVoteResponse { |
| 19 | match self.role { |
| 20 | NodeRole::Learner | NodeRole::Observer => { |
| 21 | // Learners and observers never grant votes. |
| 22 | return RequestVoteResponse { |
| 23 | term: self.hard_state.current_term, |
| 24 | vote_granted: false, |
| 25 | }; |
| 26 | } |
| 27 | NodeRole::Follower | NodeRole::Candidate | NodeRole::Leader => {} |
| 28 | } |
| 29 | |
| 30 | if req.term > self.hard_state.current_term { |
| 31 | self.become_follower(req.term); |
| 32 | } |
| 33 | |
| 34 | if req.term < self.hard_state.current_term { |
| 35 | return RequestVoteResponse { |
| 36 | term: self.hard_state.current_term, |
| 37 | vote_granted: false, |
| 38 | }; |
| 39 | } |
| 40 | |
| 41 | let voted_for = self.hard_state.voted_for; |
| 42 | let can_vote = voted_for == 0 || voted_for == req.candidate_id; |
| 43 | |
| 44 | let log_ok = req.last_log_term > self.log.last_term() |
| 45 | || (req.last_log_term == self.log.last_term() |
| 46 | && req.last_log_index >= self.log.last_index()); |
| 47 | |
| 48 | if can_vote && log_ok { |
| 49 | self.hard_state.voted_for = req.candidate_id; |
| 50 | self.persist_hard_state(); |
| 51 | self.reset_election_timeout(); |
| 52 | |
| 53 | debug!( |
| 54 | node = self.config.node_id, |
| 55 | group = self.config.group_id, |
| 56 | candidate = req.candidate_id, |
| 57 | term = req.term, |
| 58 | "granted vote" |
| 59 | ); |
| 60 | |
| 61 | RequestVoteResponse { |
| 62 | term: self.hard_state.current_term, |
| 63 | vote_granted: true, |
| 64 | } |
| 65 | } else { |
| 66 | RequestVoteResponse { |
| 67 | term: self.hard_state.current_term, |
| 68 | vote_granted: false, |
| 69 | } |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | /// Handle RequestVote response (candidate only). |
| 74 | pub fn handle_request_vote_response(&mut self, peer: u64, resp: &RequestVoteResponse) { |