2 * Copyright (c) 2015 Brocade Communications 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
8 package org.opendaylight.controller.cluster.raft;
10 import static org.junit.Assert.assertEquals;
11 import static org.opendaylight.controller.cluster.raft.utils.MessageCollectorActor.clearMessages;
12 import static org.opendaylight.controller.cluster.raft.utils.MessageCollectorActor.expectFirstMatching;
13 import akka.actor.ActorRef;
14 import akka.actor.Props;
15 import akka.actor.UntypedActor;
16 import akka.dispatch.Dispatchers;
17 import akka.testkit.JavaTestKit;
18 import akka.testkit.TestActorRef;
19 import com.google.common.base.Optional;
20 import com.google.common.collect.ImmutableMap;
21 import com.google.common.collect.Maps;
22 import com.google.common.collect.Sets;
23 import java.util.Collections;
24 import java.util.List;
26 import java.util.concurrent.TimeUnit;
27 import org.junit.After;
28 import org.junit.Before;
29 import org.junit.Test;
30 import org.opendaylight.controller.cluster.DataPersistenceProvider;
31 import org.opendaylight.controller.cluster.NonPersistentDataProvider;
32 import org.opendaylight.controller.cluster.raft.ServerConfigurationPayload.ServerInfo;
33 import org.opendaylight.controller.cluster.raft.base.messages.ApplySnapshot;
34 import org.opendaylight.controller.cluster.raft.base.messages.ApplyState;
35 import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshotReply;
36 import org.opendaylight.controller.cluster.raft.base.messages.InitiateCaptureSnapshot;
37 import org.opendaylight.controller.cluster.raft.behaviors.AbstractLeader;
38 import org.opendaylight.controller.cluster.raft.behaviors.Follower;
39 import org.opendaylight.controller.cluster.raft.behaviors.Leader;
40 import org.opendaylight.controller.cluster.raft.messages.AddServer;
41 import org.opendaylight.controller.cluster.raft.messages.AddServerReply;
42 import org.opendaylight.controller.cluster.raft.messages.AppendEntries;
43 import org.opendaylight.controller.cluster.raft.messages.FollowerCatchUpTimeout;
44 import org.opendaylight.controller.cluster.raft.messages.InstallSnapshot;
45 import org.opendaylight.controller.cluster.raft.messages.ServerChangeStatus;
46 import org.opendaylight.controller.cluster.raft.messages.UnInitializedFollowerSnapshotReply;
47 import org.opendaylight.controller.cluster.raft.policy.DisableElectionsRaftPolicy;
48 import org.opendaylight.controller.cluster.raft.utils.ForwardMessageToBehaviorActor;
49 import org.opendaylight.controller.cluster.raft.utils.InMemoryJournal;
50 import org.opendaylight.controller.cluster.raft.utils.InMemorySnapshotStore;
51 import org.opendaylight.controller.cluster.raft.utils.MessageCollectorActor;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
54 import scala.concurrent.duration.FiniteDuration;
57 * Unit tests for RaftActorServerConfigurationSupport.
59 * @author Thomas Pantelis
61 public class RaftActorServerConfigurationSupportTest extends AbstractActorTest {
62 static final String LEADER_ID = "leader";
63 static final String FOLLOWER_ID = "follower";
64 static final String NEW_SERVER_ID = "new-server";
65 static final String NEW_SERVER_ID2 = "new-server2";
66 private static final Logger LOG = LoggerFactory.getLogger(RaftActorServerConfigurationSupportTest.class);
67 private static final DataPersistenceProvider NO_PERSISTENCE = new NonPersistentDataProvider();
69 private final TestActorFactory actorFactory = new TestActorFactory(getSystem());
71 private final TestActorRef<ForwardMessageToBehaviorActor> followerActor = actorFactory.createTestActor(
72 Props.create(ForwardMessageToBehaviorActor.class).withDispatcher(Dispatchers.DefaultDispatcherId()),
73 actorFactory.generateActorId(FOLLOWER_ID));
75 private TestActorRef<MockNewFollowerRaftActor> newFollowerRaftActor;
76 private TestActorRef<MessageCollectorActor> newFollowerCollectorActor;
77 private RaftActorContext newFollowerActorContext;
79 private final JavaTestKit testKit = new JavaTestKit(getSystem());
83 InMemoryJournal.clear();
84 InMemorySnapshotStore.clear();
86 DefaultConfigParamsImpl configParams = newFollowerConfigParams();
88 newFollowerCollectorActor = actorFactory.createTestActor(
89 MessageCollectorActor.props().withDispatcher(Dispatchers.DefaultDispatcherId()),
90 actorFactory.generateActorId(NEW_SERVER_ID + "Collector"));
91 newFollowerRaftActor = actorFactory.createTestActor(MockNewFollowerRaftActor.props(
92 configParams, newFollowerCollectorActor).withDispatcher(Dispatchers.DefaultDispatcherId()),
93 actorFactory.generateActorId(NEW_SERVER_ID));
96 newFollowerActorContext = newFollowerRaftActor.underlyingActor().getRaftActorContext();
97 } catch (Exception e) {
98 newFollowerActorContext = newFollowerRaftActor.underlyingActor().getRaftActorContext();
102 private static DefaultConfigParamsImpl newFollowerConfigParams() {
103 DefaultConfigParamsImpl configParams = new DefaultConfigParamsImpl();
104 configParams.setHeartBeatInterval(new FiniteDuration(100, TimeUnit.MILLISECONDS));
105 configParams.setElectionTimeoutFactor(100000);
106 configParams.setCustomRaftPolicyImplementationClass(DisableElectionsRaftPolicy.class.getName());
111 public void tearDown() throws Exception {
112 actorFactory.close();
116 public void testAddServerWithExistingFollower() throws Exception {
117 RaftActorContext followerActorContext = newFollowerContext(FOLLOWER_ID, followerActor);
118 followerActorContext.setReplicatedLog(new MockRaftActorContext.MockReplicatedLogBuilder().createEntries(
120 followerActorContext.setCommitIndex(2);
121 followerActorContext.setLastApplied(2);
123 Follower follower = new Follower(followerActorContext);
124 followerActor.underlyingActor().setBehavior(follower);
126 TestActorRef<MockLeaderRaftActor> leaderActor = actorFactory.createTestActor(
127 MockLeaderRaftActor.props(ImmutableMap.of(FOLLOWER_ID, followerActor.path().toString()),
128 followerActorContext).withDispatcher(Dispatchers.DefaultDispatcherId()),
129 actorFactory.generateActorId(LEADER_ID));
131 // Expect initial heartbeat from the leader.
132 expectFirstMatching(followerActor, AppendEntries.class);
133 clearMessages(followerActor);
135 MockLeaderRaftActor leaderRaftActor = leaderActor.underlyingActor();
137 leaderActor.tell(new AddServer(NEW_SERVER_ID, newFollowerRaftActor.path().toString(), true), testKit.getRef());
139 // Leader should install snapshot - capture and verify ApplySnapshot contents
141 ApplySnapshot applySnapshot = expectFirstMatching(newFollowerCollectorActor, ApplySnapshot.class);
142 List<Object> snapshotState = (List<Object>) MockRaftActor.toObject(applySnapshot.getSnapshot().getState());
143 assertEquals("Snapshot state", snapshotState, leaderRaftActor.getState());
145 AddServerReply addServerReply = testKit.expectMsgClass(JavaTestKit.duration("5 seconds"), AddServerReply.class);
146 assertEquals("getStatus", ServerChangeStatus.OK, addServerReply.getStatus());
147 assertEquals("getLeaderHint", LEADER_ID, addServerReply.getLeaderHint());
149 // Verify ServerConfigurationPayload entry in leader's log
151 RaftActorContext leaderActorContext = leaderRaftActor.getRaftActorContext();
152 assertEquals("Leader journal last index", 3, leaderActorContext.getReplicatedLog().lastIndex());
153 assertEquals("Leader commit index", 3, leaderActorContext.getCommitIndex());
154 assertEquals("Leader last applied index", 3, leaderActorContext.getLastApplied());
155 verifyServerConfigurationPayloadEntry(leaderActorContext.getReplicatedLog(), votingServer(LEADER_ID),
156 votingServer(FOLLOWER_ID), votingServer(NEW_SERVER_ID));
158 // Verify ServerConfigurationPayload entry in both followers
160 assertEquals("Follower journal last index", 3, followerActorContext.getReplicatedLog().lastIndex());
161 verifyServerConfigurationPayloadEntry(followerActorContext.getReplicatedLog(), votingServer(LEADER_ID),
162 votingServer(FOLLOWER_ID), votingServer(NEW_SERVER_ID));
164 assertEquals("New follower journal last index", 3, newFollowerActorContext.getReplicatedLog().lastIndex());
165 verifyServerConfigurationPayloadEntry(newFollowerActorContext.getReplicatedLog(), votingServer(LEADER_ID),
166 votingServer(FOLLOWER_ID), votingServer(NEW_SERVER_ID));
168 // Verify new server config was applied in both followers
170 assertEquals("Follower peers", Sets.newHashSet(LEADER_ID, NEW_SERVER_ID), followerActorContext.getPeerIds());
172 assertEquals("New follower peers", Sets.newHashSet(LEADER_ID, FOLLOWER_ID), newFollowerActorContext.getPeerIds());
174 expectFirstMatching(newFollowerCollectorActor, ApplyState.class);
175 expectFirstMatching(followerActor, ApplyState.class);
177 assertEquals("Follower commit index", 3, followerActorContext.getCommitIndex());
178 assertEquals("Follower last applied index", 3, followerActorContext.getLastApplied());
179 assertEquals("New follower commit index", 3, newFollowerActorContext.getCommitIndex());
180 assertEquals("New follower last applied index", 3, newFollowerActorContext.getLastApplied());
184 public void testAddServerWithNoExistingFollower() throws Exception {
185 RaftActorContext initialActorContext = new MockRaftActorContext();
186 initialActorContext.setCommitIndex(1);
187 initialActorContext.setLastApplied(1);
188 initialActorContext.setReplicatedLog(new MockRaftActorContext.MockReplicatedLogBuilder().createEntries(
191 TestActorRef<MockLeaderRaftActor> leaderActor = actorFactory.createTestActor(
192 MockLeaderRaftActor.props(ImmutableMap.<String, String>of(),
193 initialActorContext).withDispatcher(Dispatchers.DefaultDispatcherId()),
194 actorFactory.generateActorId(LEADER_ID));
196 MockLeaderRaftActor leaderRaftActor = leaderActor.underlyingActor();
197 RaftActorContext leaderActorContext = leaderRaftActor.getRaftActorContext();
199 leaderActor.tell(new AddServer(NEW_SERVER_ID, newFollowerRaftActor.path().toString(), true), testKit.getRef());
201 // Leader should install snapshot - capture and verify ApplySnapshot contents
203 ApplySnapshot applySnapshot = expectFirstMatching(newFollowerCollectorActor, ApplySnapshot.class);
204 List<Object> snapshotState = (List<Object>) MockRaftActor.toObject(applySnapshot.getSnapshot().getState());
205 assertEquals("Snapshot state", snapshotState, leaderRaftActor.getState());
207 AddServerReply addServerReply = testKit.expectMsgClass(JavaTestKit.duration("5 seconds"), AddServerReply.class);
208 assertEquals("getStatus", ServerChangeStatus.OK, addServerReply.getStatus());
209 assertEquals("getLeaderHint", LEADER_ID, addServerReply.getLeaderHint());
211 // Verify ServerConfigurationPayload entry in leader's log
213 assertEquals("Leader journal last index", 2, leaderActorContext.getReplicatedLog().lastIndex());
214 assertEquals("Leader commit index", 2, leaderActorContext.getCommitIndex());
215 assertEquals("Leader last applied index", 2, leaderActorContext.getLastApplied());
216 verifyServerConfigurationPayloadEntry(leaderActorContext.getReplicatedLog(), votingServer(LEADER_ID),
217 votingServer(NEW_SERVER_ID));
219 // Verify ServerConfigurationPayload entry in the new follower
221 expectFirstMatching(newFollowerCollectorActor, ApplyState.class);
222 assertEquals("New follower journal last index", 2, newFollowerActorContext.getReplicatedLog().lastIndex());
223 verifyServerConfigurationPayloadEntry(newFollowerActorContext.getReplicatedLog(), votingServer(LEADER_ID),
224 votingServer(NEW_SERVER_ID));
226 // Verify new server config was applied in the new follower
228 assertEquals("New follower peers", Sets.newHashSet(LEADER_ID), newFollowerActorContext.getPeerIds());
232 public void testAddServersAsNonVoting() throws Exception {
233 RaftActorContext initialActorContext = new MockRaftActorContext();
234 initialActorContext.setCommitIndex(-1);
235 initialActorContext.setLastApplied(-1);
236 initialActorContext.setReplicatedLog(new MockRaftActorContext.MockReplicatedLogBuilder().build());
238 TestActorRef<MockLeaderRaftActor> leaderActor = actorFactory.createTestActor(
239 MockLeaderRaftActor.props(ImmutableMap.<String, String>of(),
240 initialActorContext).withDispatcher(Dispatchers.DefaultDispatcherId()),
241 actorFactory.generateActorId(LEADER_ID));
243 MockLeaderRaftActor leaderRaftActor = leaderActor.underlyingActor();
244 RaftActorContext leaderActorContext = leaderRaftActor.getRaftActorContext();
246 leaderActor.tell(new AddServer(NEW_SERVER_ID, newFollowerRaftActor.path().toString(), false), testKit.getRef());
248 AddServerReply addServerReply = testKit.expectMsgClass(JavaTestKit.duration("5 seconds"), AddServerReply.class);
249 assertEquals("getStatus", ServerChangeStatus.OK, addServerReply.getStatus());
250 assertEquals("getLeaderHint", LEADER_ID, addServerReply.getLeaderHint());
252 // Verify ServerConfigurationPayload entry in leader's log
254 assertEquals("Leader journal last index", 0, leaderActorContext.getReplicatedLog().lastIndex());
255 assertEquals("Leader commit index", 0, leaderActorContext.getCommitIndex());
256 assertEquals("Leader last applied index", 0, leaderActorContext.getLastApplied());
257 verifyServerConfigurationPayloadEntry(leaderActorContext.getReplicatedLog(), votingServer(LEADER_ID),
258 nonVotingServer(NEW_SERVER_ID));
260 // Verify ServerConfigurationPayload entry in the new follower
262 expectFirstMatching(newFollowerCollectorActor, ApplyState.class);
263 assertEquals("New follower journal last index", 0, newFollowerActorContext.getReplicatedLog().lastIndex());
264 verifyServerConfigurationPayloadEntry(newFollowerActorContext.getReplicatedLog(), votingServer(LEADER_ID),
265 nonVotingServer(NEW_SERVER_ID));
267 // Verify new server config was applied in the new follower
269 assertEquals("New follower peers", Sets.newHashSet(LEADER_ID), newFollowerActorContext.getPeerIds());
271 MessageCollectorActor.assertNoneMatching(newFollowerCollectorActor, InstallSnapshot.class, 500);
273 // Add another non-voting server.
275 RaftActorContext follower2ActorContext = newFollowerContext(NEW_SERVER_ID2, followerActor);
276 Follower newFollower2 = new Follower(follower2ActorContext);
277 followerActor.underlyingActor().setBehavior(newFollower2);
279 leaderActor.tell(new AddServer(NEW_SERVER_ID2, followerActor.path().toString(), false), testKit.getRef());
281 addServerReply = testKit.expectMsgClass(JavaTestKit.duration("5 seconds"), AddServerReply.class);
282 assertEquals("getStatus", ServerChangeStatus.OK, addServerReply.getStatus());
283 assertEquals("getLeaderHint", LEADER_ID, addServerReply.getLeaderHint());
285 assertEquals("Leader journal last index", 1, leaderActorContext.getReplicatedLog().lastIndex());
286 assertEquals("Leader commit index", 1, leaderActorContext.getCommitIndex());
287 assertEquals("Leader last applied index", 1, leaderActorContext.getLastApplied());
288 verifyServerConfigurationPayloadEntry(leaderActorContext.getReplicatedLog(),
289 votingServer(LEADER_ID), nonVotingServer(NEW_SERVER_ID), nonVotingServer(NEW_SERVER_ID2));
293 public void testAddServerWithOperationInProgress() throws Exception {
294 RaftActorContext initialActorContext = new MockRaftActorContext();
295 initialActorContext.setCommitIndex(-1);
296 initialActorContext.setLastApplied(-1);
297 initialActorContext.setReplicatedLog(new MockRaftActorContext.MockReplicatedLogBuilder().build());
299 TestActorRef<MockLeaderRaftActor> leaderActor = actorFactory.createTestActor(
300 MockLeaderRaftActor.props(ImmutableMap.<String, String>of(),
301 initialActorContext).withDispatcher(Dispatchers.DefaultDispatcherId()),
302 actorFactory.generateActorId(LEADER_ID));
304 MockLeaderRaftActor leaderRaftActor = leaderActor.underlyingActor();
305 RaftActorContext leaderActorContext = leaderRaftActor.getRaftActorContext();
307 RaftActorContext follower2ActorContext = newFollowerContext(NEW_SERVER_ID2, followerActor);
308 Follower newFollower2 = new Follower(follower2ActorContext);
309 followerActor.underlyingActor().setBehavior(newFollower2);
311 MockNewFollowerRaftActor newFollowerRaftActorInstance = newFollowerRaftActor.underlyingActor();
312 newFollowerRaftActorInstance.setDropMessageOfType(InstallSnapshot.SERIALIZABLE_CLASS);
314 leaderActor.tell(new AddServer(NEW_SERVER_ID, newFollowerRaftActor.path().toString(), true), testKit.getRef());
316 // Wait for leader's install snapshot and capture it
318 Object installSnapshot = expectFirstMatching(newFollowerCollectorActor, InstallSnapshot.class);
320 // Send a second AddServer - should get queued
321 JavaTestKit testKit2 = new JavaTestKit(getSystem());
322 leaderActor.tell(new AddServer(NEW_SERVER_ID2, followerActor.path().toString(), false), testKit2.getRef());
324 // Continue the first AddServer
325 newFollowerRaftActorInstance.setDropMessageOfType(null);
326 newFollowerRaftActor.tell(installSnapshot, leaderActor);
328 // Verify both complete successfully
329 AddServerReply addServerReply = testKit.expectMsgClass(JavaTestKit.duration("5 seconds"), AddServerReply.class);
330 assertEquals("getStatus", ServerChangeStatus.OK, addServerReply.getStatus());
332 addServerReply = testKit2.expectMsgClass(JavaTestKit.duration("5 seconds"), AddServerReply.class);
333 assertEquals("getStatus", ServerChangeStatus.OK, addServerReply.getStatus());
335 // Verify ServerConfigurationPayload entries in leader's log
337 assertEquals("Leader journal last index", 1, leaderActorContext.getReplicatedLog().lastIndex());
338 assertEquals("Leader commit index", 1, leaderActorContext.getCommitIndex());
339 assertEquals("Leader last applied index", 1, leaderActorContext.getLastApplied());
340 verifyServerConfigurationPayloadEntry(leaderActorContext.getReplicatedLog(),
341 votingServer(LEADER_ID), votingServer(NEW_SERVER_ID), nonVotingServer(NEW_SERVER_ID2));
343 // Verify ServerConfigurationPayload entry in the new follower
345 MessageCollectorActor.expectMatching(newFollowerCollectorActor, ApplyState.class, 2);
347 assertEquals("New follower peers", Sets.newHashSet(LEADER_ID, NEW_SERVER_ID2),
348 newFollowerActorContext.getPeerIds());
352 public void testAddServerWithPriorSnapshotInProgress() throws Exception {
353 RaftActorContext initialActorContext = new MockRaftActorContext();
354 initialActorContext.setCommitIndex(-1);
355 initialActorContext.setLastApplied(-1);
356 initialActorContext.setReplicatedLog(new MockRaftActorContext.MockReplicatedLogBuilder().build());
358 TestActorRef<MockLeaderRaftActor> leaderActor = actorFactory.createTestActor(
359 MockLeaderRaftActor.props(ImmutableMap.<String, String>of(),
360 initialActorContext).withDispatcher(Dispatchers.DefaultDispatcherId()),
361 actorFactory.generateActorId(LEADER_ID));
363 MockLeaderRaftActor leaderRaftActor = leaderActor.underlyingActor();
364 RaftActorContext leaderActorContext = leaderRaftActor.getRaftActorContext();
366 TestActorRef<MessageCollectorActor> leaderCollectorActor = actorFactory.createTestActor(
367 MessageCollectorActor.props().withDispatcher(Dispatchers.DefaultDispatcherId()),
368 actorFactory.generateActorId(LEADER_ID + "Collector"));
369 leaderRaftActor.setCollectorActor(leaderCollectorActor);
371 // Drop commit message for now to delay snapshot completion
372 leaderRaftActor.setDropMessageOfType(String.class);
374 leaderActor.tell(new InitiateCaptureSnapshot(), leaderActor);
376 String commitMsg = expectFirstMatching(leaderCollectorActor, String.class);
378 leaderActor.tell(new AddServer(NEW_SERVER_ID, newFollowerRaftActor.path().toString(), true), testKit.getRef());
380 leaderRaftActor.setDropMessageOfType(null);
381 leaderActor.tell(commitMsg, leaderActor);
383 AddServerReply addServerReply = testKit.expectMsgClass(JavaTestKit.duration("5 seconds"), AddServerReply.class);
384 assertEquals("getStatus", ServerChangeStatus.OK, addServerReply.getStatus());
385 assertEquals("getLeaderHint", LEADER_ID, addServerReply.getLeaderHint());
387 expectFirstMatching(newFollowerCollectorActor, ApplySnapshot.class);
389 // Verify ServerConfigurationPayload entry in leader's log
391 assertEquals("Leader journal last index", 0, leaderActorContext.getReplicatedLog().lastIndex());
392 assertEquals("Leader commit index", 0, leaderActorContext.getCommitIndex());
393 assertEquals("Leader last applied index", 0, leaderActorContext.getLastApplied());
394 verifyServerConfigurationPayloadEntry(leaderActorContext.getReplicatedLog(), votingServer(LEADER_ID),
395 votingServer(NEW_SERVER_ID));
399 public void testAddServerWithPriorSnapshotCompleteTimeout() throws Exception {
400 RaftActorContext initialActorContext = new MockRaftActorContext();
401 initialActorContext.setCommitIndex(-1);
402 initialActorContext.setLastApplied(-1);
403 initialActorContext.setReplicatedLog(new MockRaftActorContext.MockReplicatedLogBuilder().build());
405 TestActorRef<MockLeaderRaftActor> leaderActor = actorFactory.createTestActor(
406 MockLeaderRaftActor.props(ImmutableMap.<String, String>of(),
407 initialActorContext).withDispatcher(Dispatchers.DefaultDispatcherId()),
408 actorFactory.generateActorId(LEADER_ID));
410 MockLeaderRaftActor leaderRaftActor = leaderActor.underlyingActor();
411 RaftActorContext leaderActorContext = leaderRaftActor.getRaftActorContext();
413 ((DefaultConfigParamsImpl)leaderActorContext.getConfigParams()).setElectionTimeoutFactor(1);
415 TestActorRef<MessageCollectorActor> leaderCollectorActor = actorFactory.createTestActor(
416 MessageCollectorActor.props().withDispatcher(Dispatchers.DefaultDispatcherId()),
417 actorFactory.generateActorId(LEADER_ID + "Collector"));
418 leaderRaftActor.setCollectorActor(leaderCollectorActor);
420 // Drop commit message so the snapshot doesn't complete.
421 leaderRaftActor.setDropMessageOfType(String.class);
423 leaderActor.tell(new InitiateCaptureSnapshot(), leaderActor);
425 leaderActor.tell(new AddServer(NEW_SERVER_ID, newFollowerRaftActor.path().toString(), true), testKit.getRef());
427 AddServerReply addServerReply = testKit.expectMsgClass(JavaTestKit.duration("5 seconds"), AddServerReply.class);
428 assertEquals("getStatus", ServerChangeStatus.TIMEOUT, addServerReply.getStatus());
430 assertEquals("Leader peers size", 0, leaderActorContext.getPeerIds().size());
434 public void testAddServerWithLeaderChangeBeforePriorSnapshotComplete() throws Exception {
435 RaftActorContext initialActorContext = new MockRaftActorContext();
436 initialActorContext.setCommitIndex(-1);
437 initialActorContext.setLastApplied(-1);
438 initialActorContext.setReplicatedLog(new MockRaftActorContext.MockReplicatedLogBuilder().build());
440 TestActorRef<MockLeaderRaftActor> leaderActor = actorFactory.createTestActor(
441 MockLeaderRaftActor.props(ImmutableMap.<String, String>of(),
442 initialActorContext).withDispatcher(Dispatchers.DefaultDispatcherId()),
443 actorFactory.generateActorId(LEADER_ID));
445 MockLeaderRaftActor leaderRaftActor = leaderActor.underlyingActor();
446 RaftActorContext leaderActorContext = leaderRaftActor.getRaftActorContext();
447 ((DefaultConfigParamsImpl)leaderActorContext.getConfigParams()).setElectionTimeoutFactor(100);
449 TestActorRef<MessageCollectorActor> leaderCollectorActor = actorFactory.createTestActor(
450 MessageCollectorActor.props().withDispatcher(Dispatchers.DefaultDispatcherId()),
451 actorFactory.generateActorId(LEADER_ID + "Collector"));
452 leaderRaftActor.setCollectorActor(leaderCollectorActor);
454 // Drop the commit message so the snapshot doesn't complete yet.
455 leaderRaftActor.setDropMessageOfType(String.class);
457 leaderActor.tell(new InitiateCaptureSnapshot(), leaderActor);
459 leaderActor.tell(new AddServer(NEW_SERVER_ID, newFollowerRaftActor.path().toString(), true), testKit.getRef());
461 String commitMsg = expectFirstMatching(leaderCollectorActor, String.class);
463 // Change the leader behavior to follower
464 leaderActor.tell(new Follower(leaderActorContext), leaderActor);
466 // Drop CaptureSnapshotReply in case install snapshot is incorrectly initiated after the prior
467 // snapshot completes. This will prevent the invalid snapshot from completing and fail the
468 // isCapturing assertion below.
469 leaderRaftActor.setDropMessageOfType(CaptureSnapshotReply.class);
471 // Complete the prior snapshot - this should be a no-op b/c it's no longer the leader
472 leaderActor.tell(commitMsg, leaderActor);
474 leaderActor.tell(new FollowerCatchUpTimeout(NEW_SERVER_ID), leaderActor);
476 AddServerReply addServerReply = testKit.expectMsgClass(JavaTestKit.duration("5 seconds"), AddServerReply.class);
477 assertEquals("getStatus", ServerChangeStatus.NO_LEADER, addServerReply.getStatus());
479 assertEquals("Leader peers size", 0, leaderActorContext.getPeerIds().size());
480 assertEquals("isCapturing", false, leaderActorContext.getSnapshotManager().isCapturing());
484 public void testAddServerWithLeaderChangeDuringInstallSnapshot() throws Exception {
485 RaftActorContext initialActorContext = new MockRaftActorContext();
486 initialActorContext.setCommitIndex(-1);
487 initialActorContext.setLastApplied(-1);
488 initialActorContext.setReplicatedLog(new MockRaftActorContext.MockReplicatedLogBuilder().build());
490 TestActorRef<MockLeaderRaftActor> leaderActor = actorFactory.createTestActor(
491 MockLeaderRaftActor.props(ImmutableMap.<String, String>of(),
492 initialActorContext).withDispatcher(Dispatchers.DefaultDispatcherId()),
493 actorFactory.generateActorId(LEADER_ID));
495 MockLeaderRaftActor leaderRaftActor = leaderActor.underlyingActor();
496 RaftActorContext leaderActorContext = leaderRaftActor.getRaftActorContext();
498 ((DefaultConfigParamsImpl)leaderActorContext.getConfigParams()).setElectionTimeoutFactor(8);
500 TestActorRef<MessageCollectorActor> leaderCollectorActor = actorFactory.createTestActor(
501 MessageCollectorActor.props().withDispatcher(Dispatchers.DefaultDispatcherId()),
502 actorFactory.generateActorId(LEADER_ID + "Collector"));
503 leaderRaftActor.setCollectorActor(leaderCollectorActor);
505 // Drop the UnInitializedFollowerSnapshotReply to delay it.
506 leaderRaftActor.setDropMessageOfType(UnInitializedFollowerSnapshotReply.class);
508 leaderActor.tell(new AddServer(NEW_SERVER_ID, newFollowerRaftActor.path().toString(), true), testKit.getRef());
510 UnInitializedFollowerSnapshotReply snapshotReply = expectFirstMatching(leaderCollectorActor,
511 UnInitializedFollowerSnapshotReply.class);
513 // Prevent election timeout when the leader switches to follower
514 ((DefaultConfigParamsImpl)leaderActorContext.getConfigParams()).setElectionTimeoutFactor(100);
516 // Change the leader behavior to follower
517 leaderActor.tell(new Follower(leaderActorContext), leaderActor);
519 // Send the captured UnInitializedFollowerSnapshotReply - should be a no-op
520 leaderRaftActor.setDropMessageOfType(null);
521 leaderActor.tell(snapshotReply, leaderActor);
523 AddServerReply addServerReply = testKit.expectMsgClass(JavaTestKit.duration("5 seconds"), AddServerReply.class);
524 assertEquals("getStatus", ServerChangeStatus.NO_LEADER, addServerReply.getStatus());
526 assertEquals("Leader peers size", 0, leaderActorContext.getPeerIds().size());
530 public void testAddServerWithInstallSnapshotTimeout() throws Exception {
531 RaftActorContext initialActorContext = new MockRaftActorContext();
532 initialActorContext.setCommitIndex(-1);
533 initialActorContext.setLastApplied(-1);
534 initialActorContext.setReplicatedLog(new MockRaftActorContext.MockReplicatedLogBuilder().build());
536 TestActorRef<MockLeaderRaftActor> leaderActor = actorFactory.createTestActor(
537 MockLeaderRaftActor.props(ImmutableMap.<String, String>of(),
538 initialActorContext).withDispatcher(Dispatchers.DefaultDispatcherId()),
539 actorFactory.generateActorId(LEADER_ID));
541 MockLeaderRaftActor leaderRaftActor = leaderActor.underlyingActor();
542 RaftActorContext leaderActorContext = leaderRaftActor.getRaftActorContext();
543 ((DefaultConfigParamsImpl)leaderActorContext.getConfigParams()).setElectionTimeoutFactor(1);
545 // Drop the InstallSnapshot message so it times out
546 newFollowerRaftActor.underlyingActor().setDropMessageOfType(InstallSnapshot.SERIALIZABLE_CLASS);
548 leaderActor.tell(new AddServer(NEW_SERVER_ID, newFollowerRaftActor.path().toString(), true), testKit.getRef());
550 leaderActor.tell(new UnInitializedFollowerSnapshotReply("bogus"), leaderActor);
552 AddServerReply addServerReply = testKit.expectMsgClass(JavaTestKit.duration("5 seconds"), AddServerReply.class);
553 assertEquals("getStatus", ServerChangeStatus.TIMEOUT, addServerReply.getStatus());
555 assertEquals("Leader peers size", 0, leaderActorContext.getPeerIds().size());
556 assertEquals("Leader followers size", 0,
557 ((AbstractLeader)leaderRaftActor.getCurrentBehavior()).getFollowerIds().size());
561 public void testAddServerWithNoLeader() {
562 DefaultConfigParamsImpl configParams = new DefaultConfigParamsImpl();
563 configParams.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
565 TestActorRef<MockRaftActor> noLeaderActor = actorFactory.createTestActor(
566 MockRaftActor.props(LEADER_ID, ImmutableMap.<String,String>of(FOLLOWER_ID, followerActor.path().toString()),
567 Optional.<ConfigParams>of(configParams), NO_PERSISTENCE).withDispatcher(Dispatchers.DefaultDispatcherId()),
568 actorFactory.generateActorId(LEADER_ID));
569 noLeaderActor.underlyingActor().waitForInitializeBehaviorComplete();
571 noLeaderActor.tell(new AddServer(NEW_SERVER_ID, newFollowerRaftActor.path().toString(), true), testKit.getRef());
572 AddServerReply addServerReply = testKit.expectMsgClass(JavaTestKit.duration("5 seconds"), AddServerReply.class);
573 assertEquals("getStatus", ServerChangeStatus.NO_LEADER, addServerReply.getStatus());
577 public void testAddServerForwardedToLeader() {
578 DefaultConfigParamsImpl configParams = new DefaultConfigParamsImpl();
579 configParams.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
581 TestActorRef<MessageCollectorActor> leaderActor = actorFactory.createTestActor(
582 MessageCollectorActor.props().withDispatcher(Dispatchers.DefaultDispatcherId()),
583 actorFactory.generateActorId(LEADER_ID));
585 TestActorRef<MockRaftActor> followerRaftActor = actorFactory.createTestActor(
586 MockRaftActor.props(FOLLOWER_ID, ImmutableMap.<String,String>of(LEADER_ID, leaderActor.path().toString()),
587 Optional.<ConfigParams>of(configParams), NO_PERSISTENCE).withDispatcher(Dispatchers.DefaultDispatcherId()),
588 actorFactory.generateActorId(FOLLOWER_ID));
589 followerRaftActor.underlyingActor().waitForInitializeBehaviorComplete();
591 followerRaftActor.tell(new AppendEntries(1, LEADER_ID, 0, 1, Collections.<ReplicatedLogEntry>emptyList(),
592 -1, -1, (short)0), leaderActor);
594 followerRaftActor.tell(new AddServer(NEW_SERVER_ID, newFollowerRaftActor.path().toString(), true), testKit.getRef());
595 expectFirstMatching(leaderActor, AddServer.class);
598 private ServerInfo votingServer(String id) {
599 return new ServerInfo(id, true);
602 private ServerInfo nonVotingServer(String id) {
603 return new ServerInfo(id, false);
606 private static void verifyServerConfigurationPayloadEntry(ReplicatedLog log, ServerInfo... expected) {
607 ReplicatedLogEntry logEntry = log.get(log.lastIndex());
608 assertEquals("Last log entry payload class", ServerConfigurationPayload.class, logEntry.getData().getClass());
609 ServerConfigurationPayload payload = (ServerConfigurationPayload)logEntry.getData();
610 assertEquals("getNewServerConfig", Sets.newHashSet(expected), Sets.newHashSet(payload.getServerConfig()));
613 private static RaftActorContext newFollowerContext(String id, TestActorRef<? extends UntypedActor> actor) {
614 DefaultConfigParamsImpl configParams = new DefaultConfigParamsImpl();
615 configParams.setHeartBeatInterval(new FiniteDuration(100, TimeUnit.MILLISECONDS));
616 configParams.setElectionTimeoutFactor(100000);
617 ElectionTermImpl termInfo = new ElectionTermImpl(NO_PERSISTENCE, id, LOG);
618 termInfo.update(1, LEADER_ID);
619 RaftActorContext followerActorContext = new RaftActorContextImpl(actor, actor.underlyingActor().getContext(),
620 id, termInfo, -1, -1,
621 ImmutableMap.of(LEADER_ID, ""), configParams, NO_PERSISTENCE, LOG);
622 followerActorContext.setCommitIndex(-1);
623 followerActorContext.setLastApplied(-1);
624 followerActorContext.setReplicatedLog(new MockRaftActorContext.MockReplicatedLogBuilder().build());
626 return followerActorContext;
629 static abstract class AbstractMockRaftActor extends MockRaftActor {
630 private volatile TestActorRef<MessageCollectorActor> collectorActor;
631 private volatile Class<?> dropMessageOfType;
633 AbstractMockRaftActor(String id, Map<String, String> peerAddresses, Optional<ConfigParams> config,
634 DataPersistenceProvider dataPersistenceProvider, TestActorRef<MessageCollectorActor> collectorActor) {
635 super(id, peerAddresses, config, dataPersistenceProvider);
636 this.collectorActor = collectorActor;
639 void setDropMessageOfType(Class<?> dropMessageOfType) {
640 this.dropMessageOfType = dropMessageOfType;
643 void setCollectorActor(TestActorRef<MessageCollectorActor> collectorActor) {
644 this.collectorActor = collectorActor;
648 public void handleCommand(Object message) {
649 if(dropMessageOfType == null || !dropMessageOfType.equals(message.getClass())) {
650 super.handleCommand(message);
653 if(collectorActor != null) {
654 collectorActor.tell(message, getSender());
659 public static class MockLeaderRaftActor extends AbstractMockRaftActor {
660 public MockLeaderRaftActor(Map<String, String> peerAddresses, ConfigParams config,
661 RaftActorContext fromContext) {
662 super(LEADER_ID, peerAddresses, Optional.of(config), NO_PERSISTENCE, null);
663 setPersistence(false);
665 RaftActorContext context = getRaftActorContext();
666 for(int i = 0; i < fromContext.getReplicatedLog().size(); i++) {
667 ReplicatedLogEntry entry = fromContext.getReplicatedLog().get(i);
668 getState().add(entry.getData());
669 context.getReplicatedLog().append(entry);
672 context.setCommitIndex(fromContext.getCommitIndex());
673 context.setLastApplied(fromContext.getLastApplied());
674 context.getTermInformation().update(fromContext.getTermInformation().getCurrentTerm(),
675 fromContext.getTermInformation().getVotedFor());
679 protected void initializeBehavior() {
680 changeCurrentBehavior(new Leader(getRaftActorContext()));
681 initializeBehaviorComplete.countDown();
685 public void createSnapshot(ActorRef actorRef) {
687 actorRef.tell(new CaptureSnapshotReply(RaftActorTest.fromObject(getState()).toByteArray()), actorRef);
688 } catch (Exception e) {
689 LOG.error("createSnapshot failed", e);
693 static Props props(Map<String, String> peerAddresses, RaftActorContext fromContext) {
694 DefaultConfigParamsImpl configParams = new DefaultConfigParamsImpl();
695 configParams.setHeartBeatInterval(new FiniteDuration(100, TimeUnit.MILLISECONDS));
696 configParams.setElectionTimeoutFactor(10);
697 return Props.create(MockLeaderRaftActor.class, peerAddresses, configParams, fromContext);
701 public static class MockNewFollowerRaftActor extends AbstractMockRaftActor {
702 public MockNewFollowerRaftActor(ConfigParams config, TestActorRef<MessageCollectorActor> collectorActor) {
703 super(NEW_SERVER_ID, Maps.<String, String>newHashMap(), Optional.of(config), null, collectorActor);
706 static Props props(ConfigParams config, TestActorRef<MessageCollectorActor> collectorActor) {
707 return Props.create(MockNewFollowerRaftActor.class, config, collectorActor);