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 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.RaftRPC;
19 import org.opendaylight.controller.cluster.raft.messages.RequestVote;
20 import org.opendaylight.controller.cluster.raft.messages.RequestVoteReply;
22 import java.util.Collection;
23 import java.util.HashMap;
27 * The behavior of a RaftActor when it is in the CandidateState
31 * <li> On conversion to candidate, start election:
33 * <li> Increment currentTerm
35 * <li> Reset election timer
36 * <li> Send RequestVote RPCs to all other servers
38 * <li> If votes received from majority of servers: become leader
39 * <li> If AppendEntries RPC received from new leader: convert to
41 * <li> If election timeout elapses: start new election
44 public class Candidate extends AbstractRaftActorBehavior {
46 private final Map<String, ActorSelection> peerToActor = new HashMap<>();
48 private int voteCount;
50 private final int votesRequired;
52 public Candidate(RaftActorContext context) {
55 Collection<String> peerPaths = context.getPeerAddresses().values();
57 for (String peerPath : peerPaths) {
58 peerToActor.put(peerPath,
59 context.actorSelection(peerPath));
62 context.getLogger().debug("Election:Candidate has following peers:"+peerToActor.keySet());
63 if(peerPaths.size() > 0) {
64 // Votes are required from a majority of the peers including self.
65 // The votesRequired field therefore stores a calculated value
66 // of the number of votes required for this candidate to win an
67 // election based on it's known peers.
68 // If a peer was added during normal operation and raft replicas
69 // came to know about them then the new peer would also need to be
70 // taken into consideration when calculating this value.
71 // Here are some examples for what the votesRequired would be for n
73 // 0 peers = 1 votesRequired (0 + 1) / 2 + 1 = 1
74 // 2 peers = 2 votesRequired (2 + 1) / 2 + 1 = 2
75 // 4 peers = 3 votesRequired (4 + 1) / 2 + 1 = 3
76 int noOfPeers = peerPaths.size();
78 votesRequired = (noOfPeers + self) / 2 + 1;
84 scheduleElection(electionDuration());
87 @Override protected RaftState handleAppendEntries(ActorRef sender,
88 AppendEntries appendEntries) {
93 @Override protected RaftState handleAppendEntriesReply(ActorRef sender,
94 AppendEntriesReply appendEntriesReply) {
99 @Override protected RaftState handleRequestVoteReply(ActorRef sender,
100 RequestVoteReply requestVoteReply) {
102 if (requestVoteReply.isVoteGranted()) {
106 if (voteCount >= votesRequired) {
107 return RaftState.Leader;
113 @Override public RaftState state() {
114 return RaftState.Candidate;
118 public RaftState handleMessage(ActorRef sender, Object message) {
120 if (message instanceof RaftRPC) {
121 RaftRPC rpc = (RaftRPC) message;
122 // If RPC request or response contains term T > currentTerm:
123 // set currentTerm = T, convert to follower (§5.1)
124 // This applies to all RPC messages and responses
125 if (rpc.getTerm() > context.getTermInformation().getCurrentTerm()) {
126 context.getTermInformation().updateAndPersist(rpc.getTerm(), null);
127 return RaftState.Follower;
131 if (message instanceof ElectionTimeout) {
132 if (votesRequired == 0) {
133 // If there are no peers then we should be a Leader
134 // We wait for the election timeout to occur before declare
135 // ourselves the leader. This gives enough time for a leader
136 // who we do not know about (as a peer)
137 // to send a message to the candidate
138 return RaftState.Leader;
141 scheduleElection(electionDuration());
144 return super.handleMessage(sender, message);
148 private void startNewTerm() {
151 // set voteCount back to 1 (that is voting for self)
154 // Increment the election term and vote for self
155 long currentTerm = context.getTermInformation().getCurrentTerm();
156 context.getTermInformation().updateAndPersist(currentTerm + 1, context.getId());
158 context.getLogger().debug("Starting new term " + (currentTerm+1));
160 // Request for a vote
161 // TODO: Retry request for vote if replies do not arrive in a reasonable
162 // amount of time TBD
163 for (ActorSelection peerActor : peerToActor.values()) {
164 peerActor.tell(new RequestVote(
165 context.getTermInformation().getCurrentTerm(),
167 context.getReplicatedLog().lastIndex(),
168 context.getReplicatedLog().lastTerm()),
176 @Override public void close() throws Exception {