Test RaftActor using a simple program
[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 org.opendaylight.controller.cluster.raft.RaftActorContext;
14 import org.opendaylight.controller.cluster.raft.RaftState;
15 import org.opendaylight.controller.cluster.raft.internal.messages.ElectionTimeout;
16 import org.opendaylight.controller.cluster.raft.messages.AppendEntries;
17 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
18 import org.opendaylight.controller.cluster.raft.messages.RequestVote;
19 import org.opendaylight.controller.cluster.raft.messages.RequestVoteReply;
20
21 import java.util.Collection;
22 import java.util.HashMap;
23 import java.util.Map;
24
25 /**
26  * The behavior of a RaftActor when it is in the CandidateState
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 final Map<String, ActorSelection> peerToActor = new HashMap<>();
46
47     private int voteCount;
48
49     private final int votesRequired;
50
51     public Candidate(RaftActorContext context) {
52         super(context);
53
54         Collection<String> peerPaths = context.getPeerAddresses().values();
55
56         for (String peerPath : peerPaths) {
57             peerToActor.put(peerPath,
58                 context.actorSelection(peerPath));
59         }
60
61         if(peerPaths.size() > 0) {
62             // Votes are required from a majority of the peers including self.
63             // The votesRequired field therefore stores a calculated value
64             // of the number of votes required for this candidate to win an
65             // election based on it's known peers.
66             // If a peer was added during normal operation and raft replicas
67             // came to know about them then the new peer would also need to be
68             // taken into consideration when calculating this value.
69             // Here are some examples for what the votesRequired would be for n
70             // peers
71             // 0 peers = 1 votesRequired (0 + 1) / 2 + 1 = 1
72             // 2 peers = 2 votesRequired (2 + 1) / 2 + 1 = 2
73             // 4 peers = 3 votesRequired (4 + 1) / 2 + 1 = 3
74             int noOfPeers = peerPaths.size();
75             int self = 1;
76             votesRequired = (noOfPeers + self) / 2 + 1;
77         } else {
78             votesRequired = 0;
79         }
80
81         startNewTerm();
82         scheduleElection(electionDuration());
83     }
84
85     @Override protected RaftState handleAppendEntries(ActorRef sender,
86         AppendEntries appendEntries, RaftState suggestedState) {
87
88         context.getLogger().error("An unexpected AppendEntries received in state " + state());
89
90         return suggestedState;
91     }
92
93     @Override protected RaftState handleAppendEntriesReply(ActorRef sender,
94         AppendEntriesReply appendEntriesReply, RaftState suggestedState) {
95
96         // Some peer thinks I was a leader and sent me a reply
97
98         return suggestedState;
99     }
100
101     @Override protected RaftState handleRequestVoteReply(ActorRef sender,
102         RequestVoteReply requestVoteReply, RaftState suggestedState) {
103         if (suggestedState == RaftState.Follower) {
104             // If base class thinks I should be follower then I am
105             return suggestedState;
106         }
107
108         if (requestVoteReply.isVoteGranted()) {
109             voteCount++;
110         }
111
112         if (voteCount >= votesRequired) {
113             return RaftState.Leader;
114         }
115
116         return state();
117     }
118
119     @Override public RaftState state() {
120         return RaftState.Candidate;
121     }
122
123     @Override
124     public RaftState handleMessage(ActorRef sender, Object message) {
125         if (message instanceof ElectionTimeout) {
126             if (votesRequired == 0) {
127                 // If there are no peers then we should be a Leader
128                 // We wait for the election timeout to occur before declare
129                 // ourselves the leader. This gives enough time for a leader
130                 // who we do not know about (as a peer)
131                 // to send a message to the candidate
132                 return RaftState.Leader;
133             }
134             startNewTerm();
135             scheduleElection(electionDuration());
136             return state();
137         }
138         return super.handleMessage(sender, message);
139     }
140
141
142     private void startNewTerm() {
143
144
145         // set voteCount back to 1 (that is voting for self)
146         voteCount = 1;
147
148         // Increment the election term and vote for self
149         long currentTerm = context.getTermInformation().getCurrentTerm();
150         context.getTermInformation().update(currentTerm + 1, context.getId());
151
152         context.getLogger().debug("Starting new term " + (currentTerm+1));
153
154         // Request for a vote
155         for (ActorSelection peerActor : peerToActor.values()) {
156             peerActor.tell(new RequestVote(
157                     context.getTermInformation().getCurrentTerm(),
158                     context.getId(),
159                     context.getReplicatedLog().lastIndex(),
160                     context.getReplicatedLog().lastTerm()),
161                 context.getActor()
162             );
163         }
164
165
166     }
167
168     @Override public void close() throws Exception {
169         stopElection();
170     }
171 }