Properly handle RequestVote in all states
[controller.git] / opendaylight / md-sal / sal-akka-raft / src / main / java / org / opendaylight / controller / cluster / raft / behaviors / Candidate.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8
9 package org.opendaylight.controller.cluster.raft.behaviors;
10
11 import akka.actor.ActorRef;
12 import akka.actor.ActorSelection;
13 import org.opendaylight.controller.cluster.raft.RaftActorContext;
14 import org.opendaylight.controller.cluster.raft.RaftState;
15 import org.opendaylight.controller.cluster.raft.internal.messages.ElectionTimeout;
16 import org.opendaylight.controller.cluster.raft.messages.AppendEntries;
17 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
18 import org.opendaylight.controller.cluster.raft.messages.RequestVote;
19 import org.opendaylight.controller.cluster.raft.messages.RequestVoteReply;
20
21 import java.util.HashMap;
22 import java.util.List;
23 import java.util.Map;
24
25 /**
26  * The behavior of a RaftActor when it is in the CandidateState
27  * <p>
28  * Candidates (ยง5.2):
29  * <ul>
30  * <li> On conversion to candidate, start election:
31  * <ul>
32  * <li> Increment currentTerm
33  * <li> Vote for self
34  * <li> Reset election timer
35  * <li> Send RequestVote RPCs to all other servers
36  * </ul>
37  * <li> If votes received from majority of servers: become leader
38  * <li> If AppendEntries RPC received from new leader: convert to
39  * follower
40  * <li> If election timeout elapses: start new election
41  * </ul>
42  */
43 public class Candidate extends AbstractRaftActorBehavior {
44
45     private final Map<String, ActorSelection> peerToActor = new HashMap<>();
46
47     private int voteCount;
48
49     private final int votesRequired;
50
51     public Candidate(RaftActorContext context, List<String> peerPaths) {
52         super(context);
53
54         for (String peerPath : peerPaths) {
55             peerToActor.put(peerPath,
56                 context.actorSelection(peerPath));
57         }
58
59         if(peerPaths.size() > 0) {
60             // Votes are required from a majority of the peers including self.
61             // The votesRequired field therefore stores a calculated value
62             // of the number of votes required for this candidate to win an
63             // election based on it's known peers.
64             // If a peer was added during normal operation and raft replicas
65             // came to know about them then the new peer would also need to be
66             // taken into consideration when calculating this value.
67             // Here are some examples for what the votesRequired would be for n
68             // peers
69             // 0 peers = 1 votesRequired (0 + 1) / 2 + 1 = 1
70             // 2 peers = 2 votesRequired (2 + 1) / 2 + 1 = 2
71             // 4 peers = 3 votesRequired (4 + 1) / 2 + 1 = 3
72             int noOfPeers = peerPaths.size();
73             int self = 1;
74             votesRequired = (noOfPeers + self) / 2 + 1;
75         } else {
76             votesRequired = 0;
77         }
78
79         startNewTerm();
80         scheduleElection(electionDuration());
81     }
82
83     @Override protected RaftState handleAppendEntries(ActorRef sender,
84         AppendEntries appendEntries, RaftState suggestedState) {
85
86         // There is some peer who thinks it's a leader but is not
87         // I will not accept this append entries
88         sender.tell(new AppendEntriesReply(
89             context.getTermInformation().getCurrentTerm(), false),
90             context.getActor());
91
92         return suggestedState;
93     }
94
95     @Override protected RaftState handleAppendEntriesReply(ActorRef sender,
96         AppendEntriesReply appendEntriesReply, RaftState suggestedState) {
97
98         // Some peer thinks I was a leader and sent me a reply
99
100         return suggestedState;
101     }
102
103     @Override protected RaftState handleRequestVoteReply(ActorRef sender,
104         RequestVoteReply requestVoteReply, RaftState suggestedState) {
105         if(suggestedState == RaftState.Follower) {
106             // If base class thinks I should be follower then I am
107             return suggestedState;
108         }
109
110         if(requestVoteReply.isVoteGranted()){
111             voteCount++;
112         }
113
114         if(voteCount >= votesRequired){
115             return RaftState.Leader;
116         }
117
118         return state();
119     }
120
121     @Override protected RaftState state() {
122         return RaftState.Candidate;
123     }
124
125     @Override
126     public RaftState handleMessage(ActorRef sender, Object message) {
127         if(message instanceof ElectionTimeout){
128             if(votesRequired == 0){
129                 // If there are no peers then we should be a Leader
130                 // We wait for the election timeout to occur before declare
131                 // ourselves the leader. This gives enough time for a leader
132                 // who we do not know about (as a peer)
133                 // to send a message to the candidate
134                 return RaftState.Leader;
135             }
136             startNewTerm();
137             scheduleElection(electionDuration());
138             return state();
139         }
140         return super.handleMessage(sender, message);
141     }
142
143
144     private void startNewTerm(){
145         // set voteCount back to 1 (that is voting for self)
146         voteCount = 1;
147
148         // Increment the election term and vote for self
149         long currentTerm = context.getTermInformation().getCurrentTerm();
150         context.getTermInformation().update(currentTerm+1, context.getId());
151
152         // Request for a vote
153         for(ActorSelection peerActor : peerToActor.values()){
154             peerActor.tell(new RequestVote(
155                     context.getTermInformation().getCurrentTerm(),
156                     context.getId(), context.getReplicatedLog().last().getIndex(),
157                     context.getReplicatedLog().last().getTerm()),
158                 context.getActor());
159         }
160
161
162     }
163
164 }