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;
26 * The behavior of a RaftActor when it is in the Candidate raft state.
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 int voteCount;
48 private final int votesRequired;
50 private final Collection<String> votingPeers = new ArrayList<>();
52 public Candidate(RaftActorContext context) {
53 super(context, RaftState.Candidate);
55 for (PeerInfo peer: context.getPeers()) {
56 if (peer.isVoting()) {
57 votingPeers.add(peer.getId());
61 log.debug("{}: Election: Candidate has following voting peers: {}", logName(), votingPeers);
63 votesRequired = getMajorityVoteCount(votingPeers.size());
67 if (votingPeers.isEmpty()) {
68 actor().tell(ElectionTimeout.INSTANCE, actor());
70 scheduleElection(electionDuration());
75 public final String getLeaderId() {
80 public final short getLeaderPayloadVersion() {
85 protected RaftActorBehavior handleAppendEntries(ActorRef sender, AppendEntries appendEntries) {
87 log.debug("{}: handleAppendEntries: {}", logName(), appendEntries);
89 // Some other candidate for the same term became a leader and sent us an append entry
90 if (currentTerm() == appendEntries.getTerm()) {
91 log.info("{}: New Leader {} sent an AppendEntries to Candidate for term {} - will switch to Follower",
92 logName(), appendEntries.getLeaderId(), currentTerm());
94 return switchBehavior(new Follower(context));
101 protected RaftActorBehavior handleAppendEntriesReply(ActorRef sender, AppendEntriesReply appendEntriesReply) {
106 protected RaftActorBehavior handleRequestVoteReply(ActorRef sender, RequestVoteReply requestVoteReply) {
107 log.debug("{}: handleRequestVoteReply: {}, current voteCount: {}", logName(), requestVoteReply, voteCount);
109 if (requestVoteReply.isVoteGranted()) {
113 if (voteCount >= votesRequired) {
114 if (context.getLastApplied() < context.getReplicatedLog().lastIndex()) {
115 log.info("{}: LastApplied index {} is behind last index {} - switching to PreLeader",
116 logName(), context.getLastApplied(), context.getReplicatedLog().lastIndex());
117 return internalSwitchBehavior(RaftState.PreLeader);
119 return internalSwitchBehavior(RaftState.Leader);
127 public RaftActorBehavior handleMessage(ActorRef sender, Object message) {
128 if (message instanceof ElectionTimeout) {
129 log.debug("{}: Received ElectionTimeout", logName());
131 if (votesRequired == 0) {
132 // If there are no peers then we should be a Leader
133 // We wait for the election timeout to occur before declare
134 // ourselves the leader. This gives enough time for a leader
135 // who we do not know about (as a peer)
136 // to send a message to the candidate
138 return internalSwitchBehavior(RaftState.Leader);
142 scheduleElection(electionDuration());
146 if (message instanceof RaftRPC) {
148 RaftRPC rpc = (RaftRPC) message;
150 log.debug("{}: RaftRPC message received {}, my term is {}", logName(), rpc,
151 context.getTermInformation().getCurrentTerm());
153 // If RPC request or response contains term T > currentTerm:
154 // set currentTerm = T, convert to follower (§5.1)
155 // This applies to all RPC messages and responses
156 if (rpc.getTerm() > context.getTermInformation().getCurrentTerm()) {
157 log.info("{}: Term {} in \"{}\" message is greater than Candidate's term {} - switching to Follower",
158 logName(), rpc.getTerm(), rpc, context.getTermInformation().getCurrentTerm());
160 context.getTermInformation().updateAndPersist(rpc.getTerm(), null);
162 // The raft paper does not say whether or not a Candidate can/should process a RequestVote in
163 // this case but doing so gains quicker convergence when the sender's log is more up-to-date.
164 if (message instanceof RequestVote) {
165 super.handleMessage(sender, message);
168 return internalSwitchBehavior(RaftState.Follower);
172 return super.handleMessage(sender, message);
176 private void startNewTerm() {
179 // set voteCount back to 1 (that is voting for self)
182 // Increment the election term and vote for self
183 long currentTerm = context.getTermInformation().getCurrentTerm();
184 long newTerm = currentTerm + 1;
185 context.getTermInformation().updateAndPersist(newTerm, context.getId());
187 log.info("{}: Starting new election term {}", logName(), newTerm);
189 // Request for a vote
190 // TODO: Retry request for vote if replies do not arrive in a reasonable
191 // amount of time TBD
192 for (String peerId : votingPeers) {
193 ActorSelection peerActor = context.getPeerActorSelection(peerId);
194 if (peerActor != null) {
195 RequestVote requestVote = new RequestVote(
196 context.getTermInformation().getCurrentTerm(),
198 context.getReplicatedLog().lastIndex(),
199 context.getReplicatedLog().lastTerm());
201 log.debug("{}: Sending {} to peer {}", logName(), requestVote, peerId);
203 peerActor.tell(requestVote, context.getActor());
209 public void close() {