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 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 import scala.concurrent.duration.FiniteDuration;
27 * The behavior of a RaftActor when it is in the Candidate raft state.
32 * <li> On conversion to candidate, start election:
34 * <li> Increment currentTerm
36 * <li> Reset election timer
37 * <li> Send RequestVote RPCs to all other servers
39 * <li> If votes received from majority of servers: become leader
40 * <li> If AppendEntries RPC received from new leader: convert to
42 * <li> If election timeout elapses: start new election
45 public class Candidate extends AbstractRaftActorBehavior {
47 private int voteCount;
49 private final int votesRequired;
51 private final Collection<String> votingPeers = new ArrayList<>();
53 public Candidate(RaftActorContext context) {
54 super(context, RaftState.Candidate);
56 for (PeerInfo peer: context.getPeers()) {
57 if (peer.isVoting()) {
58 votingPeers.add(peer.getId());
62 log.debug("{}: Election: Candidate has following voting peers: {}", logName(), votingPeers);
64 votesRequired = getMajorityVoteCount(votingPeers.size());
68 if (votingPeers.isEmpty()) {
69 actor().tell(ElectionTimeout.INSTANCE, actor());
71 scheduleElection(electionDuration());
76 public final String getLeaderId() {
81 public final short getLeaderPayloadVersion() {
86 protected RaftActorBehavior handleAppendEntries(ActorRef sender, AppendEntries appendEntries) {
88 log.debug("{}: handleAppendEntries: {}", logName(), appendEntries);
90 // Some other candidate for the same term became a leader and sent us an append entry
91 if (currentTerm() == appendEntries.getTerm()) {
92 log.info("{}: New Leader {} sent an AppendEntries to Candidate for term {} - will switch to Follower",
93 logName(), appendEntries.getLeaderId(), currentTerm());
95 return switchBehavior(new Follower(context));
102 protected RaftActorBehavior handleAppendEntriesReply(ActorRef sender, AppendEntriesReply appendEntriesReply) {
107 protected RaftActorBehavior handleRequestVoteReply(ActorRef sender, RequestVoteReply requestVoteReply) {
108 log.debug("{}: handleRequestVoteReply: {}, current voteCount: {}", logName(), requestVoteReply, voteCount);
110 if (requestVoteReply.isVoteGranted()) {
114 if (voteCount >= votesRequired) {
115 if (context.getLastApplied() < context.getReplicatedLog().lastIndex()) {
116 log.info("{}: LastApplied index {} is behind last index {} - switching to PreLeader",
117 logName(), context.getLastApplied(), context.getReplicatedLog().lastIndex());
118 return internalSwitchBehavior(RaftState.PreLeader);
120 return internalSwitchBehavior(RaftState.Leader);
128 protected FiniteDuration electionDuration() {
129 return super.electionDuration().$div(context.getConfigParams().getCandidateElectionTimeoutDivisor());
133 public RaftActorBehavior handleMessage(ActorRef sender, Object message) {
134 if (message instanceof ElectionTimeout) {
135 log.debug("{}: Received ElectionTimeout", logName());
137 if (votesRequired == 0) {
138 // If there are no peers then we should be a Leader
139 // We wait for the election timeout to occur before declare
140 // ourselves the leader. This gives enough time for a leader
141 // who we do not know about (as a peer)
142 // to send a message to the candidate
144 return internalSwitchBehavior(RaftState.Leader);
148 scheduleElection(electionDuration());
152 if (message instanceof RaftRPC) {
154 RaftRPC rpc = (RaftRPC) message;
156 log.debug("{}: RaftRPC message received {}, my term is {}", logName(), rpc,
157 context.getTermInformation().getCurrentTerm());
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 log.info("{}: Term {} in \"{}\" message is greater than Candidate's term {} - switching to Follower",
164 logName(), rpc.getTerm(), rpc, context.getTermInformation().getCurrentTerm());
166 context.getTermInformation().updateAndPersist(rpc.getTerm(), null);
168 // The raft paper does not say whether or not a Candidate can/should process a RequestVote in
169 // this case but doing so gains quicker convergence when the sender's log is more up-to-date.
170 if (message instanceof RequestVote) {
171 super.handleMessage(sender, message);
174 return internalSwitchBehavior(RaftState.Follower);
178 return super.handleMessage(sender, message);
182 private void startNewTerm() {
185 // set voteCount back to 1 (that is voting for self)
188 // Increment the election term and vote for self
189 long currentTerm = context.getTermInformation().getCurrentTerm();
190 long newTerm = currentTerm + 1;
191 context.getTermInformation().updateAndPersist(newTerm, context.getId());
193 log.info("{}: Starting new election term {}", logName(), newTerm);
195 // Request for a vote
196 // TODO: Retry request for vote if replies do not arrive in a reasonable
197 // amount of time TBD
198 for (String peerId : votingPeers) {
199 ActorSelection peerActor = context.getPeerActorSelection(peerId);
200 if (peerActor != null) {
201 RequestVote requestVote = new RequestVote(
202 context.getTermInformation().getCurrentTerm(),
204 context.getReplicatedLog().lastIndex(),
205 context.getReplicatedLog().lastTerm());
207 log.debug("{}: Sending {} to peer {}", logName(), requestVote, peerId);
209 peerActor.tell(requestVote, context.getActor());
215 public void close() {