924ba57986739a1a56865b797a03007df8a7f872
[controller.git] / opendaylight / md-sal / sal-akka-raft / src / test / java / org / opendaylight / controller / cluster / raft / behaviors / CandidateTest.java
1 /*
2  * Copyright (c) 2014, 2015 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 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;
21 import java.util.Map;
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;
45
46 public class CandidateTest extends AbstractRaftActorBehaviorTest<Candidate> {
47     static final Logger LOG = LoggerFactory.getLogger(CandidateTest.class);
48
49     private final TestActorRef<MessageCollectorActor> candidateActor = actorFactory.createTestActor(
50             Props.create(MessageCollectorActor.class), actorFactory.generateActorId("candidate"));
51
52     private TestActorRef<MessageCollectorActor>[] peerActors;
53
54     private RaftActorBehavior candidate;
55
56     @Before
57     public void setUp(){
58     }
59
60     @Override
61     @After
62     public void tearDown() throws Exception {
63         if(candidate != null) {
64             candidate.close();
65         }
66
67         super.tearDown();
68     }
69
70     @Test
71     public void testWhenACandidateIsCreatedItIncrementsTheCurrentTermAndVotesForItself(){
72         RaftActorContext raftActorContext = createActorContext();
73         long expectedTerm = raftActorContext.getTermInformation().getCurrentTerm();
74
75         candidate = new Candidate(raftActorContext);
76
77         assertEquals("getCurrentTerm", expectedTerm+1, raftActorContext.getTermInformation().getCurrentTerm());
78         assertEquals("getVotedFor", raftActorContext.getId(), raftActorContext.getTermInformation().getVotedFor());
79     }
80
81     @Test
82     public void testThatAnElectionTimeoutIsTriggered(){
83          MockRaftActorContext actorContext = createActorContext();
84          candidate = new Candidate(actorContext);
85
86          MessageCollectorActor.expectFirstMatching(candidateActor, ElectionTimeout.class,
87                  actorContext.getConfigParams().getElectionTimeOutInterval().$times(6).toMillis());
88     }
89
90     @Test
91     public void testHandleElectionTimeoutWhenThereAreZeroPeers(){
92         RaftActorContext raftActorContext = createActorContext();
93         candidate = new Candidate(raftActorContext);
94
95         RaftActorBehavior newBehavior =
96             candidate.handleMessage(candidateActor, ElectionTimeout.INSTANCE);
97
98         assertEquals("Behavior", RaftState.Leader, newBehavior.state());
99     }
100
101     @Test
102     public void testHandleElectionTimeoutWhenThereAreTwoNodeCluster(){
103         MockRaftActorContext raftActorContext = createActorContext();
104         raftActorContext.setPeerAddresses(setupPeers(1));
105         candidate = new Candidate(raftActorContext);
106
107         candidate = candidate.handleMessage(candidateActor, ElectionTimeout.INSTANCE);
108
109         assertEquals("Behavior", RaftState.Candidate, candidate.state());
110     }
111
112     @Test
113     public void testBecomeLeaderOnReceivingMajorityVotesInThreeNodeCluster(){
114         MockRaftActorContext raftActorContext = createActorContext();
115         raftActorContext.setLastApplied(raftActorContext.getReplicatedLog().lastIndex());
116         raftActorContext.setPeerAddresses(setupPeers(2));
117         candidate = new Candidate(raftActorContext);
118
119         candidate = candidate.handleMessage(peerActors[0], new RequestVoteReply(1, true));
120
121         assertEquals("Behavior", RaftState.Leader, candidate.state());
122     }
123
124     @Test
125     public void testBecomePreLeaderOnReceivingMajorityVotesInThreeNodeCluster(){
126         MockRaftActorContext raftActorContext = createActorContext();
127         raftActorContext.setPeerAddresses(setupPeers(2));
128         candidate = new Candidate(raftActorContext);
129
130         candidate = candidate.handleMessage(peerActors[0], new RequestVoteReply(1, true));
131
132         // LastApplied is -1 and behind the last index.
133         assertEquals("Behavior", RaftState.PreLeader, candidate.state());
134     }
135
136     @Test
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);
146
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());
152
153         MessageCollectorActor.expectFirstMatching(peerActors[1], RequestVote.class);
154         MessageCollectorActor.expectFirstMatching(peerActors[2], RequestVote.class);
155         MessageCollectorActor.expectFirstMatching(peerActors[3], RequestVote.class);
156
157         // First peers denies the vote.
158         candidate = candidate.handleMessage(peerActors[0], new RequestVoteReply(1, false));
159
160         assertEquals("Behavior", RaftState.Candidate, candidate.state());
161
162         candidate = candidate.handleMessage(peerActors[1], new RequestVoteReply(1, true));
163
164         assertEquals("Behavior", RaftState.Candidate, candidate.state());
165
166         candidate = candidate.handleMessage(peerActors[2], new RequestVoteReply(1, true));
167
168         assertEquals("Behavior", RaftState.Leader, candidate.state());
169     }
170
171     @Test
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);
182
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);
187
188         candidate = candidate.handleMessage(peerActors[1], new RequestVoteReply(1, false));
189
190         assertEquals("Behavior", RaftState.Candidate, candidate.state());
191
192         candidate = candidate.handleMessage(peerActors[2], new RequestVoteReply(1, true));
193
194         assertEquals("Behavior", RaftState.Leader, candidate.state());
195     }
196
197     @Test
198     public void testResponseToHandleAppendEntriesWithLowerTerm() {
199         candidate = new Candidate(createActorContext());
200
201         setupPeers(1);
202         RaftActorBehavior newBehavior = candidate.handleMessage(peerActors[0], new AppendEntries(1, "test", 0, 0,
203                 Collections.<ReplicatedLogEntry>emptyList(), 0, -1, (short) 0));
204
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);
210     }
211
212     @Test
213     public void testResponseToHandleAppendEntriesWithHigherTerm() {
214         candidate = new Candidate(createActorContext());
215
216         setupPeers(1);
217         RaftActorBehavior newBehavior = candidate.handleMessage(peerActors[0], new AppendEntries(5, "test", 0, 0,
218                 Collections.<ReplicatedLogEntry>emptyList(), 0, -1, (short) 0));
219
220         assertTrue("New Behavior : " + newBehavior, newBehavior instanceof Follower);
221     }
222
223     @Test
224     public void testResponseToHandleAppendEntriesWithEqualTerm() {
225         MockRaftActorContext actorContext = createActorContext();
226
227         candidate = new Candidate(actorContext);
228
229         setupPeers(1);
230         RaftActorBehavior newBehavior = candidate.handleMessage(peerActors[0], new AppendEntries(2, "test", 0, 0,
231                 Collections.<ReplicatedLogEntry>emptyList(), 0, -1, (short) 0));
232
233         assertTrue("New Behavior : " + newBehavior + " term = " + actorContext.getTermInformation().getCurrentTerm(),
234                 newBehavior instanceof Follower);
235     }
236
237
238     @Test
239     public void testResponseToRequestVoteWithLowerTerm() {
240         candidate = new Candidate(createActorContext());
241
242         setupPeers(1);
243         candidate.handleMessage(peerActors[0], new RequestVote(1, "test", 0, 0));
244
245         RequestVoteReply reply = MessageCollectorActor.expectFirstMatching(
246                 peerActors[0], RequestVoteReply.class);
247         assertEquals("isVoteGranted", false, reply.isVoteGranted());
248         assertEquals("getTerm", 2, reply.getTerm());
249     }
250
251     @Test
252     public void testHandleRequestVoteWhenSenderTermEqualToCurrentTermAndVotedForMatches() {
253         MockRaftActorContext context = createActorContext();
254         context.getTermInformation().update(1000, null);
255
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);
259
260         setupPeers(1);
261         candidate.handleMessage(peerActors[0], new RequestVote(1001, context.getId(), 10000, 999));
262
263         RequestVoteReply reply = MessageCollectorActor.expectFirstMatching(
264                 peerActors[0], RequestVoteReply.class);
265         assertEquals("isVoteGranted", true, reply.isVoteGranted());
266         assertEquals("getTerm", 1001, reply.getTerm());
267     }
268
269     @Test
270     public void testHandleRequestVoteWhenSenderTermEqualToCurrentTermAndVotedForDoesNotMatch() {
271         MockRaftActorContext context = createActorContext();
272         context.getTermInformation().update(1000, null);
273
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);
277
278         setupPeers(1);
279
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));
283
284         RequestVoteReply reply = MessageCollectorActor.expectFirstMatching(
285                 peerActors[0], RequestVoteReply.class);
286         assertEquals("isVoteGranted", false, reply.isVoteGranted());
287         assertEquals("getTerm", 1001, reply.getTerm());
288     }
289
290     @Test
291     public void testCandidateSchedulesElectionTimeoutImmediatelyWhenItHasNoPeers(){
292         MockRaftActorContext context = createActorContext();
293
294         Stopwatch stopwatch = Stopwatch.createStarted();
295
296         candidate = createBehavior(context);
297
298         MessageCollectorActor.expectFirstMatching(candidateActor, ElectionTimeout.class);
299
300         long elapsed = stopwatch.elapsed(TimeUnit.MILLISECONDS);
301
302         assertTrue(elapsed < context.getConfigParams().getElectionTimeOutInterval().toMillis());
303     }
304
305     @Test
306     @Override
307     public void testHandleAppendEntriesAddSameEntryToLog() throws Exception {
308         MockRaftActorContext context = createActorContext();
309
310         context.getTermInformation().update(2, "test");
311
312         // Prepare the receivers log
313         MockRaftActorContext.MockPayload payload = new MockRaftActorContext.MockPayload("zero");
314         setLastLogEntry(context, 2, 0, payload);
315
316         List<ReplicatedLogEntry> entries = new ArrayList<>();
317         entries.add(new MockRaftActorContext.MockReplicatedLogEntry(2, 0, payload));
318
319         AppendEntries appendEntries = new AppendEntries(2, "leader-1", -1, -1, entries, 2, -1, (short)0);
320
321         behavior = createBehavior(context);
322
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");
329
330         // Send an unknown message so that the state of the RaftActor remains unchanged
331         behavior.handleMessage(candidateActor, "unknown");
332
333         RaftActorBehavior raftBehavior = behavior.handleMessage(candidateActor, appendEntries);
334
335         assertEquals("Raft state", RaftState.Follower, raftBehavior.state());
336
337         assertEquals("ReplicatedLog size", 1, context.getReplicatedLog().size());
338
339         handleAppendEntriesAddSameEntryToLogReply(candidateActor);
340     }
341
342     @Override
343     protected Candidate createBehavior(final RaftActorContext actorContext) {
344         return new Candidate(actorContext);
345     }
346
347     @Override protected MockRaftActorContext createActorContext() {
348         return new MockRaftActorContext("candidate", getSystem(), candidateActor);
349     }
350
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());
359         }
360
361         return peerMap;
362     }
363
364     @Override
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());
370         } else {
371             assertEquals("New votedFor", null, actorContext.getTermInformation().getVotedFor());
372         }
373     }
374 }