Bug 5504: Add PreLeader raft state
[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.setPeerAddresses(setupPeers(2));
116         candidate = new Candidate(raftActorContext);
117
118         candidate = candidate.handleMessage(peerActors[0], new RequestVoteReply(1, true));
119
120         assertEquals("Behavior", RaftState.Leader, candidate.state());
121     }
122
123     @Test
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.setCommitIndex(raftActorContext.getReplicatedLog().lastIndex());
130         raftActorContext.setPeerAddresses(setupPeers(4));
131         candidate = new Candidate(raftActorContext);
132
133         RequestVote requestVote = MessageCollectorActor.expectFirstMatching(peerActors[0], RequestVote.class);
134         assertEquals("getTerm", 3L, requestVote.getTerm());
135         assertEquals("getCandidateId", raftActorContext.getId(), requestVote.getCandidateId());
136         assertEquals("getLastLogTerm", 1L, requestVote.getLastLogTerm());
137         assertEquals("getLastLogIndex", 4L, requestVote.getLastLogIndex());
138
139         MessageCollectorActor.expectFirstMatching(peerActors[1], RequestVote.class);
140         MessageCollectorActor.expectFirstMatching(peerActors[2], RequestVote.class);
141         MessageCollectorActor.expectFirstMatching(peerActors[3], RequestVote.class);
142
143         // First peers denies the vote.
144         candidate = candidate.handleMessage(peerActors[0], new RequestVoteReply(1, false));
145
146         assertEquals("Behavior", RaftState.Candidate, candidate.state());
147
148         candidate = candidate.handleMessage(peerActors[1], new RequestVoteReply(1, true));
149
150         assertEquals("Behavior", RaftState.Candidate, candidate.state());
151
152         candidate = candidate.handleMessage(peerActors[2], new RequestVoteReply(1, true));
153
154         assertEquals("Behavior", RaftState.Leader, candidate.state());
155     }
156
157     @Test
158     public void testBecomeLeaderOnReceivingMajorityVotesWithNonVotingPeers(){
159         ElectionTerm mockElectionTerm = Mockito.mock(ElectionTerm.class);
160         Mockito.doReturn(1L).when(mockElectionTerm).getCurrentTerm();
161         RaftActorContext raftActorContext = new RaftActorContextImpl(candidateActor, candidateActor.actorContext(),
162                 "candidate", mockElectionTerm, -1, -1, setupPeers(4), new DefaultConfigParamsImpl(),
163                 new NonPersistentDataProvider(), LOG);
164         raftActorContext.setReplicatedLog(new MockRaftActorContext.MockReplicatedLogBuilder().build());
165         raftActorContext.getPeerInfo("peer1").setVotingState(VotingState.NON_VOTING);
166         raftActorContext.getPeerInfo("peer4").setVotingState(VotingState.NON_VOTING);
167         candidate = new Candidate(raftActorContext);
168
169         MessageCollectorActor.expectFirstMatching(peerActors[1], RequestVote.class);
170         MessageCollectorActor.expectFirstMatching(peerActors[2], RequestVote.class);
171         MessageCollectorActor.assertNoneMatching(peerActors[0], RequestVote.class, 300);
172         MessageCollectorActor.assertNoneMatching(peerActors[3], RequestVote.class, 100);
173
174         candidate = candidate.handleMessage(peerActors[1], new RequestVoteReply(1, false));
175
176         assertEquals("Behavior", RaftState.Candidate, candidate.state());
177
178         candidate = candidate.handleMessage(peerActors[2], new RequestVoteReply(1, true));
179
180         assertEquals("Behavior", RaftState.Leader, candidate.state());
181     }
182
183     @Test
184     public void testResponseToHandleAppendEntriesWithLowerTerm() {
185         candidate = new Candidate(createActorContext());
186
187         setupPeers(1);
188         RaftActorBehavior newBehavior = candidate.handleMessage(peerActors[0], new AppendEntries(1, "test", 0, 0,
189                 Collections.<ReplicatedLogEntry>emptyList(), 0, -1, (short) 0));
190
191         AppendEntriesReply reply = MessageCollectorActor.expectFirstMatching(
192                 peerActors[0], AppendEntriesReply.class);
193         assertEquals("isSuccess", false, reply.isSuccess());
194         assertEquals("getTerm", 2, reply.getTerm());
195         assertTrue("New Behavior : " + newBehavior, newBehavior instanceof Candidate);
196     }
197
198     @Test
199     public void testResponseToHandleAppendEntriesWithHigherTerm() {
200         candidate = new Candidate(createActorContext());
201
202         setupPeers(1);
203         RaftActorBehavior newBehavior = candidate.handleMessage(peerActors[0], new AppendEntries(5, "test", 0, 0,
204                 Collections.<ReplicatedLogEntry>emptyList(), 0, -1, (short) 0));
205
206         assertTrue("New Behavior : " + newBehavior, newBehavior instanceof Follower);
207     }
208
209     @Test
210     public void testResponseToHandleAppendEntriesWithEqualTerm() {
211         MockRaftActorContext actorContext = createActorContext();
212
213         candidate = new Candidate(actorContext);
214
215         setupPeers(1);
216         RaftActorBehavior newBehavior = candidate.handleMessage(peerActors[0], new AppendEntries(2, "test", 0, 0,
217                 Collections.<ReplicatedLogEntry>emptyList(), 0, -1, (short) 0));
218
219         assertTrue("New Behavior : " + newBehavior + " term = " + actorContext.getTermInformation().getCurrentTerm(),
220                 newBehavior instanceof Follower);
221     }
222
223
224     @Test
225     public void testResponseToRequestVoteWithLowerTerm() {
226         candidate = new Candidate(createActorContext());
227
228         setupPeers(1);
229         candidate.handleMessage(peerActors[0], new RequestVote(1, "test", 0, 0));
230
231         RequestVoteReply reply = MessageCollectorActor.expectFirstMatching(
232                 peerActors[0], RequestVoteReply.class);
233         assertEquals("isVoteGranted", false, reply.isVoteGranted());
234         assertEquals("getTerm", 2, reply.getTerm());
235     }
236
237     @Test
238     public void testHandleRequestVoteWhenSenderTermEqualToCurrentTermAndVotedForMatches() {
239         MockRaftActorContext context = createActorContext();
240         context.getTermInformation().update(1000, null);
241
242         // Once a candidate is created it will immediately increment the current term so after
243         // construction the currentTerm should be 1001
244         candidate = new Candidate(context);
245
246         setupPeers(1);
247         candidate.handleMessage(peerActors[0], new RequestVote(1001, context.getId(), 10000, 999));
248
249         RequestVoteReply reply = MessageCollectorActor.expectFirstMatching(
250                 peerActors[0], RequestVoteReply.class);
251         assertEquals("isVoteGranted", true, reply.isVoteGranted());
252         assertEquals("getTerm", 1001, reply.getTerm());
253     }
254
255     @Test
256     public void testHandleRequestVoteWhenSenderTermEqualToCurrentTermAndVotedForDoesNotMatch() {
257         MockRaftActorContext context = createActorContext();
258         context.getTermInformation().update(1000, null);
259
260         // Once a candidate is created it will immediately increment the current term so after
261         // construction the currentTerm should be 1001
262         candidate = new Candidate(context);
263
264         setupPeers(1);
265
266         // RequestVote candidate ID ("candidate2") does not match this candidate's votedFor
267         // (it votes for itself)
268         candidate.handleMessage(peerActors[0], new RequestVote(1001, "candidate2", 10000, 999));
269
270         RequestVoteReply reply = MessageCollectorActor.expectFirstMatching(
271                 peerActors[0], RequestVoteReply.class);
272         assertEquals("isVoteGranted", false, reply.isVoteGranted());
273         assertEquals("getTerm", 1001, reply.getTerm());
274     }
275
276     @Test
277     public void testCandidateSchedulesElectionTimeoutImmediatelyWhenItHasNoPeers(){
278         MockRaftActorContext context = createActorContext();
279
280         Stopwatch stopwatch = Stopwatch.createStarted();
281
282         candidate = createBehavior(context);
283
284         MessageCollectorActor.expectFirstMatching(candidateActor, ElectionTimeout.class);
285
286         long elapsed = stopwatch.elapsed(TimeUnit.MILLISECONDS);
287
288         assertTrue(elapsed < context.getConfigParams().getElectionTimeOutInterval().toMillis());
289     }
290
291     @Test
292     @Override
293     public void testHandleAppendEntriesAddSameEntryToLog() throws Exception {
294         MockRaftActorContext context = createActorContext();
295
296         context.getTermInformation().update(2, "test");
297
298         // Prepare the receivers log
299         MockRaftActorContext.MockPayload payload = new MockRaftActorContext.MockPayload("zero");
300         setLastLogEntry(context, 2, 0, payload);
301
302         List<ReplicatedLogEntry> entries = new ArrayList<>();
303         entries.add(new MockRaftActorContext.MockReplicatedLogEntry(2, 0, payload));
304
305         AppendEntries appendEntries = new AppendEntries(2, "leader-1", -1, -1, entries, 2, -1, (short)0);
306
307         behavior = createBehavior(context);
308
309         // Resetting the Candidates term to make sure it will match
310         // the term sent by AppendEntries. If this was not done then
311         // the test will fail because the Candidate will assume that
312         // the message was sent to it from a lower term peer and will
313         // thus respond with a failure
314         context.getTermInformation().update(2, "test");
315
316         // Send an unknown message so that the state of the RaftActor remains unchanged
317         behavior.handleMessage(candidateActor, "unknown");
318
319         RaftActorBehavior raftBehavior = behavior.handleMessage(candidateActor, appendEntries);
320
321         assertEquals("Raft state", RaftState.Follower, raftBehavior.state());
322
323         assertEquals("ReplicatedLog size", 1, context.getReplicatedLog().size());
324
325         handleAppendEntriesAddSameEntryToLogReply(candidateActor);
326     }
327
328     @Override
329     protected Candidate createBehavior(final RaftActorContext actorContext) {
330         return new Candidate(actorContext);
331     }
332
333     @Override protected MockRaftActorContext createActorContext() {
334         return new MockRaftActorContext("candidate", getSystem(), candidateActor);
335     }
336
337     @SuppressWarnings("unchecked")
338     private Map<String, String> setupPeers(final int count) {
339         Map<String, String> peerMap = new HashMap<>();
340         peerActors = new TestActorRef[count];
341         for(int i = 0; i < count; i++) {
342             peerActors[i] = actorFactory.createTestActor(Props.create(MessageCollectorActor.class),
343                     actorFactory.generateActorId("peer"));
344             peerMap.put("peer" + (i+1), peerActors[i].path().toString());
345         }
346
347         return peerMap;
348     }
349
350     @Override
351     protected void assertStateChangesToFollowerWhenRaftRPCHasNewerTerm(final MockRaftActorContext actorContext,
352             final ActorRef actorRef, final RaftRPC rpc) throws Exception {
353         super.assertStateChangesToFollowerWhenRaftRPCHasNewerTerm(actorContext, actorRef, rpc);
354         if(rpc instanceof RequestVote) {
355             assertEquals("New votedFor", ((RequestVote)rpc).getCandidateId(), actorContext.getTermInformation().getVotedFor());
356         } else {
357             assertEquals("New votedFor", null, actorContext.getTermInformation().getVotedFor());
358         }
359     }
360 }