2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
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
9 package org.opendaylight.controller.cluster.raft.behaviors;
11 import akka.actor.ActorRef;
12 import akka.actor.ActorSelection;
13 import akka.actor.Cancellable;
14 import org.opendaylight.controller.cluster.raft.RaftActorContext;
15 import org.opendaylight.controller.cluster.raft.RaftState;
16 import org.opendaylight.controller.cluster.raft.internal.messages.ElectionTimeout;
17 import org.opendaylight.controller.cluster.raft.messages.AppendEntries;
18 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
19 import org.opendaylight.controller.cluster.raft.messages.RequestVote;
20 import org.opendaylight.controller.cluster.raft.messages.RequestVoteReply;
21 import scala.concurrent.duration.FiniteDuration;
23 import java.util.HashMap;
24 import java.util.List;
26 import java.util.Random;
27 import java.util.concurrent.TimeUnit;
28 import java.util.concurrent.atomic.AtomicLong;
31 * The behavior of a RaftActor when it is in the CandidateState
35 * <li> On conversion to candidate, start election:
37 * <li> Increment currentTerm
39 * <li> Reset election timer
40 * <li> Send RequestVote RPCs to all other servers
42 * <li> If votes received from majority of servers: become leader
43 * <li> If AppendEntries RPC received from new leader: convert to
45 * <li> If election timeout elapses: start new election
48 public class Candidate extends AbstractRaftActorBehavior {
51 * The maximum election time variance
53 private static final int ELECTION_TIME_MAX_VARIANCE = 100;
56 * The interval in which a new election would get triggered if no leader is found
58 private static final long ELECTION_TIME_INTERVAL = Leader.HEART_BEAT_INTERVAL.toMillis() * 2;
63 private final Map<String, ActorSelection> peerToActor = new HashMap<>();
65 private Cancellable electionCancel = null;
67 private int voteCount;
69 private final int votesRequired;
71 public Candidate(RaftActorContext context, List<String> peerPaths) {
74 for (String peerPath : peerPaths) {
75 peerToActor.put(peerPath,
76 context.actorSelection(peerPath));
79 if(peerPaths.size() > 0) {
80 // Votes are required from a majority of the peers including self.
81 // The votesRequired field therefore stores a calculated value
82 // of the number of votes required for this candidate to win an
83 // election based on it's known peers.
84 // If a peer was added during normal operation and raft replicas
85 // came to know about them then the new peer would also need to be
86 // taken into consideration when calculating this value.
87 // Here are some examples for what the votesRequired would be for n
89 // 0 peers = 1 votesRequired (0 + 1) / 2 + 1 = 1
90 // 2 peers = 2 votesRequired (2 + 1) / 2 + 1 = 2
91 // 4 peers = 3 votesRequired (4 + 1) / 2 + 1 = 3
92 int noOfPeers = peerPaths.size();
94 votesRequired = (noOfPeers + self) / 2 + 1;
99 scheduleElection(randomizedDuration());
102 @Override protected RaftState handleAppendEntries(ActorRef sender,
103 AppendEntries appendEntries, RaftState suggestedState) {
105 // There is some peer who thinks it's a leader but is not
106 // I will not accept this append entries
107 sender.tell(new AppendEntriesReply(
108 context.getTermInformation().getCurrentTerm().get(), false),
111 return suggestedState;
114 @Override protected RaftState handleAppendEntriesReply(ActorRef sender,
115 AppendEntriesReply appendEntriesReply, RaftState suggestedState) {
117 // Some peer thinks I was a leader and sent me a reply
119 return suggestedState;
122 @Override protected RaftState handleRequestVote(ActorRef sender,
123 RequestVote requestVote, RaftState suggestedState) {
125 // We got this RequestVote because the term in there is less than
126 // or equal to our current term, so do not grant the vote
127 sender.tell(new RequestVoteReply(
128 context.getTermInformation().getCurrentTerm().get(), false),
131 return suggestedState;
134 @Override protected RaftState handleRequestVoteReply(ActorRef sender,
135 RequestVoteReply requestVoteReply, RaftState suggestedState) {
136 if(suggestedState == RaftState.Follower) {
137 // If base class thinks I should be follower then I am
138 return suggestedState;
141 if(requestVoteReply.isVoteGranted()){
145 if(voteCount >= votesRequired){
146 return RaftState.Leader;
152 @Override protected RaftState state() {
153 return RaftState.Candidate;
157 public RaftState handleMessage(ActorRef sender, Object message) {
158 if(message instanceof ElectionTimeout){
159 if(votesRequired == 0){
160 // If there are no peers then we should be a Leader
161 // We wait for the election timeout to occur before declare
162 // ourselves the leader. This gives enough time for a leader
163 // who we do not know about (as a peer)
164 // to send a message to the candidate
165 return RaftState.Leader;
167 scheduleElection(randomizedDuration());
170 return super.handleMessage(sender, message);
173 private FiniteDuration randomizedDuration(){
174 long variance = new Random().nextInt(ELECTION_TIME_MAX_VARIANCE);
175 return new FiniteDuration(ELECTION_TIME_INTERVAL + variance, TimeUnit.MILLISECONDS);
178 private void scheduleElection(FiniteDuration interval) {
180 // set voteCount back to 1 (that is voting for self)
183 // Increment the election term and vote for self
184 AtomicLong currentTerm = context.getTermInformation().getCurrentTerm();
185 context.getTermInformation().update(currentTerm.incrementAndGet(), context.getId());
187 // Request for a vote
188 for(ActorSelection peerActor : peerToActor.values()){
189 peerActor.tell(new RequestVote(
190 context.getTermInformation().getCurrentTerm().get(),
191 context.getId(), context.getReplicatedLog().last().getIndex(),
192 context.getReplicatedLog().last().getTerm()),
196 if (electionCancel != null && !electionCancel.isCancelled()) {
197 electionCancel.cancel();
200 // Schedule an election. When the scheduler triggers an ElectionTimeout
201 // message is sent to itself
203 context.getActorSystem().scheduler().scheduleOnce(interval,
204 context.getActor(), new ElectionTimeout(),
205 context.getActorSystem().dispatcher(), context.getActor());