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 CandidateState
30 * <li> On conversion to candidate, start election:
32 * <li> Increment currentTerm
34 * <li> Reset election timer
35 * <li> Send RequestVote RPCs to all other servers
37 * <li> If votes received from majority of servers: become leader
38 * <li> If AppendEntries RPC received from new leader: convert to
40 * <li> If election timeout elapses: start new election
43 public class Candidate extends AbstractRaftActorBehavior {
45 private int voteCount;
47 private final int votesRequired;
49 private final Collection<String> votingPeers = new ArrayList<>();
51 public Candidate(RaftActorContext context) {
52 super(context, RaftState.Candidate);
54 for(PeerInfo peer: context.getPeers()) {
56 votingPeers.add(peer.getId());
60 if(LOG.isDebugEnabled()) {
61 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,
87 AppendEntries appendEntries) {
89 if(LOG.isDebugEnabled()) {
90 LOG.debug("{}: handleAppendEntries: {}", logName(), appendEntries);
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());
98 return switchBehavior(new Follower(context));
105 protected RaftActorBehavior handleAppendEntriesReply(ActorRef sender, AppendEntriesReply appendEntriesReply) {
110 protected RaftActorBehavior handleRequestVoteReply(ActorRef sender, RequestVoteReply requestVoteReply) {
111 LOG.debug("{}: handleRequestVoteReply: {}, current voteCount: {}", logName(), requestVoteReply, voteCount);
113 if (requestVoteReply.isVoteGranted()) {
117 if (voteCount >= votesRequired) {
118 return internalSwitchBehavior(RaftState.Leader);
125 public RaftActorBehavior handleMessage(ActorRef sender, Object originalMessage) {
126 if (originalMessage instanceof ElectionTimeout) {
127 LOG.debug("{}: Received ElectionTimeout", logName());
129 if (votesRequired == 0) {
130 // If there are no peers then we should be a Leader
131 // We wait for the election timeout to occur before declare
132 // ourselves the leader. This gives enough time for a leader
133 // who we do not know about (as a peer)
134 // to send a message to the candidate
136 return internalSwitchBehavior(RaftState.Leader);
140 scheduleElection(electionDuration());
144 final Object message = fromSerializableMessage(originalMessage);
145 if (message instanceof RaftRPC) {
147 RaftRPC rpc = (RaftRPC) message;
149 if(LOG.isDebugEnabled()) {
150 LOG.debug("{}: RaftRPC message received {}, my term is {}", logName(), rpc,
151 context.getTermInformation().getCurrentTerm());
154 // If RPC request or response contains term T > currentTerm:
155 // set currentTerm = T, convert to follower (§5.1)
156 // This applies to all RPC messages and responses
157 if (rpc.getTerm() > context.getTermInformation().getCurrentTerm()) {
158 context.getTermInformation().updateAndPersist(rpc.getTerm(), null);
160 return internalSwitchBehavior(RaftState.Follower);
164 return super.handleMessage(sender, message);
168 private void startNewTerm() {
171 // set voteCount back to 1 (that is voting for self)
174 // Increment the election term and vote for self
175 long currentTerm = context.getTermInformation().getCurrentTerm();
176 long newTerm = currentTerm + 1;
177 context.getTermInformation().updateAndPersist(newTerm, context.getId());
179 LOG.debug("{}: Starting new term {}", logName(), newTerm);
181 // Request for a vote
182 // TODO: Retry request for vote if replies do not arrive in a reasonable
183 // amount of time TBD
184 for (String peerId : votingPeers) {
185 ActorSelection peerActor = context.getPeerActorSelection(peerId);
186 if(peerActor != null) {
187 RequestVote requestVote = new RequestVote(
188 context.getTermInformation().getCurrentTerm(),
190 context.getReplicatedLog().lastIndex(),
191 context.getReplicatedLog().lastTerm());
193 LOG.debug("{}: Sending {} to peer {}", logName(), requestVote, peerId);
195 peerActor.tell(requestVote, context.getActor());
201 public void close() {