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.setPeerAddresses(setupPeers(2));
116 candidate = new Candidate(raftActorContext);
118 candidate = candidate.handleMessage(peerActors[0], new RequestVoteReply(1, true));
120 assertEquals("Behavior", RaftState.Leader, candidate.state());
124 public void testBecomeLeaderOnReceivingMajorityVotesInFiveNodeCluster(){
125 MockRaftActorContext raftActorContext = createActorContext();
126 raftActorContext.getTermInformation().update(2L, "other");
127 raftActorContext.setReplicatedLog(new MockRaftActorContext.MockReplicatedLogBuilder().
128 createEntries(0, 5, 1).build());
129 raftActorContext.setPeerAddresses(setupPeers(4));
130 candidate = new Candidate(raftActorContext);
132 RequestVote requestVote = MessageCollectorActor.expectFirstMatching(peerActors[0], RequestVote.class);
133 assertEquals("getTerm", 3L, requestVote.getTerm());
134 assertEquals("getCandidateId", raftActorContext.getId(), requestVote.getCandidateId());
135 assertEquals("getLastLogTerm", 1L, requestVote.getLastLogTerm());
136 assertEquals("getLastLogIndex", 4L, requestVote.getLastLogIndex());
138 MessageCollectorActor.expectFirstMatching(peerActors[1], RequestVote.class);
139 MessageCollectorActor.expectFirstMatching(peerActors[2], RequestVote.class);
140 MessageCollectorActor.expectFirstMatching(peerActors[3], RequestVote.class);
142 // First peers denies the vote.
143 candidate = candidate.handleMessage(peerActors[0], new RequestVoteReply(1, false));
145 assertEquals("Behavior", RaftState.Candidate, candidate.state());
147 candidate = candidate.handleMessage(peerActors[1], new RequestVoteReply(1, true));
149 assertEquals("Behavior", RaftState.Candidate, candidate.state());
151 candidate = candidate.handleMessage(peerActors[2], new RequestVoteReply(1, true));
153 assertEquals("Behavior", RaftState.Leader, candidate.state());
157 public void testBecomeLeaderOnReceivingMajorityVotesWithNonVotingPeers(){
158 ElectionTerm mockElectionTerm = Mockito.mock(ElectionTerm.class);
159 Mockito.doReturn(1L).when(mockElectionTerm).getCurrentTerm();
160 RaftActorContext raftActorContext = new RaftActorContextImpl(candidateActor, candidateActor.actorContext(),
161 "candidate", mockElectionTerm, -1, -1, setupPeers(4), new DefaultConfigParamsImpl(),
162 new NonPersistentDataProvider(), LOG);
163 raftActorContext.setReplicatedLog(new MockRaftActorContext.MockReplicatedLogBuilder().build());
164 raftActorContext.getPeerInfo("peer1").setVotingState(VotingState.NON_VOTING);
165 raftActorContext.getPeerInfo("peer4").setVotingState(VotingState.NON_VOTING);
166 candidate = new Candidate(raftActorContext);
168 MessageCollectorActor.expectFirstMatching(peerActors[1], RequestVote.class);
169 MessageCollectorActor.expectFirstMatching(peerActors[2], RequestVote.class);
170 MessageCollectorActor.assertNoneMatching(peerActors[0], RequestVote.class, 300);
171 MessageCollectorActor.assertNoneMatching(peerActors[3], RequestVote.class, 100);
173 candidate = candidate.handleMessage(peerActors[1], new RequestVoteReply(1, false));
175 assertEquals("Behavior", RaftState.Candidate, candidate.state());
177 candidate = candidate.handleMessage(peerActors[2], new RequestVoteReply(1, true));
179 assertEquals("Behavior", RaftState.Leader, candidate.state());
183 public void testResponseToHandleAppendEntriesWithLowerTerm() {
184 candidate = new Candidate(createActorContext());
187 RaftActorBehavior newBehavior = candidate.handleMessage(peerActors[0], new AppendEntries(1, "test", 0, 0,
188 Collections.<ReplicatedLogEntry>emptyList(), 0, -1, (short) 0));
190 AppendEntriesReply reply = MessageCollectorActor.expectFirstMatching(
191 peerActors[0], AppendEntriesReply.class);
192 assertEquals("isSuccess", false, reply.isSuccess());
193 assertEquals("getTerm", 2, reply.getTerm());
194 assertTrue("New Behavior : " + newBehavior, newBehavior instanceof Candidate);
198 public void testResponseToHandleAppendEntriesWithHigherTerm() {
199 candidate = new Candidate(createActorContext());
202 RaftActorBehavior newBehavior = candidate.handleMessage(peerActors[0], new AppendEntries(5, "test", 0, 0,
203 Collections.<ReplicatedLogEntry>emptyList(), 0, -1, (short) 0));
205 assertTrue("New Behavior : " + newBehavior, newBehavior instanceof Follower);
209 public void testResponseToHandleAppendEntriesWithEqualTerm() {
210 MockRaftActorContext actorContext = createActorContext();
212 candidate = new Candidate(actorContext);
215 RaftActorBehavior newBehavior = candidate.handleMessage(peerActors[0], new AppendEntries(2, "test", 0, 0,
216 Collections.<ReplicatedLogEntry>emptyList(), 0, -1, (short) 0));
218 assertTrue("New Behavior : " + newBehavior + " term = " + actorContext.getTermInformation().getCurrentTerm(),
219 newBehavior instanceof Follower);
224 public void testResponseToRequestVoteWithLowerTerm() {
225 candidate = new Candidate(createActorContext());
228 candidate.handleMessage(peerActors[0], new RequestVote(1, "test", 0, 0));
230 RequestVoteReply reply = MessageCollectorActor.expectFirstMatching(
231 peerActors[0], RequestVoteReply.class);
232 assertEquals("isVoteGranted", false, reply.isVoteGranted());
233 assertEquals("getTerm", 2, reply.getTerm());
237 public void testHandleRequestVoteWhenSenderTermEqualToCurrentTermAndVotedForMatches() {
238 MockRaftActorContext context = createActorContext();
239 context.getTermInformation().update(1000, null);
241 // Once a candidate is created it will immediately increment the current term so after
242 // construction the currentTerm should be 1001
243 candidate = new Candidate(context);
246 candidate.handleMessage(peerActors[0], new RequestVote(1001, context.getId(), 10000, 999));
248 RequestVoteReply reply = MessageCollectorActor.expectFirstMatching(
249 peerActors[0], RequestVoteReply.class);
250 assertEquals("isVoteGranted", true, reply.isVoteGranted());
251 assertEquals("getTerm", 1001, reply.getTerm());
255 public void testHandleRequestVoteWhenSenderTermEqualToCurrentTermAndVotedForDoesNotMatch() {
256 MockRaftActorContext context = createActorContext();
257 context.getTermInformation().update(1000, null);
259 // Once a candidate is created it will immediately increment the current term so after
260 // construction the currentTerm should be 1001
261 candidate = new Candidate(context);
265 // RequestVote candidate ID ("candidate2") does not match this candidate's votedFor
266 // (it votes for itself)
267 candidate.handleMessage(peerActors[0], new RequestVote(1001, "candidate2", 10000, 999));
269 RequestVoteReply reply = MessageCollectorActor.expectFirstMatching(
270 peerActors[0], RequestVoteReply.class);
271 assertEquals("isVoteGranted", false, reply.isVoteGranted());
272 assertEquals("getTerm", 1001, reply.getTerm());
276 public void testCandidateSchedulesElectionTimeoutImmediatelyWhenItHasNoPeers(){
277 MockRaftActorContext context = createActorContext();
279 Stopwatch stopwatch = Stopwatch.createStarted();
281 candidate = createBehavior(context);
283 MessageCollectorActor.expectFirstMatching(candidateActor, ElectionTimeout.class);
285 long elapsed = stopwatch.elapsed(TimeUnit.MILLISECONDS);
287 assertTrue(elapsed < context.getConfigParams().getElectionTimeOutInterval().toMillis());
292 public void testHandleAppendEntriesAddSameEntryToLog() throws Exception {
293 MockRaftActorContext context = createActorContext();
295 context.getTermInformation().update(2, "test");
297 // Prepare the receivers log
298 MockRaftActorContext.MockPayload payload = new MockRaftActorContext.MockPayload("zero");
299 setLastLogEntry(context, 2, 0, payload);
301 List<ReplicatedLogEntry> entries = new ArrayList<>();
302 entries.add(new MockRaftActorContext.MockReplicatedLogEntry(2, 0, payload));
304 AppendEntries appendEntries = new AppendEntries(2, "leader-1", -1, -1, entries, 2, -1, (short)0);
306 behavior = createBehavior(context);
308 // Resetting the Candidates term to make sure it will match
309 // the term sent by AppendEntries. If this was not done then
310 // the test will fail because the Candidate will assume that
311 // the message was sent to it from a lower term peer and will
312 // thus respond with a failure
313 context.getTermInformation().update(2, "test");
315 // Send an unknown message so that the state of the RaftActor remains unchanged
316 RaftActorBehavior expected = behavior.handleMessage(candidateActor, "unknown");
318 RaftActorBehavior raftBehavior = behavior.handleMessage(candidateActor, appendEntries);
320 assertEquals("Raft state", RaftState.Follower, raftBehavior.state());
322 assertEquals("ReplicatedLog size", 1, context.getReplicatedLog().size());
324 handleAppendEntriesAddSameEntryToLogReply(candidateActor);
328 protected Candidate createBehavior(final RaftActorContext actorContext) {
329 return new Candidate(actorContext);
332 @Override protected MockRaftActorContext createActorContext() {
333 return new MockRaftActorContext("candidate", getSystem(), candidateActor);
336 private Map<String, String> setupPeers(final int count) {
337 Map<String, String> peerMap = new HashMap<>();
338 peerActors = new TestActorRef[count];
339 for(int i = 0; i < count; i++) {
340 peerActors[i] = actorFactory.createTestActor(Props.create(MessageCollectorActor.class),
341 actorFactory.generateActorId("peer"));
342 peerMap.put("peer" + (i+1), peerActors[i].path().toString());
349 protected void assertStateChangesToFollowerWhenRaftRPCHasNewerTerm(final MockRaftActorContext actorContext,
350 final ActorRef actorRef, final RaftRPC rpc) throws Exception {
351 super.assertStateChangesToFollowerWhenRaftRPCHasNewerTerm(actorContext, actorRef, rpc);
352 assertEquals("New votedFor", null, actorContext.getTermInformation().getVotedFor());