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;
14 import org.opendaylight.controller.cluster.raft.RaftActorContext;
15 import org.opendaylight.controller.cluster.raft.RaftState;
16 import org.opendaylight.controller.cluster.raft.base.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.RaftRPC;
20 import org.opendaylight.controller.cluster.raft.messages.RequestVote;
21 import org.opendaylight.controller.cluster.raft.messages.RequestVoteReply;
24 * The behavior of a RaftActor when it is in the CandidateState
28 * <li> On conversion to candidate, start election:
30 * <li> Increment currentTerm
32 * <li> Reset election timer
33 * <li> Send RequestVote RPCs to all other servers
35 * <li> If votes received from majority of servers: become leader
36 * <li> If AppendEntries RPC received from new leader: convert to
38 * <li> If election timeout elapses: start new election
41 public class Candidate extends AbstractRaftActorBehavior {
43 private int voteCount;
45 private final int votesRequired;
47 private final Set<String> peers;
49 public Candidate(RaftActorContext context) {
50 super(context, RaftState.Candidate);
52 peers = context.getPeerAddresses().keySet();
54 if(LOG.isDebugEnabled()) {
55 LOG.debug("{}: Election: Candidate has following peers: {}", logName(), peers);
58 votesRequired = getMajorityVoteCount(peers.size());
62 if(context.getPeerAddresses().isEmpty()){
63 actor().tell(ELECTION_TIMEOUT, actor());
65 scheduleElection(electionDuration());
71 @Override protected RaftActorBehavior handleAppendEntries(ActorRef sender,
72 AppendEntries appendEntries) {
74 if(LOG.isDebugEnabled()) {
75 LOG.debug("{}: handleAppendEntries: {}", logName(), appendEntries);
78 // Some other candidate for the same term became a leader and sent us an append entry
79 if(currentTerm() == appendEntries.getTerm()){
80 LOG.debug("{}: New Leader sent an append entry to Candidate for term {} will switch to Follower",
81 logName(), currentTerm());
83 return switchBehavior(new Follower(context));
89 @Override protected RaftActorBehavior handleAppendEntriesReply(ActorRef sender,
90 AppendEntriesReply appendEntriesReply) {
95 @Override protected RaftActorBehavior handleRequestVoteReply(ActorRef sender,
96 RequestVoteReply requestVoteReply) {
98 LOG.debug("{}: handleRequestVoteReply: {}, current voteCount: {}", logName(), requestVoteReply,
101 if (requestVoteReply.isVoteGranted()) {
105 if (voteCount >= votesRequired) {
106 return internalSwitchBehavior(RaftState.Leader);
113 public RaftActorBehavior handleMessage(ActorRef sender, Object originalMessage) {
115 Object message = fromSerializableMessage(originalMessage);
117 if (message instanceof RaftRPC) {
119 RaftRPC rpc = (RaftRPC) message;
121 if(LOG.isDebugEnabled()) {
122 LOG.debug("{}: RaftRPC message received {}, my term is {}", logName(), rpc,
123 context.getTermInformation().getCurrentTerm());
126 // If RPC request or response contains term T > currentTerm:
127 // set currentTerm = T, convert to follower (§5.1)
128 // This applies to all RPC messages and responses
129 if (rpc.getTerm() > context.getTermInformation().getCurrentTerm()) {
130 context.getTermInformation().updateAndPersist(rpc.getTerm(), null);
132 return internalSwitchBehavior(RaftState.Follower);
136 if (message instanceof ElectionTimeout) {
137 LOG.debug("{}: Received ElectionTimeout", logName());
139 if (votesRequired == 0) {
140 // If there are no peers then we should be a Leader
141 // We wait for the election timeout to occur before declare
142 // ourselves the leader. This gives enough time for a leader
143 // who we do not know about (as a peer)
144 // to send a message to the candidate
146 return internalSwitchBehavior(RaftState.Leader);
149 scheduleElection(electionDuration());
153 return super.handleMessage(sender, message);
157 private void startNewTerm() {
160 // set voteCount back to 1 (that is voting for self)
163 // Increment the election term and vote for self
164 long currentTerm = context.getTermInformation().getCurrentTerm();
165 long newTerm = currentTerm + 1;
166 context.getTermInformation().updateAndPersist(newTerm, context.getId());
168 LOG.debug("{}: Starting new term {}", logName(), newTerm);
170 // Request for a vote
171 // TODO: Retry request for vote if replies do not arrive in a reasonable
172 // amount of time TBD
173 for (String peerId : peers) {
174 ActorSelection peerActor = context.getPeerActorSelection(peerId);
175 if(peerActor != null) {
176 RequestVote requestVote = new RequestVote(
177 context.getTermInformation().getCurrentTerm(),
179 context.getReplicatedLog().lastIndex(),
180 context.getReplicatedLog().lastTerm());
182 LOG.debug("{}: Sending {} to peer {}", logName(), requestVote, peerId);
184 peerActor.tell(requestVote, context.getActor());
189 @Override public void close() throws Exception {