176704f3d377323a962d5a171cfe53c84beb494e
[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 java.util.ArrayList;
14 import java.util.Collection;
15 import org.opendaylight.controller.cluster.raft.PeerInfo;
16 import org.opendaylight.controller.cluster.raft.RaftActorContext;
17 import org.opendaylight.controller.cluster.raft.RaftState;
18 import org.opendaylight.controller.cluster.raft.base.messages.ElectionTimeout;
19 import org.opendaylight.controller.cluster.raft.messages.AppendEntries;
20 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
21 import org.opendaylight.controller.cluster.raft.messages.RaftRPC;
22 import org.opendaylight.controller.cluster.raft.messages.RequestVote;
23 import org.opendaylight.controller.cluster.raft.messages.RequestVoteReply;
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 int voteCount;
46
47     private final int votesRequired;
48
49     private final Collection<String> votingPeers = new ArrayList<>();
50
51     public Candidate(RaftActorContext context) {
52         super(context, RaftState.Candidate);
53
54         for(PeerInfo peer: context.getPeers()) {
55             if(peer.isVoting()) {
56                 votingPeers.add(peer.getId());
57             }
58         }
59
60         if(LOG.isDebugEnabled()) {
61             LOG.debug("{}: Election: Candidate has following voting peers: {}", logName(), votingPeers);
62         }
63
64         votesRequired = getMajorityVoteCount(votingPeers.size());
65
66         startNewTerm();
67
68         if(votingPeers.isEmpty()){
69             actor().tell(ElectionTimeout.INSTANCE, actor());
70         } else {
71             scheduleElection(electionDuration());
72         }
73     }
74
75     @Override
76     public final String getLeaderId() {
77         return null;
78     }
79
80     @Override
81     public final short getLeaderPayloadVersion() {
82         return -1;
83     }
84
85     @Override
86     protected RaftActorBehavior handleAppendEntries(ActorRef sender,
87         AppendEntries appendEntries) {
88
89         if(LOG.isDebugEnabled()) {
90             LOG.debug("{}: handleAppendEntries: {}", logName(), appendEntries);
91         }
92
93         // Some other candidate for the same term became a leader and sent us an append entry
94         if(currentTerm() == appendEntries.getTerm()){
95             LOG.debug("{}: New Leader sent an append entry to Candidate for term {} will switch to Follower",
96                     logName(), currentTerm());
97
98             return switchBehavior(new Follower(context));
99         }
100
101         return this;
102     }
103
104     @Override
105     protected RaftActorBehavior handleAppendEntriesReply(ActorRef sender, AppendEntriesReply appendEntriesReply) {
106         return this;
107     }
108
109     @Override
110     protected RaftActorBehavior handleRequestVoteReply(ActorRef sender, RequestVoteReply requestVoteReply) {
111         LOG.debug("{}: handleRequestVoteReply: {}, current voteCount: {}", logName(), requestVoteReply, voteCount);
112
113         if (requestVoteReply.isVoteGranted()) {
114             voteCount++;
115         }
116
117         if (voteCount >= votesRequired) {
118             if(context.getLastApplied() < context.getReplicatedLog().lastIndex()) {
119                 LOG.debug("{}: LastApplied index {} is behind last index {}", logName(), context.getLastApplied(),
120                         context.getReplicatedLog().lastIndex());
121                 return internalSwitchBehavior(RaftState.PreLeader);
122             } else {
123                 return internalSwitchBehavior(RaftState.Leader);
124             }
125         }
126
127         return this;
128     }
129
130     @Override
131     public RaftActorBehavior handleMessage(ActorRef sender, Object message) {
132         if (message instanceof ElectionTimeout) {
133             LOG.debug("{}: Received ElectionTimeout", logName());
134
135             if (votesRequired == 0) {
136                 // If there are no peers then we should be a Leader
137                 // We wait for the election timeout to occur before declare
138                 // ourselves the leader. This gives enough time for a leader
139                 // who we do not know about (as a peer)
140                 // to send a message to the candidate
141
142                 return internalSwitchBehavior(RaftState.Leader);
143             }
144
145             startNewTerm();
146             scheduleElection(electionDuration());
147             return this;
148         }
149
150         if (message instanceof RaftRPC) {
151
152             RaftRPC rpc = (RaftRPC) message;
153
154             if(LOG.isDebugEnabled()) {
155                 LOG.debug("{}: RaftRPC message received {}, my term is {}", logName(), rpc,
156                         context.getTermInformation().getCurrentTerm());
157             }
158
159             // If RPC request or response contains term T > currentTerm:
160             // set currentTerm = T, convert to follower (§5.1)
161             // This applies to all RPC messages and responses
162             if (rpc.getTerm() > context.getTermInformation().getCurrentTerm()) {
163                 context.getTermInformation().updateAndPersist(rpc.getTerm(), null);
164
165                 // The raft paper does not say whether or not a Candidate can/should process a RequestVote in
166                 // this case but doing so gains quicker convergence when the sender's log is more up-to-date.
167                 if (message instanceof RequestVote) {
168                     super.handleMessage(sender, message);
169                 }
170
171                 return internalSwitchBehavior(RaftState.Follower);
172             }
173         }
174
175         return super.handleMessage(sender, message);
176     }
177
178
179     private void startNewTerm() {
180
181
182         // set voteCount back to 1 (that is voting for self)
183         voteCount = 1;
184
185         // Increment the election term and vote for self
186         long currentTerm = context.getTermInformation().getCurrentTerm();
187         long newTerm = currentTerm + 1;
188         context.getTermInformation().updateAndPersist(newTerm, context.getId());
189
190         LOG.debug("{}: Starting new term {}", logName(), newTerm);
191
192         // Request for a vote
193         // TODO: Retry request for vote if replies do not arrive in a reasonable
194         // amount of time TBD
195         for (String peerId : votingPeers) {
196             ActorSelection peerActor = context.getPeerActorSelection(peerId);
197             if(peerActor != null) {
198                 RequestVote requestVote = new RequestVote(
199                         context.getTermInformation().getCurrentTerm(),
200                         context.getId(),
201                         context.getReplicatedLog().lastIndex(),
202                         context.getReplicatedLog().lastTerm());
203
204                 LOG.debug("{}: Sending {} to peer {}", logName(), requestVote, peerId);
205
206                 peerActor.tell(requestVote, context.getActor());
207             }
208         }
209     }
210
211     @Override
212     public void close() {
213         stopElection();
214     }
215 }