Fix warnings and clean up javadocs in sal-akka-raft
[controller.git] / opendaylight / md-sal / sal-akka-raft / src / main / java / org / opendaylight / controller / cluster / raft / behaviors / Candidate.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8
9 package org.opendaylight.controller.cluster.raft.behaviors;
10
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
25 /**
26  * The behavior of a RaftActor when it is in the Candidate raft state.
27  * <p/>
28  * Candidates (§5.2):
29  * <ul>
30  * <li> On conversion to candidate, start election:
31  * <ul>
32  * <li> Increment currentTerm
33  * <li> Vote for self
34  * <li> Reset election timer
35  * <li> Send RequestVote RPCs to all other servers
36  * </ul>
37  * <li> If votes received from majority of servers: become leader
38  * <li> If AppendEntries RPC received from new leader: convert to
39  * follower
40  * <li> If election timeout elapses: start new election
41  * </ul>
42  */
43 public class Candidate extends AbstractRaftActorBehavior {
44
45     private int voteCount;
46
47     private final int votesRequired;
48
49     private final Collection<String> votingPeers = new ArrayList<>();
50
51     public Candidate(RaftActorContext context) {
52         super(context, RaftState.Candidate);
53
54         for (PeerInfo peer: context.getPeers()) {
55             if (peer.isVoting()) {
56                 votingPeers.add(peer.getId());
57             }
58         }
59
60         log.debug("{}: Election: Candidate has following voting peers: {}", logName(), votingPeers);
61
62         votesRequired = getMajorityVoteCount(votingPeers.size());
63
64         startNewTerm();
65
66         if (votingPeers.isEmpty()) {
67             actor().tell(ElectionTimeout.INSTANCE, actor());
68         } else {
69             scheduleElection(electionDuration());
70         }
71     }
72
73     @Override
74     public final String getLeaderId() {
75         return null;
76     }
77
78     @Override
79     public final short getLeaderPayloadVersion() {
80         return -1;
81     }
82
83     @Override
84     protected RaftActorBehavior handleAppendEntries(ActorRef sender, AppendEntries appendEntries) {
85
86         log.debug("{}: handleAppendEntries: {}", logName(), appendEntries);
87
88         // Some other candidate for the same term became a leader and sent us an append entry
89         if (currentTerm() == appendEntries.getTerm()) {
90             log.debug("{}: New Leader sent an append entry to Candidate for term {} will switch to Follower",
91                     logName(), currentTerm());
92
93             return switchBehavior(new Follower(context));
94         }
95
96         return this;
97     }
98
99     @Override
100     protected RaftActorBehavior handleAppendEntriesReply(ActorRef sender, AppendEntriesReply appendEntriesReply) {
101         return this;
102     }
103
104     @Override
105     protected RaftActorBehavior handleRequestVoteReply(ActorRef sender, RequestVoteReply requestVoteReply) {
106         log.debug("{}: handleRequestVoteReply: {}, current voteCount: {}", logName(), requestVoteReply, voteCount);
107
108         if (requestVoteReply.isVoteGranted()) {
109             voteCount++;
110         }
111
112         if (voteCount >= votesRequired) {
113             if (context.getLastApplied() < context.getReplicatedLog().lastIndex()) {
114                 log.debug("{}: LastApplied index {} is behind last index {}", logName(), context.getLastApplied(),
115                         context.getReplicatedLog().lastIndex());
116                 return internalSwitchBehavior(RaftState.PreLeader);
117             } else {
118                 return internalSwitchBehavior(RaftState.Leader);
119             }
120         }
121
122         return this;
123     }
124
125     @Override
126     public RaftActorBehavior handleMessage(ActorRef sender, Object message) {
127         if (message instanceof ElectionTimeout) {
128             log.debug("{}: Received ElectionTimeout", logName());
129
130             if (votesRequired == 0) {
131                 // If there are no peers then we should be a Leader
132                 // We wait for the election timeout to occur before declare
133                 // ourselves the leader. This gives enough time for a leader
134                 // who we do not know about (as a peer)
135                 // to send a message to the candidate
136
137                 return internalSwitchBehavior(RaftState.Leader);
138             }
139
140             startNewTerm();
141             scheduleElection(electionDuration());
142             return this;
143         }
144
145         if (message instanceof RaftRPC) {
146
147             RaftRPC rpc = (RaftRPC) message;
148
149             log.debug("{}: RaftRPC message received {}, my term is {}", logName(), rpc,
150                         context.getTermInformation().getCurrentTerm());
151
152             // If RPC request or response contains term T > currentTerm:
153             // set currentTerm = T, convert to follower (§5.1)
154             // This applies to all RPC messages and responses
155             if (rpc.getTerm() > context.getTermInformation().getCurrentTerm()) {
156                 context.getTermInformation().updateAndPersist(rpc.getTerm(), null);
157
158                 // The raft paper does not say whether or not a Candidate can/should process a RequestVote in
159                 // this case but doing so gains quicker convergence when the sender's log is more up-to-date.
160                 if (message instanceof RequestVote) {
161                     super.handleMessage(sender, message);
162                 }
163
164                 return internalSwitchBehavior(RaftState.Follower);
165             }
166         }
167
168         return super.handleMessage(sender, message);
169     }
170
171
172     private void startNewTerm() {
173
174
175         // set voteCount back to 1 (that is voting for self)
176         voteCount = 1;
177
178         // Increment the election term and vote for self
179         long currentTerm = context.getTermInformation().getCurrentTerm();
180         long newTerm = currentTerm + 1;
181         context.getTermInformation().updateAndPersist(newTerm, context.getId());
182
183         log.debug("{}: Starting new term {}", logName(), newTerm);
184
185         // Request for a vote
186         // TODO: Retry request for vote if replies do not arrive in a reasonable
187         // amount of time TBD
188         for (String peerId : votingPeers) {
189             ActorSelection peerActor = context.getPeerActorSelection(peerId);
190             if (peerActor != null) {
191                 RequestVote requestVote = new RequestVote(
192                         context.getTermInformation().getCurrentTerm(),
193                         context.getId(),
194                         context.getReplicatedLog().lastIndex(),
195                         context.getReplicatedLog().lastTerm());
196
197                 log.debug("{}: Sending {} to peer {}", logName(), requestVote, peerId);
198
199                 peerActor.tell(requestVote, context.getActor());
200             }
201         }
202     }
203
204     @Override
205     public void close() {
206         stopElection();
207     }
208 }