2 * Copyright (c) 2014, 2015 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 static org.junit.Assert.assertEquals;
12 import static org.junit.Assert.assertTrue;
13 import akka.actor.ActorRef;
14 import akka.actor.Props;
15 import akka.testkit.TestActorRef;
16 import com.google.common.base.Stopwatch;
17 import java.util.ArrayList;
18 import java.util.Collections;
19 import java.util.HashMap;
20 import java.util.List;
22 import java.util.concurrent.TimeUnit;
23 import org.junit.After;
24 import org.junit.Before;
25 import org.junit.Test;
26 import org.mockito.Mockito;
27 import org.opendaylight.controller.cluster.NonPersistentDataProvider;
28 import org.opendaylight.controller.cluster.raft.DefaultConfigParamsImpl;
29 import org.opendaylight.controller.cluster.raft.ElectionTerm;
30 import org.opendaylight.controller.cluster.raft.MockRaftActorContext;
31 import org.opendaylight.controller.cluster.raft.RaftActorContext;
32 import org.opendaylight.controller.cluster.raft.RaftActorContextImpl;
33 import org.opendaylight.controller.cluster.raft.RaftState;
34 import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
35 import org.opendaylight.controller.cluster.raft.VotingState;
36 import org.opendaylight.controller.cluster.raft.base.messages.ElectionTimeout;
37 import org.opendaylight.controller.cluster.raft.messages.AppendEntries;
38 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
39 import org.opendaylight.controller.cluster.raft.messages.RaftRPC;
40 import org.opendaylight.controller.cluster.raft.messages.RequestVote;
41 import org.opendaylight.controller.cluster.raft.messages.RequestVoteReply;
42 import org.opendaylight.controller.cluster.raft.utils.MessageCollectorActor;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
46 public class CandidateTest extends AbstractRaftActorBehaviorTest<Candidate> {
47 static final Logger LOG = LoggerFactory.getLogger(CandidateTest.class);
49 private final TestActorRef<MessageCollectorActor> candidateActor = actorFactory.createTestActor(
50 Props.create(MessageCollectorActor.class), actorFactory.generateActorId("candidate"));
52 private TestActorRef<MessageCollectorActor>[] peerActors;
54 private RaftActorBehavior candidate;
62 public void tearDown() throws Exception {
63 if(candidate != null) {
71 public void testWhenACandidateIsCreatedItIncrementsTheCurrentTermAndVotesForItself(){
72 RaftActorContext raftActorContext = createActorContext();
73 long expectedTerm = raftActorContext.getTermInformation().getCurrentTerm();
75 candidate = new Candidate(raftActorContext);
77 assertEquals("getCurrentTerm", expectedTerm+1, raftActorContext.getTermInformation().getCurrentTerm());
78 assertEquals("getVotedFor", raftActorContext.getId(), raftActorContext.getTermInformation().getVotedFor());
82 public void testThatAnElectionTimeoutIsTriggered(){
83 MockRaftActorContext actorContext = createActorContext();
84 candidate = new Candidate(actorContext);
86 MessageCollectorActor.expectFirstMatching(candidateActor, ElectionTimeout.class,
87 actorContext.getConfigParams().getElectionTimeOutInterval().$times(6).toMillis());
91 public void testHandleElectionTimeoutWhenThereAreZeroPeers(){
92 RaftActorContext raftActorContext = createActorContext();
93 candidate = new Candidate(raftActorContext);
95 RaftActorBehavior newBehavior =
96 candidate.handleMessage(candidateActor, ElectionTimeout.INSTANCE);
98 assertEquals("Behavior", RaftState.Leader, newBehavior.state());
102 public void testHandleElectionTimeoutWhenThereAreTwoNodeCluster(){
103 MockRaftActorContext raftActorContext = createActorContext();
104 raftActorContext.setPeerAddresses(setupPeers(1));
105 candidate = new Candidate(raftActorContext);
107 candidate = candidate.handleMessage(candidateActor, ElectionTimeout.INSTANCE);
109 assertEquals("Behavior", RaftState.Candidate, candidate.state());
113 public void testBecomeLeaderOnReceivingMajorityVotesInThreeNodeCluster(){
114 MockRaftActorContext raftActorContext = createActorContext();
115 raftActorContext.setLastApplied(raftActorContext.getReplicatedLog().lastIndex());
116 raftActorContext.setPeerAddresses(setupPeers(2));
117 candidate = new Candidate(raftActorContext);
119 candidate = candidate.handleMessage(peerActors[0], new RequestVoteReply(1, true));
121 assertEquals("Behavior", RaftState.Leader, candidate.state());
125 public void testBecomePreLeaderOnReceivingMajorityVotesInThreeNodeCluster(){
126 MockRaftActorContext raftActorContext = createActorContext();
127 raftActorContext.setPeerAddresses(setupPeers(2));
128 candidate = new Candidate(raftActorContext);
130 candidate = candidate.handleMessage(peerActors[0], new RequestVoteReply(1, true));
132 // LastApplied is -1 and behind the last index.
133 assertEquals("Behavior", RaftState.PreLeader, candidate.state());
137 public void testBecomeLeaderOnReceivingMajorityVotesInFiveNodeCluster(){
138 MockRaftActorContext raftActorContext = createActorContext();
139 raftActorContext.getTermInformation().update(2L, "other");
140 raftActorContext.setReplicatedLog(new MockRaftActorContext.MockReplicatedLogBuilder().
141 createEntries(0, 5, 1).build());
142 raftActorContext.setCommitIndex(raftActorContext.getReplicatedLog().lastIndex());
143 raftActorContext.setLastApplied(raftActorContext.getReplicatedLog().lastIndex());
144 raftActorContext.setPeerAddresses(setupPeers(4));
145 candidate = new Candidate(raftActorContext);
147 RequestVote requestVote = MessageCollectorActor.expectFirstMatching(peerActors[0], RequestVote.class);
148 assertEquals("getTerm", 3L, requestVote.getTerm());
149 assertEquals("getCandidateId", raftActorContext.getId(), requestVote.getCandidateId());
150 assertEquals("getLastLogTerm", 1L, requestVote.getLastLogTerm());
151 assertEquals("getLastLogIndex", 4L, requestVote.getLastLogIndex());
153 MessageCollectorActor.expectFirstMatching(peerActors[1], RequestVote.class);
154 MessageCollectorActor.expectFirstMatching(peerActors[2], RequestVote.class);
155 MessageCollectorActor.expectFirstMatching(peerActors[3], RequestVote.class);
157 // First peers denies the vote.
158 candidate = candidate.handleMessage(peerActors[0], new RequestVoteReply(1, false));
160 assertEquals("Behavior", RaftState.Candidate, candidate.state());
162 candidate = candidate.handleMessage(peerActors[1], new RequestVoteReply(1, true));
164 assertEquals("Behavior", RaftState.Candidate, candidate.state());
166 candidate = candidate.handleMessage(peerActors[2], new RequestVoteReply(1, true));
168 assertEquals("Behavior", RaftState.Leader, candidate.state());
172 public void testBecomeLeaderOnReceivingMajorityVotesWithNonVotingPeers(){
173 ElectionTerm mockElectionTerm = Mockito.mock(ElectionTerm.class);
174 Mockito.doReturn(1L).when(mockElectionTerm).getCurrentTerm();
175 RaftActorContext raftActorContext = new RaftActorContextImpl(candidateActor, candidateActor.actorContext(),
176 "candidate", mockElectionTerm, -1, -1, setupPeers(4), new DefaultConfigParamsImpl(),
177 new NonPersistentDataProvider(), LOG);
178 raftActorContext.setReplicatedLog(new MockRaftActorContext.MockReplicatedLogBuilder().build());
179 raftActorContext.getPeerInfo("peer1").setVotingState(VotingState.NON_VOTING);
180 raftActorContext.getPeerInfo("peer4").setVotingState(VotingState.NON_VOTING);
181 candidate = new Candidate(raftActorContext);
183 MessageCollectorActor.expectFirstMatching(peerActors[1], RequestVote.class);
184 MessageCollectorActor.expectFirstMatching(peerActors[2], RequestVote.class);
185 MessageCollectorActor.assertNoneMatching(peerActors[0], RequestVote.class, 300);
186 MessageCollectorActor.assertNoneMatching(peerActors[3], RequestVote.class, 100);
188 candidate = candidate.handleMessage(peerActors[1], new RequestVoteReply(1, false));
190 assertEquals("Behavior", RaftState.Candidate, candidate.state());
192 candidate = candidate.handleMessage(peerActors[2], new RequestVoteReply(1, true));
194 assertEquals("Behavior", RaftState.Leader, candidate.state());
198 public void testResponseToHandleAppendEntriesWithLowerTerm() {
199 candidate = new Candidate(createActorContext());
202 RaftActorBehavior newBehavior = candidate.handleMessage(peerActors[0], new AppendEntries(1, "test", 0, 0,
203 Collections.<ReplicatedLogEntry>emptyList(), 0, -1, (short) 0));
205 AppendEntriesReply reply = MessageCollectorActor.expectFirstMatching(
206 peerActors[0], AppendEntriesReply.class);
207 assertEquals("isSuccess", false, reply.isSuccess());
208 assertEquals("getTerm", 2, reply.getTerm());
209 assertTrue("New Behavior : " + newBehavior, newBehavior instanceof Candidate);
213 public void testResponseToHandleAppendEntriesWithHigherTerm() {
214 candidate = new Candidate(createActorContext());
217 RaftActorBehavior newBehavior = candidate.handleMessage(peerActors[0], new AppendEntries(5, "test", 0, 0,
218 Collections.<ReplicatedLogEntry>emptyList(), 0, -1, (short) 0));
220 assertTrue("New Behavior : " + newBehavior, newBehavior instanceof Follower);
224 public void testResponseToHandleAppendEntriesWithEqualTerm() {
225 MockRaftActorContext actorContext = createActorContext();
227 candidate = new Candidate(actorContext);
230 RaftActorBehavior newBehavior = candidate.handleMessage(peerActors[0], new AppendEntries(2, "test", 0, 0,
231 Collections.<ReplicatedLogEntry>emptyList(), 0, -1, (short) 0));
233 assertTrue("New Behavior : " + newBehavior + " term = " + actorContext.getTermInformation().getCurrentTerm(),
234 newBehavior instanceof Follower);
239 public void testResponseToRequestVoteWithLowerTerm() {
240 candidate = new Candidate(createActorContext());
243 candidate.handleMessage(peerActors[0], new RequestVote(1, "test", 0, 0));
245 RequestVoteReply reply = MessageCollectorActor.expectFirstMatching(
246 peerActors[0], RequestVoteReply.class);
247 assertEquals("isVoteGranted", false, reply.isVoteGranted());
248 assertEquals("getTerm", 2, reply.getTerm());
252 public void testHandleRequestVoteWhenSenderTermEqualToCurrentTermAndVotedForMatches() {
253 MockRaftActorContext context = createActorContext();
254 context.getTermInformation().update(1000, null);
256 // Once a candidate is created it will immediately increment the current term so after
257 // construction the currentTerm should be 1001
258 candidate = new Candidate(context);
261 candidate.handleMessage(peerActors[0], new RequestVote(1001, context.getId(), 10000, 999));
263 RequestVoteReply reply = MessageCollectorActor.expectFirstMatching(
264 peerActors[0], RequestVoteReply.class);
265 assertEquals("isVoteGranted", true, reply.isVoteGranted());
266 assertEquals("getTerm", 1001, reply.getTerm());
270 public void testHandleRequestVoteWhenSenderTermEqualToCurrentTermAndVotedForDoesNotMatch() {
271 MockRaftActorContext context = createActorContext();
272 context.getTermInformation().update(1000, null);
274 // Once a candidate is created it will immediately increment the current term so after
275 // construction the currentTerm should be 1001
276 candidate = new Candidate(context);
280 // RequestVote candidate ID ("candidate2") does not match this candidate's votedFor
281 // (it votes for itself)
282 candidate.handleMessage(peerActors[0], new RequestVote(1001, "candidate2", 10000, 999));
284 RequestVoteReply reply = MessageCollectorActor.expectFirstMatching(
285 peerActors[0], RequestVoteReply.class);
286 assertEquals("isVoteGranted", false, reply.isVoteGranted());
287 assertEquals("getTerm", 1001, reply.getTerm());
291 public void testCandidateSchedulesElectionTimeoutImmediatelyWhenItHasNoPeers(){
292 MockRaftActorContext context = createActorContext();
294 Stopwatch stopwatch = Stopwatch.createStarted();
296 candidate = createBehavior(context);
298 MessageCollectorActor.expectFirstMatching(candidateActor, ElectionTimeout.class);
300 long elapsed = stopwatch.elapsed(TimeUnit.MILLISECONDS);
302 assertTrue(elapsed < context.getConfigParams().getElectionTimeOutInterval().toMillis());
307 public void testHandleAppendEntriesAddSameEntryToLog() throws Exception {
308 MockRaftActorContext context = createActorContext();
310 context.getTermInformation().update(2, "test");
312 // Prepare the receivers log
313 MockRaftActorContext.MockPayload payload = new MockRaftActorContext.MockPayload("zero");
314 setLastLogEntry(context, 2, 0, payload);
316 List<ReplicatedLogEntry> entries = new ArrayList<>();
317 entries.add(new MockRaftActorContext.MockReplicatedLogEntry(2, 0, payload));
319 AppendEntries appendEntries = new AppendEntries(2, "leader-1", -1, -1, entries, 2, -1, (short)0);
321 behavior = createBehavior(context);
323 // Resetting the Candidates term to make sure it will match
324 // the term sent by AppendEntries. If this was not done then
325 // the test will fail because the Candidate will assume that
326 // the message was sent to it from a lower term peer and will
327 // thus respond with a failure
328 context.getTermInformation().update(2, "test");
330 // Send an unknown message so that the state of the RaftActor remains unchanged
331 behavior.handleMessage(candidateActor, "unknown");
333 RaftActorBehavior raftBehavior = behavior.handleMessage(candidateActor, appendEntries);
335 assertEquals("Raft state", RaftState.Follower, raftBehavior.state());
337 assertEquals("ReplicatedLog size", 1, context.getReplicatedLog().size());
339 handleAppendEntriesAddSameEntryToLogReply(candidateActor);
343 protected Candidate createBehavior(final RaftActorContext actorContext) {
344 return new Candidate(actorContext);
347 @Override protected MockRaftActorContext createActorContext() {
348 return new MockRaftActorContext("candidate", getSystem(), candidateActor);
351 @SuppressWarnings("unchecked")
352 private Map<String, String> setupPeers(final int count) {
353 Map<String, String> peerMap = new HashMap<>();
354 peerActors = new TestActorRef[count];
355 for(int i = 0; i < count; i++) {
356 peerActors[i] = actorFactory.createTestActor(Props.create(MessageCollectorActor.class),
357 actorFactory.generateActorId("peer"));
358 peerMap.put("peer" + (i+1), peerActors[i].path().toString());
365 protected void assertStateChangesToFollowerWhenRaftRPCHasNewerTerm(final MockRaftActorContext actorContext,
366 final ActorRef actorRef, final RaftRPC rpc) throws Exception {
367 super.assertStateChangesToFollowerWhenRaftRPCHasNewerTerm(actorContext, actorRef, rpc);
368 if(rpc instanceof RequestVote) {
369 assertEquals("New votedFor", ((RequestVote)rpc).getCandidateId(), actorContext.getTermInformation().getVotedFor());
371 assertEquals("New votedFor", null, actorContext.getTermInformation().getVotedFor());