9c7322d2166cc6d6f414adf14adb188a8b6a0da4
[controller.git] / opendaylight / md-sal / sal-akka-raft / src / test / java / org / opendaylight / controller / cluster / raft / RaftActorServerConfigurationSupportTest.java
1 /*
2  * Copyright (c) 2015 Brocade Communications 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 package org.opendaylight.controller.cluster.raft;
9
10 import static org.junit.Assert.assertEquals;
11 import static org.junit.Assert.assertTrue;
12 import static org.junit.Assert.fail;
13 import static org.opendaylight.controller.cluster.raft.utils.MessageCollectorActor.assertNoneMatching;
14 import static org.opendaylight.controller.cluster.raft.utils.MessageCollectorActor.clearMessages;
15 import static org.opendaylight.controller.cluster.raft.utils.MessageCollectorActor.expectFirstMatching;
16 import static org.opendaylight.controller.cluster.raft.utils.MessageCollectorActor.expectMatching;
17
18 import akka.actor.ActorRef;
19 import akka.actor.Props;
20 import akka.actor.UntypedActor;
21 import akka.dispatch.Dispatchers;
22 import akka.testkit.JavaTestKit;
23 import akka.testkit.TestActorRef;
24 import com.google.common.base.Optional;
25 import com.google.common.base.Stopwatch;
26 import com.google.common.collect.ImmutableMap;
27 import com.google.common.collect.Maps;
28 import com.google.common.collect.Sets;
29 import java.util.Arrays;
30 import java.util.Collections;
31 import java.util.List;
32 import java.util.Map;
33 import java.util.concurrent.TimeUnit;
34 import org.junit.After;
35 import org.junit.Before;
36 import org.junit.Test;
37 import org.opendaylight.controller.cluster.NonPersistentDataProvider;
38 import org.opendaylight.controller.cluster.raft.base.messages.ApplySnapshot;
39 import org.opendaylight.controller.cluster.raft.base.messages.ApplyState;
40 import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshotReply;
41 import org.opendaylight.controller.cluster.raft.base.messages.ElectionTimeout;
42 import org.opendaylight.controller.cluster.raft.base.messages.InitiateCaptureSnapshot;
43 import org.opendaylight.controller.cluster.raft.base.messages.TimeoutNow;
44 import org.opendaylight.controller.cluster.raft.behaviors.AbstractLeader;
45 import org.opendaylight.controller.cluster.raft.behaviors.Follower;
46 import org.opendaylight.controller.cluster.raft.behaviors.Leader;
47 import org.opendaylight.controller.cluster.raft.behaviors.RaftActorBehavior;
48 import org.opendaylight.controller.cluster.raft.messages.AddServer;
49 import org.opendaylight.controller.cluster.raft.messages.AddServerReply;
50 import org.opendaylight.controller.cluster.raft.messages.AppendEntries;
51 import org.opendaylight.controller.cluster.raft.messages.ChangeServersVotingStatus;
52 import org.opendaylight.controller.cluster.raft.messages.InstallSnapshot;
53 import org.opendaylight.controller.cluster.raft.messages.RemoveServer;
54 import org.opendaylight.controller.cluster.raft.messages.RemoveServerReply;
55 import org.opendaylight.controller.cluster.raft.messages.RequestVote;
56 import org.opendaylight.controller.cluster.raft.messages.ServerChangeReply;
57 import org.opendaylight.controller.cluster.raft.messages.ServerChangeStatus;
58 import org.opendaylight.controller.cluster.raft.messages.ServerRemoved;
59 import org.opendaylight.controller.cluster.raft.messages.UnInitializedFollowerSnapshotReply;
60 import org.opendaylight.controller.cluster.raft.persisted.ApplyJournalEntries;
61 import org.opendaylight.controller.cluster.raft.persisted.ServerConfigurationPayload;
62 import org.opendaylight.controller.cluster.raft.persisted.ServerInfo;
63 import org.opendaylight.controller.cluster.raft.persisted.UpdateElectionTerm;
64 import org.opendaylight.controller.cluster.raft.policy.DisableElectionsRaftPolicy;
65 import org.opendaylight.controller.cluster.raft.utils.ForwardMessageToBehaviorActor;
66 import org.opendaylight.controller.cluster.raft.utils.InMemoryJournal;
67 import org.opendaylight.controller.cluster.raft.utils.InMemorySnapshotStore;
68 import org.opendaylight.controller.cluster.raft.utils.MessageCollectorActor;
69 import org.slf4j.Logger;
70 import org.slf4j.LoggerFactory;
71 import scala.concurrent.duration.FiniteDuration;
72
73 /**
74  * Unit tests for RaftActorServerConfigurationSupport.
75  *
76  * @author Thomas Pantelis
77  */
78 public class RaftActorServerConfigurationSupportTest extends AbstractActorTest {
79     static final String LEADER_ID = "leader";
80     static final String FOLLOWER_ID = "follower";
81     static final String FOLLOWER_ID2 = "follower2";
82     static final String NEW_SERVER_ID = "new-server";
83     static final String NEW_SERVER_ID2 = "new-server2";
84     private static final Logger LOG = LoggerFactory.getLogger(RaftActorServerConfigurationSupportTest.class);
85     private static final Class<?> COMMIT_MESSAGE_CLASS = RaftActorSnapshotMessageSupport.COMMIT_SNAPSHOT.getClass();
86     private static final boolean NO_PERSISTENCE = false;
87     private static final boolean PERSISTENT = true;
88
89     private final TestActorFactory actorFactory = new TestActorFactory(getSystem());
90
91     private final TestActorRef<ForwardMessageToBehaviorActor> followerActor = actorFactory.createTestActor(
92             Props.create(ForwardMessageToBehaviorActor.class).withDispatcher(Dispatchers.DefaultDispatcherId()),
93             actorFactory.generateActorId(FOLLOWER_ID));
94
95     private TestActorRef<MockNewFollowerRaftActor> newFollowerRaftActor;
96     private TestActorRef<MessageCollectorActor> newFollowerCollectorActor;
97     private RaftActorContext newFollowerActorContext;
98
99     private final JavaTestKit testKit = new JavaTestKit(getSystem());
100
101     @Before
102     public void setup() {
103         InMemoryJournal.clear();
104         InMemorySnapshotStore.clear();
105     }
106
107     @SuppressWarnings("checkstyle:IllegalCatch")
108     private void setupNewFollower() {
109         DefaultConfigParamsImpl configParams = newFollowerConfigParams();
110
111         newFollowerCollectorActor = actorFactory.createTestActor(
112                 MessageCollectorActor.props().withDispatcher(Dispatchers.DefaultDispatcherId()),
113                 actorFactory.generateActorId(NEW_SERVER_ID + "Collector"));
114         newFollowerRaftActor = actorFactory.createTestActor(MockNewFollowerRaftActor.props(
115                 configParams, newFollowerCollectorActor).withDispatcher(Dispatchers.DefaultDispatcherId()),
116                 actorFactory.generateActorId(NEW_SERVER_ID));
117
118         try {
119             newFollowerActorContext = newFollowerRaftActor.underlyingActor().getRaftActorContext();
120         } catch (Exception e) {
121             newFollowerActorContext = newFollowerRaftActor.underlyingActor().getRaftActorContext();
122         }
123     }
124
125     private static DefaultConfigParamsImpl newFollowerConfigParams() {
126         DefaultConfigParamsImpl configParams = new DefaultConfigParamsImpl();
127         configParams.setHeartBeatInterval(new FiniteDuration(100, TimeUnit.MILLISECONDS));
128         configParams.setElectionTimeoutFactor(100000);
129         configParams.setCustomRaftPolicyImplementationClass(DisableElectionsRaftPolicy.class.getName());
130         return configParams;
131     }
132
133     @After
134     public void tearDown() throws Exception {
135         actorFactory.close();
136     }
137
138     @Test
139     public void testAddServerWithExistingFollower() throws Exception {
140         LOG.info("testAddServerWithExistingFollower starting");
141         setupNewFollower();
142         RaftActorContextImpl followerActorContext = newFollowerContext(FOLLOWER_ID, followerActor);
143         followerActorContext.setReplicatedLog(new MockRaftActorContext.MockReplicatedLogBuilder().createEntries(
144                 0, 3, 1).build());
145         followerActorContext.setCommitIndex(2);
146         followerActorContext.setLastApplied(2);
147
148         Follower follower = new Follower(followerActorContext);
149         followerActor.underlyingActor().setBehavior(follower);
150         followerActorContext.setCurrentBehavior(follower);
151
152         TestActorRef<MockLeaderRaftActor> leaderActor = actorFactory.createTestActor(
153                 MockLeaderRaftActor.props(ImmutableMap.of(FOLLOWER_ID, followerActor.path().toString()),
154                         followerActorContext).withDispatcher(Dispatchers.DefaultDispatcherId()),
155                 actorFactory.generateActorId(LEADER_ID));
156
157         // Expect initial heartbeat from the leader.
158         expectFirstMatching(followerActor, AppendEntries.class);
159         clearMessages(followerActor);
160
161         MockLeaderRaftActor leaderRaftActor = leaderActor.underlyingActor();
162         final TestActorRef<MessageCollectorActor> leaderCollectorActor = newLeaderCollectorActor(leaderRaftActor);
163
164         leaderActor.tell(new AddServer(NEW_SERVER_ID, newFollowerRaftActor.path().toString(), true), testKit.getRef());
165
166         // Leader should install snapshot - capture and verify ApplySnapshot contents
167
168         ApplySnapshot applySnapshot = expectFirstMatching(newFollowerCollectorActor, ApplySnapshot.class);
169         @SuppressWarnings("unchecked")
170         List<Object> snapshotState = (List<Object>) MockRaftActor.toObject(applySnapshot.getSnapshot().getState());
171         assertEquals("Snapshot state", snapshotState, leaderRaftActor.getState());
172
173         AddServerReply addServerReply = testKit.expectMsgClass(JavaTestKit.duration("5 seconds"), AddServerReply.class);
174         assertEquals("getStatus", ServerChangeStatus.OK, addServerReply.getStatus());
175         assertEquals("getLeaderHint", LEADER_ID, addServerReply.getLeaderHint().get());
176
177         // Verify ServerConfigurationPayload entry in leader's log
178
179         expectFirstMatching(leaderCollectorActor, ApplyState.class);
180         RaftActorContext leaderActorContext = leaderRaftActor.getRaftActorContext();
181         assertEquals("Leader journal last index", 3, leaderActorContext.getReplicatedLog().lastIndex());
182         assertEquals("Leader commit index", 3, leaderActorContext.getCommitIndex());
183         assertEquals("Leader last applied index", 3, leaderActorContext.getLastApplied());
184         verifyServerConfigurationPayloadEntry(leaderActorContext.getReplicatedLog(), votingServer(LEADER_ID),
185                 votingServer(FOLLOWER_ID), votingServer(NEW_SERVER_ID));
186
187         // Verify ServerConfigurationPayload entry in both followers
188
189         expectFirstMatching(followerActor, ApplyState.class);
190         assertEquals("Follower journal last index", 3, followerActorContext.getReplicatedLog().lastIndex());
191         verifyServerConfigurationPayloadEntry(followerActorContext.getReplicatedLog(), votingServer(LEADER_ID),
192                 votingServer(FOLLOWER_ID), votingServer(NEW_SERVER_ID));
193
194         expectFirstMatching(newFollowerCollectorActor, ApplyState.class);
195         assertEquals("New follower journal last index", 3, newFollowerActorContext.getReplicatedLog().lastIndex());
196         verifyServerConfigurationPayloadEntry(newFollowerActorContext.getReplicatedLog(), votingServer(LEADER_ID),
197                 votingServer(FOLLOWER_ID), votingServer(NEW_SERVER_ID));
198
199         // Verify new server config was applied in both followers
200
201         assertEquals("Follower peers", Sets.newHashSet(LEADER_ID, NEW_SERVER_ID), followerActorContext.getPeerIds());
202
203         assertEquals("New follower peers", Sets.newHashSet(LEADER_ID, FOLLOWER_ID),
204                 newFollowerActorContext.getPeerIds());
205
206         expectFirstMatching(newFollowerCollectorActor, ApplyState.class);
207         expectFirstMatching(followerActor, ApplyState.class);
208
209         assertEquals("Follower commit index", 3, followerActorContext.getCommitIndex());
210         assertEquals("Follower last applied index", 3, followerActorContext.getLastApplied());
211         assertEquals("New follower commit index", 3, newFollowerActorContext.getCommitIndex());
212         assertEquals("New follower last applied index", 3, newFollowerActorContext.getLastApplied());
213
214         assertEquals("Leader persisted ReplicatedLogImplEntry entries", 0,
215                 InMemoryJournal.get(LEADER_ID, ReplicatedLogImplEntry.class).size());
216         assertEquals("Leader persisted ServerConfigurationPayload entries", 1,
217                 InMemoryJournal.get(LEADER_ID, ServerConfigurationPayload.class).size());
218
219         assertEquals("New follower persisted ReplicatedLogImplEntry entries", 0,
220                 InMemoryJournal.get(NEW_SERVER_ID, ReplicatedLogImplEntry.class).size());
221         assertEquals("New follower persisted ServerConfigurationPayload entries", 1,
222                 InMemoryJournal.get(NEW_SERVER_ID, ServerConfigurationPayload.class).size());
223
224         LOG.info("testAddServerWithExistingFollower ending");
225     }
226
227     @Test
228     public void testAddServerWithNoExistingFollower() throws Exception {
229         LOG.info("testAddServerWithNoExistingFollower starting");
230
231         setupNewFollower();
232         RaftActorContext initialActorContext = new MockRaftActorContext();
233         initialActorContext.setCommitIndex(1);
234         initialActorContext.setLastApplied(1);
235         initialActorContext.setReplicatedLog(new MockRaftActorContext.MockReplicatedLogBuilder().createEntries(
236                 0, 2, 1).build());
237
238         TestActorRef<MockLeaderRaftActor> leaderActor = actorFactory.createTestActor(
239                 MockLeaderRaftActor.props(ImmutableMap.<String, String>of(),
240                         initialActorContext).withDispatcher(Dispatchers.DefaultDispatcherId()),
241                 actorFactory.generateActorId(LEADER_ID));
242
243         MockLeaderRaftActor leaderRaftActor = leaderActor.underlyingActor();
244         final RaftActorContext leaderActorContext = leaderRaftActor.getRaftActorContext();
245
246         final TestActorRef<MessageCollectorActor> leaderCollectorActor = newLeaderCollectorActor(leaderRaftActor);
247
248         leaderActor.tell(new AddServer(NEW_SERVER_ID, newFollowerRaftActor.path().toString(), true), testKit.getRef());
249
250         // Leader should install snapshot - capture and verify ApplySnapshot contents
251
252         ApplySnapshot applySnapshot = expectFirstMatching(newFollowerCollectorActor, ApplySnapshot.class);
253         @SuppressWarnings("unchecked")
254         List<Object> snapshotState = (List<Object>) MockRaftActor.toObject(applySnapshot.getSnapshot().getState());
255         assertEquals("Snapshot state", snapshotState, leaderRaftActor.getState());
256
257         AddServerReply addServerReply = testKit.expectMsgClass(JavaTestKit.duration("5 seconds"), AddServerReply.class);
258         assertEquals("getStatus", ServerChangeStatus.OK, addServerReply.getStatus());
259         assertEquals("getLeaderHint", LEADER_ID, addServerReply.getLeaderHint().get());
260
261         // Verify ServerConfigurationPayload entry in leader's log
262
263         expectFirstMatching(leaderCollectorActor, ApplyState.class);
264         assertEquals("Leader journal last index", 2, leaderActorContext.getReplicatedLog().lastIndex());
265         assertEquals("Leader commit index", 2, leaderActorContext.getCommitIndex());
266         assertEquals("Leader last applied index", 2, leaderActorContext.getLastApplied());
267         verifyServerConfigurationPayloadEntry(leaderActorContext.getReplicatedLog(), votingServer(LEADER_ID),
268                 votingServer(NEW_SERVER_ID));
269
270         // Verify ServerConfigurationPayload entry in the new follower
271
272         expectFirstMatching(newFollowerCollectorActor, ApplyState.class);
273         assertEquals("New follower journal last index", 2, newFollowerActorContext.getReplicatedLog().lastIndex());
274         verifyServerConfigurationPayloadEntry(newFollowerActorContext.getReplicatedLog(), votingServer(LEADER_ID),
275                 votingServer(NEW_SERVER_ID));
276
277         // Verify new server config was applied in the new follower
278
279         assertEquals("New follower peers", Sets.newHashSet(LEADER_ID), newFollowerActorContext.getPeerIds());
280
281         LOG.info("testAddServerWithNoExistingFollower ending");
282     }
283
284     @Test
285     public void testAddServersAsNonVoting() throws Exception {
286         LOG.info("testAddServersAsNonVoting starting");
287
288         setupNewFollower();
289         RaftActorContext initialActorContext = new MockRaftActorContext();
290
291         TestActorRef<MockLeaderRaftActor> leaderActor = actorFactory.createTestActor(
292                 MockLeaderRaftActor.props(ImmutableMap.<String, String>of(),
293                         initialActorContext).withDispatcher(Dispatchers.DefaultDispatcherId()),
294                 actorFactory.generateActorId(LEADER_ID));
295
296         MockLeaderRaftActor leaderRaftActor = leaderActor.underlyingActor();
297         final RaftActorContext leaderActorContext = leaderRaftActor.getRaftActorContext();
298
299         final TestActorRef<MessageCollectorActor> leaderCollectorActor = newLeaderCollectorActor(leaderRaftActor);
300
301         leaderActor.tell(new AddServer(NEW_SERVER_ID, newFollowerRaftActor.path().toString(), false), testKit.getRef());
302
303         AddServerReply addServerReply = testKit.expectMsgClass(JavaTestKit.duration("5 seconds"), AddServerReply.class);
304         assertEquals("getStatus", ServerChangeStatus.OK, addServerReply.getStatus());
305         assertEquals("getLeaderHint", LEADER_ID, addServerReply.getLeaderHint().get());
306
307         // Verify ServerConfigurationPayload entry in leader's log
308
309         expectFirstMatching(leaderCollectorActor, ApplyState.class);
310
311         assertEquals("Leader journal last index", 0, leaderActorContext.getReplicatedLog().lastIndex());
312         assertEquals("Leader commit index", 0, leaderActorContext.getCommitIndex());
313         assertEquals("Leader last applied index", 0, leaderActorContext.getLastApplied());
314         verifyServerConfigurationPayloadEntry(leaderActorContext.getReplicatedLog(), votingServer(LEADER_ID),
315                 nonVotingServer(NEW_SERVER_ID));
316
317         // Verify ServerConfigurationPayload entry in the new follower
318
319         expectFirstMatching(newFollowerCollectorActor, ApplyState.class);
320         assertEquals("New follower journal last index", 0, newFollowerActorContext.getReplicatedLog().lastIndex());
321         verifyServerConfigurationPayloadEntry(newFollowerActorContext.getReplicatedLog(), votingServer(LEADER_ID),
322                 nonVotingServer(NEW_SERVER_ID));
323
324         // Verify new server config was applied in the new follower
325
326         assertEquals("New follower peers", Sets.newHashSet(LEADER_ID), newFollowerActorContext.getPeerIds());
327
328         assertNoneMatching(newFollowerCollectorActor, InstallSnapshot.class, 500);
329
330         // Add another non-voting server.
331
332         clearMessages(leaderCollectorActor);
333
334         RaftActorContext follower2ActorContext = newFollowerContext(NEW_SERVER_ID2, followerActor);
335         Follower newFollower2 = new Follower(follower2ActorContext);
336         followerActor.underlyingActor().setBehavior(newFollower2);
337
338         leaderActor.tell(new AddServer(NEW_SERVER_ID2, followerActor.path().toString(), false), testKit.getRef());
339
340         addServerReply = testKit.expectMsgClass(JavaTestKit.duration("5 seconds"), AddServerReply.class);
341         assertEquals("getStatus", ServerChangeStatus.OK, addServerReply.getStatus());
342         assertEquals("getLeaderHint", java.util.Optional.of(LEADER_ID), addServerReply.getLeaderHint());
343
344         expectFirstMatching(leaderCollectorActor, ApplyState.class);
345         assertEquals("Leader journal last index", 1, leaderActorContext.getReplicatedLog().lastIndex());
346         assertEquals("Leader commit index", 1, leaderActorContext.getCommitIndex());
347         assertEquals("Leader last applied index", 1, leaderActorContext.getLastApplied());
348         verifyServerConfigurationPayloadEntry(leaderActorContext.getReplicatedLog(),
349                 votingServer(LEADER_ID), nonVotingServer(NEW_SERVER_ID), nonVotingServer(NEW_SERVER_ID2));
350
351         LOG.info("testAddServersAsNonVoting ending");
352     }
353
354     @Test
355     public void testAddServerWithOperationInProgress() throws Exception {
356         LOG.info("testAddServerWithOperationInProgress starting");
357
358         setupNewFollower();
359         RaftActorContext initialActorContext = new MockRaftActorContext();
360
361         TestActorRef<MockLeaderRaftActor> leaderActor = actorFactory.createTestActor(
362                 MockLeaderRaftActor.props(ImmutableMap.<String, String>of(),
363                         initialActorContext).withDispatcher(Dispatchers.DefaultDispatcherId()),
364                 actorFactory.generateActorId(LEADER_ID));
365
366         MockLeaderRaftActor leaderRaftActor = leaderActor.underlyingActor();
367         final RaftActorContext leaderActorContext = leaderRaftActor.getRaftActorContext();
368
369         final TestActorRef<MessageCollectorActor> leaderCollectorActor = newLeaderCollectorActor(leaderRaftActor);
370
371         RaftActorContext follower2ActorContext = newFollowerContext(NEW_SERVER_ID2, followerActor);
372         Follower newFollower2 = new Follower(follower2ActorContext);
373         followerActor.underlyingActor().setBehavior(newFollower2);
374
375         MockNewFollowerRaftActor newFollowerRaftActorInstance = newFollowerRaftActor.underlyingActor();
376         newFollowerRaftActorInstance.setDropMessageOfType(InstallSnapshot.class);
377
378         leaderActor.tell(new AddServer(NEW_SERVER_ID, newFollowerRaftActor.path().toString(), true), testKit.getRef());
379
380         // Wait for leader's install snapshot and capture it
381
382         InstallSnapshot installSnapshot = expectFirstMatching(newFollowerCollectorActor, InstallSnapshot.class);
383
384         // Send a second AddServer - should get queued
385         JavaTestKit testKit2 = new JavaTestKit(getSystem());
386         leaderActor.tell(new AddServer(NEW_SERVER_ID2, followerActor.path().toString(), false), testKit2.getRef());
387
388         // Continue the first AddServer
389         newFollowerRaftActorInstance.setDropMessageOfType(null);
390         newFollowerRaftActor.tell(installSnapshot, leaderActor);
391
392         // Verify both complete successfully
393         AddServerReply addServerReply = testKit.expectMsgClass(JavaTestKit.duration("5 seconds"), AddServerReply.class);
394         assertEquals("getStatus", ServerChangeStatus.OK, addServerReply.getStatus());
395
396         addServerReply = testKit2.expectMsgClass(JavaTestKit.duration("5 seconds"), AddServerReply.class);
397         assertEquals("getStatus", ServerChangeStatus.OK, addServerReply.getStatus());
398
399         // Verify ServerConfigurationPayload entries in leader's log
400
401         expectMatching(leaderCollectorActor, ApplyState.class, 2);
402         assertEquals("Leader journal last index", 1, leaderActorContext.getReplicatedLog().lastIndex());
403         assertEquals("Leader commit index", 1, leaderActorContext.getCommitIndex());
404         assertEquals("Leader last applied index", 1, leaderActorContext.getLastApplied());
405         verifyServerConfigurationPayloadEntry(leaderActorContext.getReplicatedLog(),
406                 votingServer(LEADER_ID), votingServer(NEW_SERVER_ID), nonVotingServer(NEW_SERVER_ID2));
407
408         // Verify ServerConfigurationPayload entry in the new follower
409
410         expectMatching(newFollowerCollectorActor, ApplyState.class, 2);
411         assertEquals("New follower peers", Sets.newHashSet(LEADER_ID, NEW_SERVER_ID2),
412                newFollowerActorContext.getPeerIds());
413
414         LOG.info("testAddServerWithOperationInProgress ending");
415     }
416
417     @Test
418     public void testAddServerWithPriorSnapshotInProgress() throws Exception {
419         LOG.info("testAddServerWithPriorSnapshotInProgress starting");
420
421         setupNewFollower();
422         RaftActorContext initialActorContext = new MockRaftActorContext();
423
424         TestActorRef<MockLeaderRaftActor> leaderActor = actorFactory.createTestActor(
425                 MockLeaderRaftActor.props(ImmutableMap.<String, String>of(),
426                         initialActorContext).withDispatcher(Dispatchers.DefaultDispatcherId()),
427                 actorFactory.generateActorId(LEADER_ID));
428
429         MockLeaderRaftActor leaderRaftActor = leaderActor.underlyingActor();
430         final RaftActorContext leaderActorContext = leaderRaftActor.getRaftActorContext();
431
432         TestActorRef<MessageCollectorActor> leaderCollectorActor = newLeaderCollectorActor(leaderRaftActor);
433
434         // Drop commit message for now to delay snapshot completion
435         leaderRaftActor.setDropMessageOfType(String.class);
436
437         leaderActor.tell(new InitiateCaptureSnapshot(), leaderActor);
438
439         Object commitMsg = expectFirstMatching(leaderCollectorActor, COMMIT_MESSAGE_CLASS);
440
441         leaderActor.tell(new AddServer(NEW_SERVER_ID, newFollowerRaftActor.path().toString(), true), testKit.getRef());
442
443         leaderRaftActor.setDropMessageOfType(null);
444         leaderActor.tell(commitMsg, leaderActor);
445
446         AddServerReply addServerReply = testKit.expectMsgClass(JavaTestKit.duration("5 seconds"), AddServerReply.class);
447         assertEquals("getStatus", ServerChangeStatus.OK, addServerReply.getStatus());
448         assertEquals("getLeaderHint", LEADER_ID, addServerReply.getLeaderHint().get());
449
450         expectFirstMatching(newFollowerCollectorActor, ApplySnapshot.class);
451
452         // Verify ServerConfigurationPayload entry in leader's log
453
454         expectFirstMatching(leaderCollectorActor, ApplyState.class);
455         assertEquals("Leader journal last index", 0, leaderActorContext.getReplicatedLog().lastIndex());
456         assertEquals("Leader commit index", 0, leaderActorContext.getCommitIndex());
457         assertEquals("Leader last applied index", 0, leaderActorContext.getLastApplied());
458         verifyServerConfigurationPayloadEntry(leaderActorContext.getReplicatedLog(), votingServer(LEADER_ID),
459                 votingServer(NEW_SERVER_ID));
460
461         LOG.info("testAddServerWithPriorSnapshotInProgress ending");
462     }
463
464     @Test
465     public void testAddServerWithPriorSnapshotCompleteTimeout() throws Exception {
466         LOG.info("testAddServerWithPriorSnapshotCompleteTimeout starting");
467
468         setupNewFollower();
469         RaftActorContext initialActorContext = new MockRaftActorContext();
470
471         TestActorRef<MockLeaderRaftActor> leaderActor = actorFactory.createTestActor(
472                 MockLeaderRaftActor.props(ImmutableMap.<String, String>of(),
473                         initialActorContext).withDispatcher(Dispatchers.DefaultDispatcherId()),
474                 actorFactory.generateActorId(LEADER_ID));
475
476         MockLeaderRaftActor leaderRaftActor = leaderActor.underlyingActor();
477         RaftActorContext leaderActorContext = leaderRaftActor.getRaftActorContext();
478
479         ((DefaultConfigParamsImpl)leaderActorContext.getConfigParams()).setElectionTimeoutFactor(1);
480
481         // Drop commit message so the snapshot doesn't complete.
482         leaderRaftActor.setDropMessageOfType(COMMIT_MESSAGE_CLASS);
483
484         leaderActor.tell(new InitiateCaptureSnapshot(), leaderActor);
485
486         leaderActor.tell(new AddServer(NEW_SERVER_ID, newFollowerRaftActor.path().toString(), true), testKit.getRef());
487
488         AddServerReply addServerReply = testKit.expectMsgClass(JavaTestKit.duration("5 seconds"), AddServerReply.class);
489         assertEquals("getStatus", ServerChangeStatus.TIMEOUT, addServerReply.getStatus());
490
491         assertEquals("Leader peers size", 0, leaderActorContext.getPeerIds().size());
492
493         LOG.info("testAddServerWithPriorSnapshotCompleteTimeout ending");
494     }
495
496     @Test
497     public void testAddServerWithLeaderChangeBeforePriorSnapshotComplete() throws Exception {
498         LOG.info("testAddServerWithLeaderChangeBeforePriorSnapshotComplete starting");
499
500         setupNewFollower();
501         RaftActorContext initialActorContext = new MockRaftActorContext();
502
503         TestActorRef<MockLeaderRaftActor> leaderActor = actorFactory.createTestActor(
504                 MockLeaderRaftActor.props(ImmutableMap.<String, String>of(),
505                         initialActorContext).withDispatcher(Dispatchers.DefaultDispatcherId()),
506                 actorFactory.generateActorId(LEADER_ID));
507
508         MockLeaderRaftActor leaderRaftActor = leaderActor.underlyingActor();
509         RaftActorContext leaderActorContext = leaderRaftActor.getRaftActorContext();
510         ((DefaultConfigParamsImpl)leaderActorContext.getConfigParams()).setElectionTimeoutFactor(100);
511
512         final TestActorRef<MessageCollectorActor> leaderCollectorActor = newLeaderCollectorActor(leaderRaftActor);
513
514         // Drop the commit message so the snapshot doesn't complete yet.
515         leaderRaftActor.setDropMessageOfType(COMMIT_MESSAGE_CLASS);
516
517         leaderActor.tell(new InitiateCaptureSnapshot(), leaderActor);
518
519         leaderActor.tell(new AddServer(NEW_SERVER_ID, newFollowerRaftActor.path().toString(), true), testKit.getRef());
520
521         Object commitMsg = expectFirstMatching(leaderCollectorActor, COMMIT_MESSAGE_CLASS);
522
523         // Change the leader behavior to follower
524         leaderActor.tell(new Follower(leaderActorContext), leaderActor);
525
526         // Drop CaptureSnapshotReply in case install snapshot is incorrectly initiated after the prior
527         // snapshot completes. This will prevent the invalid snapshot from completing and fail the
528         // isCapturing assertion below.
529         leaderRaftActor.setDropMessageOfType(CaptureSnapshotReply.class);
530
531         // Complete the prior snapshot - this should be a no-op b/c it's no longer the leader
532         leaderActor.tell(commitMsg, leaderActor);
533
534         leaderActor.tell(new RaftActorServerConfigurationSupport.ServerOperationTimeout(NEW_SERVER_ID), leaderActor);
535
536         AddServerReply addServerReply = testKit.expectMsgClass(JavaTestKit.duration("5 seconds"), AddServerReply.class);
537         assertEquals("getStatus", ServerChangeStatus.NO_LEADER, addServerReply.getStatus());
538
539         assertEquals("Leader peers size", 0, leaderActorContext.getPeerIds().size());
540         assertEquals("isCapturing", false, leaderActorContext.getSnapshotManager().isCapturing());
541
542         LOG.info("testAddServerWithLeaderChangeBeforePriorSnapshotComplete ending");
543     }
544
545     @Test
546     public void testAddServerWithLeaderChangeDuringInstallSnapshot() throws Exception {
547         LOG.info("testAddServerWithLeaderChangeDuringInstallSnapshot starting");
548
549         setupNewFollower();
550         RaftActorContext initialActorContext = new MockRaftActorContext();
551
552         TestActorRef<MockLeaderRaftActor> leaderActor = actorFactory.createTestActor(
553                 MockLeaderRaftActor.props(ImmutableMap.<String, String>of(),
554                         initialActorContext).withDispatcher(Dispatchers.DefaultDispatcherId()),
555                 actorFactory.generateActorId(LEADER_ID));
556
557         MockLeaderRaftActor leaderRaftActor = leaderActor.underlyingActor();
558         RaftActorContext leaderActorContext = leaderRaftActor.getRaftActorContext();
559
560         ((DefaultConfigParamsImpl)leaderActorContext.getConfigParams()).setElectionTimeoutFactor(8);
561
562         TestActorRef<MessageCollectorActor> leaderCollectorActor = newLeaderCollectorActor(leaderRaftActor);
563
564         // Drop the UnInitializedFollowerSnapshotReply to delay it.
565         leaderRaftActor.setDropMessageOfType(UnInitializedFollowerSnapshotReply.class);
566
567         leaderActor.tell(new AddServer(NEW_SERVER_ID, newFollowerRaftActor.path().toString(), true), testKit.getRef());
568
569         final UnInitializedFollowerSnapshotReply snapshotReply = expectFirstMatching(leaderCollectorActor,
570                 UnInitializedFollowerSnapshotReply.class);
571
572         // Prevent election timeout when the leader switches to follower
573         ((DefaultConfigParamsImpl)leaderActorContext.getConfigParams()).setElectionTimeoutFactor(100);
574
575         // Change the leader behavior to follower
576         leaderActor.tell(new Follower(leaderActorContext), leaderActor);
577
578         // Send the captured UnInitializedFollowerSnapshotReply - should be a no-op
579         leaderRaftActor.setDropMessageOfType(null);
580         leaderActor.tell(snapshotReply, leaderActor);
581
582         AddServerReply addServerReply = testKit.expectMsgClass(JavaTestKit.duration("5 seconds"), AddServerReply.class);
583         assertEquals("getStatus", ServerChangeStatus.NO_LEADER, addServerReply.getStatus());
584
585         assertEquals("Leader peers size", 0, leaderActorContext.getPeerIds().size());
586
587         LOG.info("testAddServerWithLeaderChangeDuringInstallSnapshot ending");
588     }
589
590     @Test
591     public void testAddServerWithInstallSnapshotTimeout() throws Exception {
592         LOG.info("testAddServerWithInstallSnapshotTimeout starting");
593
594         setupNewFollower();
595         RaftActorContext initialActorContext = new MockRaftActorContext();
596
597         TestActorRef<MockLeaderRaftActor> leaderActor = actorFactory.createTestActor(
598                 MockLeaderRaftActor.props(ImmutableMap.<String, String>of(),
599                         initialActorContext).withDispatcher(Dispatchers.DefaultDispatcherId()),
600                 actorFactory.generateActorId(LEADER_ID));
601
602         MockLeaderRaftActor leaderRaftActor = leaderActor.underlyingActor();
603         RaftActorContext leaderActorContext = leaderRaftActor.getRaftActorContext();
604         ((DefaultConfigParamsImpl)leaderActorContext.getConfigParams()).setElectionTimeoutFactor(1);
605
606         // Drop the InstallSnapshot message so it times out
607         newFollowerRaftActor.underlyingActor().setDropMessageOfType(InstallSnapshot.class);
608
609         leaderActor.tell(new AddServer(NEW_SERVER_ID, newFollowerRaftActor.path().toString(), true), testKit.getRef());
610
611         leaderActor.tell(new UnInitializedFollowerSnapshotReply("bogus"), leaderActor);
612
613         AddServerReply addServerReply = testKit.expectMsgClass(JavaTestKit.duration("5 seconds"), AddServerReply.class);
614         assertEquals("getStatus", ServerChangeStatus.TIMEOUT, addServerReply.getStatus());
615
616         assertEquals("Leader peers size", 0, leaderActorContext.getPeerIds().size());
617         assertEquals("Leader followers size", 0,
618                 ((AbstractLeader)leaderRaftActor.getCurrentBehavior()).getFollowerIds().size());
619
620         LOG.info("testAddServerWithInstallSnapshotTimeout ending");
621     }
622
623     @Test
624     public void testAddServerWithNoLeader() {
625         LOG.info("testAddServerWithNoLeader starting");
626
627         setupNewFollower();
628         DefaultConfigParamsImpl configParams = new DefaultConfigParamsImpl();
629         configParams.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
630
631         TestActorRef<MockRaftActor> noLeaderActor = actorFactory.createTestActor(
632                 MockRaftActor.builder().id(LEADER_ID).peerAddresses(ImmutableMap.of(FOLLOWER_ID,
633                         followerActor.path().toString())).config(configParams).persistent(Optional.of(false))
634                         .props().withDispatcher(Dispatchers.DefaultDispatcherId()),
635                 actorFactory.generateActorId(LEADER_ID));
636         noLeaderActor.underlyingActor().waitForInitializeBehaviorComplete();
637
638         noLeaderActor.tell(new AddServer(NEW_SERVER_ID, newFollowerRaftActor.path().toString(), true),
639                 testKit.getRef());
640         AddServerReply addServerReply = testKit.expectMsgClass(JavaTestKit.duration("5 seconds"), AddServerReply.class);
641         assertEquals("getStatus", ServerChangeStatus.NO_LEADER, addServerReply.getStatus());
642
643         LOG.info("testAddServerWithNoLeader ending");
644     }
645
646     @Test
647     public void testAddServerWithNoConsensusReached() {
648         LOG.info("testAddServerWithNoConsensusReached starting");
649
650         setupNewFollower();
651         RaftActorContext initialActorContext = new MockRaftActorContext();
652
653         TestActorRef<MockLeaderRaftActor> leaderActor = actorFactory.createTestActor(
654                 MockLeaderRaftActor.props(ImmutableMap.<String, String>of(),
655                         initialActorContext).withDispatcher(Dispatchers.DefaultDispatcherId()),
656                 actorFactory.generateActorId(LEADER_ID));
657
658         MockLeaderRaftActor leaderRaftActor = leaderActor.underlyingActor();
659         final RaftActorContext leaderActorContext = leaderRaftActor.getRaftActorContext();
660
661         final TestActorRef<MessageCollectorActor> leaderCollectorActor = newLeaderCollectorActor(leaderRaftActor);
662
663         // Drop UnInitializedFollowerSnapshotReply initially
664         leaderRaftActor.setDropMessageOfType(UnInitializedFollowerSnapshotReply.class);
665
666         MockNewFollowerRaftActor newFollowerRaftActorInstance = newFollowerRaftActor.underlyingActor();
667         newFollowerCollectorActor = newCollectorActor(newFollowerRaftActorInstance, NEW_SERVER_ID);
668
669         // Drop AppendEntries to the new follower so consensus isn't reached
670         newFollowerRaftActorInstance.setDropMessageOfType(AppendEntries.class);
671
672         leaderActor.tell(new AddServer(NEW_SERVER_ID, newFollowerRaftActor.path().toString(), true), testKit.getRef());
673
674         // Capture the UnInitializedFollowerSnapshotReply
675         Object snapshotReply = expectFirstMatching(leaderCollectorActor, UnInitializedFollowerSnapshotReply.class);
676
677         // Send the UnInitializedFollowerSnapshotReply to resume the first request
678         leaderRaftActor.setDropMessageOfType(null);
679         leaderActor.tell(snapshotReply, leaderActor);
680
681         expectFirstMatching(newFollowerCollectorActor, AppendEntries.class);
682
683         // Send a second AddServer
684         leaderActor.tell(new AddServer(NEW_SERVER_ID2, "", false), testKit.getRef());
685
686         // The first AddServer should succeed with OK even though consensus wasn't reached
687         AddServerReply addServerReply = testKit.expectMsgClass(JavaTestKit.duration("5 seconds"), AddServerReply.class);
688         assertEquals("getStatus", ServerChangeStatus.OK, addServerReply.getStatus());
689         assertEquals("getLeaderHint", LEADER_ID, addServerReply.getLeaderHint().get());
690
691         // Verify ServerConfigurationPayload entry in leader's log
692         verifyServerConfigurationPayloadEntry(leaderActorContext.getReplicatedLog(), votingServer(LEADER_ID),
693                 votingServer(NEW_SERVER_ID));
694
695         // The second AddServer should fail since consensus wasn't reached for the first
696         addServerReply = testKit.expectMsgClass(JavaTestKit.duration("5 seconds"), AddServerReply.class);
697         assertEquals("getStatus", ServerChangeStatus.PRIOR_REQUEST_CONSENSUS_TIMEOUT, addServerReply.getStatus());
698
699         // Re-send the second AddServer - should also fail
700         leaderActor.tell(new AddServer(NEW_SERVER_ID2, "", false), testKit.getRef());
701         addServerReply = testKit.expectMsgClass(JavaTestKit.duration("5 seconds"), AddServerReply.class);
702         assertEquals("getStatus", ServerChangeStatus.PRIOR_REQUEST_CONSENSUS_TIMEOUT, addServerReply.getStatus());
703
704         LOG.info("testAddServerWithNoConsensusReached ending");
705     }
706
707     @Test
708     public void testAddServerWithExistingServer() {
709         LOG.info("testAddServerWithExistingServer starting");
710
711         RaftActorContext initialActorContext = new MockRaftActorContext();
712
713         TestActorRef<MockLeaderRaftActor> leaderActor = actorFactory.createTestActor(
714                 MockLeaderRaftActor.props(ImmutableMap.of(FOLLOWER_ID, followerActor.path().toString()),
715                         initialActorContext).withDispatcher(Dispatchers.DefaultDispatcherId()),
716                 actorFactory.generateActorId(LEADER_ID));
717
718         leaderActor.tell(new AddServer(FOLLOWER_ID, followerActor.path().toString(), true), testKit.getRef());
719
720         AddServerReply addServerReply = testKit.expectMsgClass(JavaTestKit.duration("5 seconds"), AddServerReply.class);
721         assertEquals("getStatus", ServerChangeStatus.ALREADY_EXISTS, addServerReply.getStatus());
722
723         LOG.info("testAddServerWithExistingServer ending");
724     }
725
726     @Test
727     public void testAddServerForwardedToLeader() {
728         LOG.info("testAddServerForwardedToLeader starting");
729
730         setupNewFollower();
731         DefaultConfigParamsImpl configParams = new DefaultConfigParamsImpl();
732         configParams.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
733
734         TestActorRef<MessageCollectorActor> leaderActor = actorFactory.createTestActor(
735                 MessageCollectorActor.props().withDispatcher(Dispatchers.DefaultDispatcherId()),
736                 actorFactory.generateActorId(LEADER_ID));
737
738         TestActorRef<MockRaftActor> followerRaftActor = actorFactory.createTestActor(
739                 MockRaftActor.builder().id(FOLLOWER_ID).peerAddresses(ImmutableMap.of(LEADER_ID,
740                         leaderActor.path().toString())).config(configParams).persistent(Optional.of(false))
741                         .props().withDispatcher(Dispatchers.DefaultDispatcherId()),
742                 actorFactory.generateActorId(FOLLOWER_ID));
743         followerRaftActor.underlyingActor().waitForInitializeBehaviorComplete();
744
745         followerRaftActor.tell(new AppendEntries(1, LEADER_ID, 0, 1, Collections.<ReplicatedLogEntry>emptyList(),
746                 -1, -1, (short)0), leaderActor);
747
748         followerRaftActor.tell(new AddServer(NEW_SERVER_ID, newFollowerRaftActor.path().toString(), true),
749                 testKit.getRef());
750         expectFirstMatching(leaderActor, AddServer.class);
751
752         LOG.info("testAddServerForwardedToLeader ending");
753     }
754
755     @Test
756     public void testOnApplyState() {
757         LOG.info("testOnApplyState starting");
758
759         DefaultConfigParamsImpl configParams = new DefaultConfigParamsImpl();
760         configParams.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
761         TestActorRef<MockRaftActor> noLeaderActor = actorFactory.createTestActor(
762                 MockRaftActor.builder().id(LEADER_ID).peerAddresses(ImmutableMap.of(FOLLOWER_ID,
763                         followerActor.path().toString())).config(configParams).persistent(Optional.of(false))
764                         .props().withDispatcher(Dispatchers.DefaultDispatcherId()),
765                 actorFactory.generateActorId(LEADER_ID));
766
767         RaftActorServerConfigurationSupport support = new RaftActorServerConfigurationSupport(
768                 noLeaderActor.underlyingActor());
769
770         ReplicatedLogEntry serverConfigEntry = new MockRaftActorContext.MockReplicatedLogEntry(1, 1,
771                 new ServerConfigurationPayload(Collections.<ServerInfo>emptyList()));
772         boolean handled = support.handleMessage(new ApplyState(null, null, serverConfigEntry), ActorRef.noSender());
773         assertEquals("Message handled", true, handled);
774
775         ReplicatedLogEntry nonServerConfigEntry = new MockRaftActorContext.MockReplicatedLogEntry(1, 1,
776                 new MockRaftActorContext.MockPayload("1"));
777         handled = support.handleMessage(new ApplyState(null, null, nonServerConfigEntry), ActorRef.noSender());
778         assertEquals("Message handled", false, handled);
779
780         LOG.info("testOnApplyState ending");
781     }
782
783     @Test
784     public void testRemoveServerWithNoLeader() {
785         LOG.info("testRemoveServerWithNoLeader starting");
786
787         DefaultConfigParamsImpl configParams = new DefaultConfigParamsImpl();
788         configParams.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
789
790         TestActorRef<MockRaftActor> leaderActor = actorFactory.createTestActor(
791                 MockRaftActor.builder().id(LEADER_ID).peerAddresses(ImmutableMap.of(FOLLOWER_ID,
792                         followerActor.path().toString())).config(configParams).persistent(Optional.of(false))
793                         .props().withDispatcher(Dispatchers.DefaultDispatcherId()),
794                 actorFactory.generateActorId(LEADER_ID));
795         leaderActor.underlyingActor().waitForInitializeBehaviorComplete();
796
797         leaderActor.tell(new RemoveServer(FOLLOWER_ID), testKit.getRef());
798         RemoveServerReply removeServerReply = testKit.expectMsgClass(JavaTestKit.duration("5 seconds"),
799                 RemoveServerReply.class);
800         assertEquals("getStatus", ServerChangeStatus.NO_LEADER, removeServerReply.getStatus());
801
802         LOG.info("testRemoveServerWithNoLeader ending");
803     }
804
805     @Test
806     public void testRemoveServerNonExistentServer() {
807         LOG.info("testRemoveServerNonExistentServer starting");
808
809         RaftActorContext initialActorContext = new MockRaftActorContext();
810
811         TestActorRef<MockLeaderRaftActor> leaderActor = actorFactory.createTestActor(
812                 MockLeaderRaftActor.props(ImmutableMap.of(FOLLOWER_ID, followerActor.path().toString()),
813                         initialActorContext).withDispatcher(Dispatchers.DefaultDispatcherId()),
814                 actorFactory.generateActorId(LEADER_ID));
815
816         leaderActor.tell(new RemoveServer(NEW_SERVER_ID), testKit.getRef());
817         RemoveServerReply removeServerReply = testKit.expectMsgClass(JavaTestKit.duration("5 seconds"),
818                 RemoveServerReply.class);
819         assertEquals("getStatus", ServerChangeStatus.DOES_NOT_EXIST, removeServerReply.getStatus());
820
821         LOG.info("testRemoveServerNonExistentServer ending");
822     }
823
824     @Test
825     public void testRemoveServerForwardToLeader() {
826         LOG.info("testRemoveServerForwardToLeader starting");
827
828         DefaultConfigParamsImpl configParams = new DefaultConfigParamsImpl();
829         configParams.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
830
831         TestActorRef<MessageCollectorActor> leaderActor = actorFactory.createTestActor(
832                 MessageCollectorActor.props().withDispatcher(Dispatchers.DefaultDispatcherId()),
833                 actorFactory.generateActorId(LEADER_ID));
834
835         TestActorRef<MockRaftActor> followerRaftActor = actorFactory.createTestActor(
836                 MockRaftActor.builder().id(FOLLOWER_ID).peerAddresses(ImmutableMap.of(LEADER_ID,
837                         leaderActor.path().toString())).config(configParams).persistent(Optional.of(false))
838                         .props().withDispatcher(Dispatchers.DefaultDispatcherId()),
839                 actorFactory.generateActorId(FOLLOWER_ID));
840         followerRaftActor.underlyingActor().waitForInitializeBehaviorComplete();
841
842         followerRaftActor.tell(new AppendEntries(1, LEADER_ID, 0, 1, Collections.<ReplicatedLogEntry>emptyList(),
843                 -1, -1, (short)0), leaderActor);
844
845         followerRaftActor.tell(new RemoveServer(FOLLOWER_ID), testKit.getRef());
846         expectFirstMatching(leaderActor, RemoveServer.class);
847
848         LOG.info("testRemoveServerForwardToLeader ending");
849     }
850
851     @Test
852     public void testRemoveServer() {
853         LOG.info("testRemoveServer starting");
854
855         DefaultConfigParamsImpl configParams = new DefaultConfigParamsImpl();
856         configParams.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
857         configParams.setCustomRaftPolicyImplementationClass(DisableElectionsRaftPolicy.class.getName());
858
859         final String followerActorId = actorFactory.generateActorId(FOLLOWER_ID);
860         final String followerActorPath = actorFactory.createTestActorPath(followerActorId);
861         RaftActorContext initialActorContext = new MockRaftActorContext();
862
863         TestActorRef<MockLeaderRaftActor> leaderActor = actorFactory.createTestActor(
864                 MockLeaderRaftActor.props(ImmutableMap.of(FOLLOWER_ID, followerActorPath),
865                         initialActorContext).withDispatcher(Dispatchers.DefaultDispatcherId()),
866                 actorFactory.generateActorId(LEADER_ID));
867
868         final TestActorRef<MessageCollectorActor> leaderCollector =
869                 newLeaderCollectorActor(leaderActor.underlyingActor());
870
871         TestActorRef<MessageCollectorActor> collector = actorFactory.createTestActor(MessageCollectorActor.props()
872                 .withDispatcher(Dispatchers.DefaultDispatcherId()),
873                         actorFactory.generateActorId("collector"));
874         actorFactory.createTestActor(
875                 CollectingMockRaftActor.props(FOLLOWER_ID, ImmutableMap.of(LEADER_ID, leaderActor.path().toString()),
876                         configParams, NO_PERSISTENCE, collector).withDispatcher(Dispatchers.DefaultDispatcherId()),
877                 followerActorId);
878
879         leaderActor.tell(new RemoveServer(FOLLOWER_ID), testKit.getRef());
880         RemoveServerReply removeServerReply = testKit.expectMsgClass(JavaTestKit.duration("5 seconds"),
881                 RemoveServerReply.class);
882         assertEquals("getStatus", ServerChangeStatus.OK, removeServerReply.getStatus());
883
884         final ApplyState applyState = MessageCollectorActor.expectFirstMatching(leaderCollector, ApplyState.class);
885         assertEquals(0L, applyState.getReplicatedLogEntry().getIndex());
886         verifyServerConfigurationPayloadEntry(leaderActor.underlyingActor().getRaftActorContext().getReplicatedLog(),
887                 votingServer(LEADER_ID));
888
889         RaftActorBehavior currentBehavior = leaderActor.underlyingActor().getCurrentBehavior();
890         assertTrue("Expected Leader", currentBehavior instanceof Leader);
891         assertEquals("Follower ids size", 0, ((Leader)currentBehavior).getFollowerIds().size());
892
893         MessageCollectorActor.expectFirstMatching(collector, ServerRemoved.class);
894
895         LOG.info("testRemoveServer ending");
896     }
897
898     @Test
899     public void testRemoveServerLeader() {
900         LOG.info("testRemoveServerLeader starting");
901
902         DefaultConfigParamsImpl configParams = new DefaultConfigParamsImpl();
903         configParams.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
904         configParams.setCustomRaftPolicyImplementationClass(DisableElectionsRaftPolicy.class.getName());
905
906         final String followerActorId = actorFactory.generateActorId(FOLLOWER_ID);
907         final String followerActorPath = actorFactory.createTestActorPath(followerActorId);
908         RaftActorContext initialActorContext = new MockRaftActorContext();
909
910         TestActorRef<MockLeaderRaftActor> leaderActor = actorFactory.createTestActor(
911                 MockLeaderRaftActor.props(ImmutableMap.of(FOLLOWER_ID, followerActorPath),
912                         initialActorContext).withDispatcher(Dispatchers.DefaultDispatcherId()),
913                 actorFactory.generateActorId(LEADER_ID));
914
915         final TestActorRef<MessageCollectorActor> leaderCollector =
916                 newLeaderCollectorActor(leaderActor.underlyingActor());
917
918         final TestActorRef<MessageCollectorActor> followerCollector =
919                 actorFactory.createTestActor(MessageCollectorActor.props()
920                 .withDispatcher(Dispatchers.DefaultDispatcherId()), actorFactory.generateActorId("collector"));
921         actorFactory.createTestActor(
922                 CollectingMockRaftActor.props(FOLLOWER_ID, ImmutableMap.of(LEADER_ID, leaderActor.path().toString()),
923                         configParams, NO_PERSISTENCE, followerCollector)
924                         .withDispatcher(Dispatchers.DefaultDispatcherId()),
925                 followerActorId);
926
927         leaderActor.tell(new RemoveServer(LEADER_ID), testKit.getRef());
928         RemoveServerReply removeServerReply = testKit.expectMsgClass(JavaTestKit.duration("5 seconds"),
929                 RemoveServerReply.class);
930         assertEquals("getStatus", ServerChangeStatus.OK, removeServerReply.getStatus());
931
932         final ApplyState applyState = MessageCollectorActor.expectFirstMatching(followerCollector, ApplyState.class);
933         assertEquals(0L, applyState.getReplicatedLogEntry().getIndex());
934         verifyServerConfigurationPayloadEntry(leaderActor.underlyingActor().getRaftActorContext().getReplicatedLog(),
935                 votingServer(FOLLOWER_ID));
936
937         MessageCollectorActor.expectFirstMatching(leaderCollector, ServerRemoved.class);
938
939         LOG.info("testRemoveServerLeader ending");
940     }
941
942     @Test
943     public void testRemoveServerLeaderWithNoFollowers() {
944         LOG.info("testRemoveServerLeaderWithNoFollowers starting");
945
946         TestActorRef<MockLeaderRaftActor> leaderActor = actorFactory.createTestActor(
947                 MockLeaderRaftActor.props(Collections.<String, String>emptyMap(),
948                         new MockRaftActorContext()).withDispatcher(Dispatchers.DefaultDispatcherId()),
949                 actorFactory.generateActorId(LEADER_ID));
950
951         leaderActor.tell(new RemoveServer(LEADER_ID), testKit.getRef());
952         RemoveServerReply removeServerReply = testKit.expectMsgClass(JavaTestKit.duration("5 seconds"),
953                 RemoveServerReply.class);
954         assertEquals("getStatus", ServerChangeStatus.NOT_SUPPORTED, removeServerReply.getStatus());
955
956         LOG.info("testRemoveServerLeaderWithNoFollowers ending");
957     }
958
959     @Test
960     public void testChangeServersVotingStatus() {
961         LOG.info("testChangeServersVotingStatus starting");
962
963         DefaultConfigParamsImpl configParams = new DefaultConfigParamsImpl();
964         configParams.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
965         configParams.setCustomRaftPolicyImplementationClass(DisableElectionsRaftPolicy.class.getName());
966
967         final String follower1ActorId = actorFactory.generateActorId(FOLLOWER_ID);
968         final String follower1ActorPath = actorFactory.createTestActorPath(follower1ActorId);
969         final String follower2ActorId = actorFactory.generateActorId(FOLLOWER_ID2);
970         final String follower2ActorPath = actorFactory.createTestActorPath(follower2ActorId);
971
972         TestActorRef<MockLeaderRaftActor> leaderActor = actorFactory.createTestActor(
973                 MockLeaderRaftActor.props(ImmutableMap.of(FOLLOWER_ID, follower1ActorPath,
974                         FOLLOWER_ID2, follower2ActorPath), new MockRaftActorContext())
975                         .withDispatcher(Dispatchers.DefaultDispatcherId()), actorFactory.generateActorId(LEADER_ID));
976         TestActorRef<MessageCollectorActor> leaderCollector = newLeaderCollectorActor(leaderActor.underlyingActor());
977
978         TestActorRef<MessageCollectorActor> follower1Collector = actorFactory.createTestActor(
979                 MessageCollectorActor.props().withDispatcher(Dispatchers.DefaultDispatcherId()),
980                 actorFactory.generateActorId("collector"));
981         final TestActorRef<CollectingMockRaftActor> follower1RaftActor = actorFactory.createTestActor(
982                 CollectingMockRaftActor.props(FOLLOWER_ID, ImmutableMap.of(LEADER_ID, leaderActor.path().toString(),
983                         FOLLOWER_ID2, follower2ActorPath), configParams, NO_PERSISTENCE, follower1Collector)
984                         .withDispatcher(Dispatchers.DefaultDispatcherId()), follower1ActorId);
985
986         TestActorRef<MessageCollectorActor> follower2Collector = actorFactory.createTestActor(
987                 MessageCollectorActor.props().withDispatcher(Dispatchers.DefaultDispatcherId()),
988                 actorFactory.generateActorId("collector"));
989         final TestActorRef<CollectingMockRaftActor> follower2RaftActor = actorFactory.createTestActor(
990                 CollectingMockRaftActor.props(FOLLOWER_ID2, ImmutableMap.of(LEADER_ID, leaderActor.path().toString(),
991                         FOLLOWER_ID, follower1ActorPath), configParams, NO_PERSISTENCE, follower2Collector)
992                         .withDispatcher(Dispatchers.DefaultDispatcherId()), follower2ActorId);
993
994         // Send first ChangeServersVotingStatus message
995
996         leaderActor.tell(new ChangeServersVotingStatus(ImmutableMap.of(FOLLOWER_ID, false, FOLLOWER_ID2, false)),
997                 testKit.getRef());
998         ServerChangeReply reply = testKit.expectMsgClass(JavaTestKit.duration("5 seconds"), ServerChangeReply.class);
999         assertEquals("getStatus", ServerChangeStatus.OK, reply.getStatus());
1000
1001         final ApplyState applyState = MessageCollectorActor.expectFirstMatching(leaderCollector, ApplyState.class);
1002         assertEquals(0L, applyState.getReplicatedLogEntry().getIndex());
1003         verifyServerConfigurationPayloadEntry(leaderActor.underlyingActor().getRaftActorContext().getReplicatedLog(),
1004                 votingServer(LEADER_ID), nonVotingServer(FOLLOWER_ID), nonVotingServer(FOLLOWER_ID2));
1005
1006         MessageCollectorActor.expectFirstMatching(follower1Collector, ApplyState.class);
1007         verifyServerConfigurationPayloadEntry(follower1RaftActor.underlyingActor().getRaftActorContext()
1008                 .getReplicatedLog(), votingServer(LEADER_ID), nonVotingServer(FOLLOWER_ID),
1009                 nonVotingServer(FOLLOWER_ID2));
1010
1011         MessageCollectorActor.expectFirstMatching(follower2Collector, ApplyState.class);
1012         verifyServerConfigurationPayloadEntry(follower2RaftActor.underlyingActor().getRaftActorContext()
1013                 .getReplicatedLog(), votingServer(LEADER_ID), nonVotingServer(FOLLOWER_ID),
1014                 nonVotingServer(FOLLOWER_ID2));
1015
1016         MessageCollectorActor.clearMessages(leaderCollector);
1017         MessageCollectorActor.clearMessages(follower1Collector);
1018         MessageCollectorActor.clearMessages(follower2Collector);
1019
1020         // Send second ChangeServersVotingStatus message
1021
1022         leaderActor.tell(new ChangeServersVotingStatus(ImmutableMap.of(FOLLOWER_ID, true)), testKit.getRef());
1023         reply = testKit.expectMsgClass(JavaTestKit.duration("5 seconds"), ServerChangeReply.class);
1024         assertEquals("getStatus", ServerChangeStatus.OK, reply.getStatus());
1025
1026         MessageCollectorActor.expectFirstMatching(leaderCollector, ApplyState.class);
1027         verifyServerConfigurationPayloadEntry(leaderActor.underlyingActor().getRaftActorContext().getReplicatedLog(),
1028                 votingServer(LEADER_ID), votingServer(FOLLOWER_ID), nonVotingServer(FOLLOWER_ID2));
1029
1030         MessageCollectorActor.expectFirstMatching(follower1Collector, ApplyState.class);
1031         verifyServerConfigurationPayloadEntry(follower1RaftActor.underlyingActor().getRaftActorContext()
1032                 .getReplicatedLog(), votingServer(LEADER_ID), votingServer(FOLLOWER_ID), nonVotingServer(FOLLOWER_ID2));
1033
1034         MessageCollectorActor.expectFirstMatching(follower2Collector, ApplyState.class);
1035         verifyServerConfigurationPayloadEntry(follower2RaftActor.underlyingActor().getRaftActorContext()
1036                 .getReplicatedLog(), votingServer(LEADER_ID), votingServer(FOLLOWER_ID), nonVotingServer(FOLLOWER_ID2));
1037
1038         LOG.info("testChangeServersVotingStatus ending");
1039     }
1040
1041     @Test
1042     public void testChangeLeaderToNonVoting() {
1043         LOG.info("testChangeLeaderToNonVoting starting");
1044
1045         DefaultConfigParamsImpl configParams = new DefaultConfigParamsImpl();
1046         configParams.setHeartBeatInterval(new FiniteDuration(500, TimeUnit.MILLISECONDS));
1047
1048         final String follower1ActorId = actorFactory.generateActorId(FOLLOWER_ID);
1049         final String follower1ActorPath = actorFactory.createTestActorPath(follower1ActorId);
1050         final String follower2ActorId = actorFactory.generateActorId(FOLLOWER_ID2);
1051         final String follower2ActorPath = actorFactory.createTestActorPath(follower2ActorId);
1052
1053         TestActorRef<MockLeaderRaftActor> leaderActor = actorFactory.createTestActor(
1054                 MockLeaderRaftActor.props(ImmutableMap.of(FOLLOWER_ID, follower1ActorPath,
1055                         FOLLOWER_ID2, follower2ActorPath), new MockRaftActorContext())
1056                         .withDispatcher(Dispatchers.DefaultDispatcherId()), actorFactory.generateActorId(LEADER_ID));
1057         TestActorRef<MessageCollectorActor> leaderCollector = newLeaderCollectorActor(leaderActor.underlyingActor());
1058
1059         TestActorRef<MessageCollectorActor> follower1Collector = actorFactory.createTestActor(
1060                 MessageCollectorActor.props().withDispatcher(Dispatchers.DefaultDispatcherId()),
1061                 actorFactory.generateActorId("collector"));
1062         final TestActorRef<CollectingMockRaftActor> follower1RaftActor = actorFactory.createTestActor(
1063                 CollectingMockRaftActor.props(FOLLOWER_ID, ImmutableMap.of(LEADER_ID, leaderActor.path().toString(),
1064                         FOLLOWER_ID2, follower2ActorPath), configParams, NO_PERSISTENCE, follower1Collector)
1065                         .withDispatcher(Dispatchers.DefaultDispatcherId()), follower1ActorId);
1066
1067         TestActorRef<MessageCollectorActor> follower2Collector = actorFactory.createTestActor(
1068                 MessageCollectorActor.props().withDispatcher(Dispatchers.DefaultDispatcherId()),
1069                 actorFactory.generateActorId("collector"));
1070         final TestActorRef<CollectingMockRaftActor> follower2RaftActor = actorFactory.createTestActor(
1071                 CollectingMockRaftActor.props(FOLLOWER_ID2, ImmutableMap.of(LEADER_ID, leaderActor.path().toString(),
1072                         FOLLOWER_ID, follower1ActorPath), configParams, NO_PERSISTENCE, follower2Collector)
1073                         .withDispatcher(Dispatchers.DefaultDispatcherId()), follower2ActorId);
1074
1075         // Send ChangeServersVotingStatus message
1076
1077         leaderActor.tell(new ChangeServersVotingStatus(ImmutableMap.of(LEADER_ID, false)), testKit.getRef());
1078         ServerChangeReply reply = testKit.expectMsgClass(JavaTestKit.duration("5 seconds"), ServerChangeReply.class);
1079         assertEquals("getStatus", ServerChangeStatus.OK, reply.getStatus());
1080
1081         MessageCollectorActor.expectFirstMatching(leaderCollector, ApplyState.class);
1082         verifyServerConfigurationPayloadEntry(leaderActor.underlyingActor().getRaftActorContext().getReplicatedLog(),
1083                 nonVotingServer(LEADER_ID), votingServer(FOLLOWER_ID), votingServer(FOLLOWER_ID2));
1084
1085         MessageCollectorActor.expectFirstMatching(follower1Collector, ApplyState.class);
1086         verifyServerConfigurationPayloadEntry(follower1RaftActor.underlyingActor().getRaftActorContext()
1087                 .getReplicatedLog(), nonVotingServer(LEADER_ID), votingServer(FOLLOWER_ID), votingServer(FOLLOWER_ID2));
1088
1089         MessageCollectorActor.expectFirstMatching(follower2Collector, ApplyState.class);
1090         verifyServerConfigurationPayloadEntry(follower2RaftActor.underlyingActor().getRaftActorContext()
1091                 .getReplicatedLog(), nonVotingServer(LEADER_ID), votingServer(FOLLOWER_ID), votingServer(FOLLOWER_ID2));
1092
1093         verifyRaftState(RaftState.Leader, follower1RaftActor.underlyingActor(), follower2RaftActor.underlyingActor());
1094         verifyRaftState(RaftState.Follower, leaderActor.underlyingActor());
1095
1096         MessageCollectorActor.expectMatching(leaderCollector, AppendEntries.class, 2);
1097
1098         LOG.info("testChangeLeaderToNonVoting ending");
1099     }
1100
1101     @Test
1102     public void testChangeLeaderToNonVotingInSingleNode() {
1103         LOG.info("testChangeLeaderToNonVotingInSingleNode starting");
1104
1105         TestActorRef<MockLeaderRaftActor> leaderActor = actorFactory.createTestActor(
1106                 MockLeaderRaftActor.props(ImmutableMap.of(), new MockRaftActorContext())
1107                         .withDispatcher(Dispatchers.DefaultDispatcherId()), actorFactory.generateActorId(LEADER_ID));
1108
1109         leaderActor.tell(new ChangeServersVotingStatus(ImmutableMap.of(LEADER_ID, false)), testKit.getRef());
1110         ServerChangeReply reply = testKit.expectMsgClass(JavaTestKit.duration("5 seconds"), ServerChangeReply.class);
1111         assertEquals("getStatus", ServerChangeStatus.INVALID_REQUEST, reply.getStatus());
1112
1113         LOG.info("testChangeLeaderToNonVotingInSingleNode ending");
1114     }
1115
1116     @Test
1117     public void testChangeToVotingWithNoLeader() {
1118         LOG.info("testChangeToVotingWithNoLeader starting");
1119
1120         DefaultConfigParamsImpl configParams = new DefaultConfigParamsImpl();
1121         configParams.setHeartBeatInterval(new FiniteDuration(100, TimeUnit.MILLISECONDS));
1122         configParams.setElectionTimeoutFactor(5);
1123
1124         final String node1ID = "node1";
1125         final String node2ID = "node2";
1126
1127         // Set up a persisted ServerConfigurationPayload. Initially node1 and node2 will come up as non-voting.
1128         // via the server config. The server config will also contain 2 voting peers that are down (ie no
1129         // actors created).
1130
1131         ServerConfigurationPayload persistedServerConfig = new ServerConfigurationPayload(Arrays.asList(
1132                 new ServerInfo(node1ID, false), new ServerInfo(node2ID, false),
1133                 new ServerInfo("downNode1", true), new ServerInfo("downNode2", true)));
1134         ReplicatedLogImplEntry persistedServerConfigEntry = new ReplicatedLogImplEntry(0, 1, persistedServerConfig);
1135
1136         InMemoryJournal.addEntry(node1ID, 1, new UpdateElectionTerm(1, "downNode1"));
1137         InMemoryJournal.addEntry(node1ID, 2, persistedServerConfigEntry);
1138         InMemoryJournal.addEntry(node1ID, 3, new ApplyJournalEntries(0));
1139         InMemoryJournal.addEntry(node2ID, 1, new UpdateElectionTerm(1, "downNode2"));
1140         InMemoryJournal.addEntry(node2ID, 2, persistedServerConfigEntry);
1141         InMemoryJournal.addEntry(node2ID, 3, new ApplyJournalEntries(0));
1142
1143         TestActorRef<MessageCollectorActor> node1Collector = actorFactory.createTestActor(
1144                 MessageCollectorActor.props().withDispatcher(Dispatchers.DefaultDispatcherId()),
1145                 actorFactory.generateActorId("collector"));
1146         TestActorRef<CollectingMockRaftActor> node1RaftActorRef = actorFactory.createTestActor(
1147                 CollectingMockRaftActor.props(node1ID, ImmutableMap.<String, String>of(), configParams,
1148                         PERSISTENT, node1Collector).withDispatcher(Dispatchers.DefaultDispatcherId()), node1ID);
1149         CollectingMockRaftActor node1RaftActor = node1RaftActorRef.underlyingActor();
1150
1151         TestActorRef<MessageCollectorActor> node2Collector = actorFactory.createTestActor(
1152                 MessageCollectorActor.props().withDispatcher(Dispatchers.DefaultDispatcherId()),
1153                 actorFactory.generateActorId("collector"));
1154         TestActorRef<CollectingMockRaftActor> node2RaftActorRef = actorFactory.createTestActor(
1155                 CollectingMockRaftActor.props(node2ID, ImmutableMap.<String, String>of(), configParams,
1156                         PERSISTENT, node2Collector).withDispatcher(Dispatchers.DefaultDispatcherId()), node2ID);
1157         CollectingMockRaftActor node2RaftActor = node2RaftActorRef.underlyingActor();
1158
1159         node1RaftActor.waitForInitializeBehaviorComplete();
1160         node2RaftActor.waitForInitializeBehaviorComplete();
1161
1162         // Verify the intended server config was loaded and applied.
1163         verifyServerConfigurationPayloadEntry(node1RaftActor.getRaftActorContext().getReplicatedLog(),
1164                 nonVotingServer(node1ID), nonVotingServer(node2ID), votingServer("downNode1"),
1165                 votingServer("downNode2"));
1166         assertEquals("isVotingMember", false, node1RaftActor.getRaftActorContext().isVotingMember());
1167         assertEquals("getRaftState", RaftState.Follower, node1RaftActor.getRaftState());
1168         assertEquals("getLeaderId", null, node1RaftActor.getLeaderId());
1169
1170         verifyServerConfigurationPayloadEntry(node2RaftActor.getRaftActorContext().getReplicatedLog(),
1171                 nonVotingServer(node1ID), nonVotingServer(node2ID), votingServer("downNode1"),
1172                 votingServer("downNode2"));
1173         assertEquals("isVotingMember", false, node2RaftActor.getRaftActorContext().isVotingMember());
1174
1175         // For the test, we send a ChangeServersVotingStatus message to node1 to flip the voting states for
1176         // each server, ie node1 and node2 to voting and the 2 down nodes to non-voting. This should cause
1177         // node1 to try to elect itself as leader in order to apply the new server config. Since the 2
1178         // down nodes are switched to non-voting, node1 should only need a vote from node2.
1179
1180         // First send the message such that node1 has no peer address for node2 - should fail.
1181
1182         ChangeServersVotingStatus changeServers = new ChangeServersVotingStatus(ImmutableMap.of(node1ID, true,
1183                 node2ID, true, "downNode1", false, "downNode2", false));
1184         node1RaftActorRef.tell(changeServers, testKit.getRef());
1185         ServerChangeReply reply = testKit.expectMsgClass(JavaTestKit.duration("5 seconds"), ServerChangeReply.class);
1186         assertEquals("getStatus", ServerChangeStatus.NO_LEADER, reply.getStatus());
1187
1188         // Send an AppendEntries so node1 has a leaderId
1189
1190         MessageCollectorActor.clearMessages(node1Collector);
1191
1192         long term = node1RaftActor.getRaftActorContext().getTermInformation().getCurrentTerm();
1193         node1RaftActorRef.tell(new AppendEntries(term, "downNode1", -1L, -1L,
1194                 Collections.<ReplicatedLogEntry>emptyList(), 0, -1, (short)1), ActorRef.noSender());
1195
1196         // Wait for the ElectionTimeout to clear the leaderId. he leaderId must be null so on the
1197         // ChangeServersVotingStatus message, it will try to elect a leader.
1198
1199         MessageCollectorActor.expectFirstMatching(node1Collector, ElectionTimeout.class);
1200
1201         // Update node2's peer address and send the message again
1202
1203         node1RaftActor.setPeerAddress(node2ID, node2RaftActorRef.path().toString());
1204
1205         node1RaftActorRef.tell(changeServers, testKit.getRef());
1206         reply = testKit.expectMsgClass(JavaTestKit.duration("5 seconds"), ServerChangeReply.class);
1207         assertEquals("getStatus", ServerChangeStatus.OK, reply.getStatus());
1208
1209         ApplyJournalEntries apply = MessageCollectorActor.expectFirstMatching(node1Collector,
1210                 ApplyJournalEntries.class);
1211         assertEquals("getToIndex", 1, apply.getToIndex());
1212         verifyServerConfigurationPayloadEntry(node1RaftActor.getRaftActorContext().getReplicatedLog(),
1213                 votingServer(node1ID), votingServer(node2ID), nonVotingServer("downNode1"),
1214                 nonVotingServer("downNode2"));
1215         assertEquals("isVotingMember", true, node1RaftActor.getRaftActorContext().isVotingMember());
1216         assertEquals("getRaftState", RaftState.Leader, node1RaftActor.getRaftState());
1217
1218         apply = MessageCollectorActor.expectFirstMatching(node2Collector, ApplyJournalEntries.class);
1219         assertEquals("getToIndex", 1, apply.getToIndex());
1220         verifyServerConfigurationPayloadEntry(node2RaftActor.getRaftActorContext().getReplicatedLog(),
1221                 votingServer(node1ID), votingServer(node2ID), nonVotingServer("downNode1"),
1222                 nonVotingServer("downNode2"));
1223         assertEquals("isVotingMember", true, node2RaftActor.getRaftActorContext().isVotingMember());
1224         assertEquals("getRaftState", RaftState.Follower, node2RaftActor.getRaftState());
1225
1226         LOG.info("testChangeToVotingWithNoLeader ending");
1227     }
1228
1229     @Test
1230     public void testChangeToVotingWithNoLeaderAndElectionTimeout() {
1231         LOG.info("testChangeToVotingWithNoLeaderAndElectionTimeout starting");
1232
1233         final String node1ID = "node1";
1234         final String node2ID = "node2";
1235
1236         final PeerAddressResolver peerAddressResolver = peerId -> peerId.equals(node1ID)
1237                 ? actorFactory.createTestActorPath(node1ID) : peerId.equals(node2ID)
1238                         ? actorFactory.createTestActorPath(node2ID) : null;
1239
1240         ServerConfigurationPayload persistedServerConfig = new ServerConfigurationPayload(Arrays.asList(
1241                 new ServerInfo(node1ID, false), new ServerInfo(node2ID, true)));
1242         ReplicatedLogImplEntry persistedServerConfigEntry = new ReplicatedLogImplEntry(0, 1, persistedServerConfig);
1243
1244         InMemoryJournal.addEntry(node1ID, 1, new UpdateElectionTerm(1, "node1"));
1245         InMemoryJournal.addEntry(node1ID, 2, persistedServerConfigEntry);
1246         InMemoryJournal.addEntry(node2ID, 1, new UpdateElectionTerm(1, "node1"));
1247         InMemoryJournal.addEntry(node2ID, 2, persistedServerConfigEntry);
1248
1249         DefaultConfigParamsImpl configParams1 = new DefaultConfigParamsImpl();
1250         configParams1.setHeartBeatInterval(new FiniteDuration(100, TimeUnit.MILLISECONDS));
1251         configParams1.setElectionTimeoutFactor(1);
1252         configParams1.setPeerAddressResolver(peerAddressResolver);
1253         TestActorRef<MessageCollectorActor> node1Collector = actorFactory.createTestActor(
1254                 MessageCollectorActor.props().withDispatcher(Dispatchers.DefaultDispatcherId()),
1255                 actorFactory.generateActorId("collector"));
1256         TestActorRef<CollectingMockRaftActor> node1RaftActorRef = actorFactory.createTestActor(
1257                 CollectingMockRaftActor.props(node1ID, ImmutableMap.<String, String>of(), configParams1,
1258                         PERSISTENT, node1Collector).withDispatcher(Dispatchers.DefaultDispatcherId()), node1ID);
1259         final CollectingMockRaftActor node1RaftActor = node1RaftActorRef.underlyingActor();
1260
1261         DefaultConfigParamsImpl configParams2 = new DefaultConfigParamsImpl();
1262         configParams2.setElectionTimeoutFactor(1000000);
1263         configParams2.setPeerAddressResolver(peerAddressResolver);
1264         TestActorRef<MessageCollectorActor> node2Collector = actorFactory.createTestActor(
1265                 MessageCollectorActor.props().withDispatcher(Dispatchers.DefaultDispatcherId()),
1266                 actorFactory.generateActorId("collector"));
1267         TestActorRef<CollectingMockRaftActor> node2RaftActorRef = actorFactory.createTestActor(
1268                 CollectingMockRaftActor.props(node2ID, ImmutableMap.<String, String>of(), configParams2,
1269                         PERSISTENT, node2Collector).withDispatcher(Dispatchers.DefaultDispatcherId()), node2ID);
1270         CollectingMockRaftActor node2RaftActor = node2RaftActorRef.underlyingActor();
1271
1272         // Send a ChangeServersVotingStatus message to node1 to change mode1 to voting. This should cause
1273         // node1 to try to elect itself as leader in order to apply the new server config. But we'll drop
1274         // RequestVote messages in node2 which should cause node1 to time out and revert back to the previous
1275         // server config and fail with NO_LEADER. Note that node1 shouldn't forward the request to node2 b/c
1276         // node2 was previously voting.
1277
1278         node2RaftActor.setDropMessageOfType(RequestVote.class);
1279
1280         ChangeServersVotingStatus changeServers = new ChangeServersVotingStatus(ImmutableMap.of(node1ID, true));
1281         node1RaftActorRef.tell(changeServers, testKit.getRef());
1282         ServerChangeReply reply = testKit.expectMsgClass(JavaTestKit.duration("5 seconds"), ServerChangeReply.class);
1283         assertEquals("getStatus", ServerChangeStatus.NO_LEADER, reply.getStatus());
1284
1285         assertEquals("Server config", Sets.newHashSet(nonVotingServer(node1ID), votingServer(node2ID)),
1286                 Sets.newHashSet(node1RaftActor.getRaftActorContext().getPeerServerInfo(true).getServerConfig()));
1287         assertEquals("getRaftState", RaftState.Follower, node1RaftActor.getRaftState());
1288
1289         LOG.info("testChangeToVotingWithNoLeaderAndElectionTimeout ending");
1290     }
1291
1292     @Test
1293     public void testChangeToVotingWithNoLeaderAndForwardedToOtherNodeAfterElectionTimeout() {
1294         LOG.info("testChangeToVotingWithNoLeaderAndForwardedToOtherNodeAfterElectionTimeout starting");
1295
1296         final String node1ID = "node1";
1297         final String node2ID = "node2";
1298
1299         final PeerAddressResolver peerAddressResolver = peerId -> peerId.equals(node1ID)
1300                 ? actorFactory.createTestActorPath(node1ID) : peerId.equals(node2ID)
1301                         ? actorFactory.createTestActorPath(node2ID) : null;
1302
1303         DefaultConfigParamsImpl configParams = new DefaultConfigParamsImpl();
1304         configParams.setHeartBeatInterval(new FiniteDuration(100, TimeUnit.MILLISECONDS));
1305         configParams.setElectionTimeoutFactor(3);
1306         configParams.setPeerAddressResolver(peerAddressResolver);
1307
1308         ServerConfigurationPayload persistedServerConfig = new ServerConfigurationPayload(Arrays.asList(
1309                 new ServerInfo(node1ID, false), new ServerInfo(node2ID, false)));
1310         ReplicatedLogImplEntry persistedServerConfigEntry = new ReplicatedLogImplEntry(0, 1, persistedServerConfig);
1311
1312         InMemoryJournal.addEntry(node1ID, 1, new UpdateElectionTerm(1, "node1"));
1313         InMemoryJournal.addEntry(node1ID, 2, persistedServerConfigEntry);
1314         InMemoryJournal.addEntry(node2ID, 1, new UpdateElectionTerm(1, "node1"));
1315         InMemoryJournal.addEntry(node2ID, 2, persistedServerConfigEntry);
1316         InMemoryJournal.addEntry(node2ID, 3, new ReplicatedLogImplEntry(1, 1,
1317                 new MockRaftActorContext.MockPayload("2")));
1318         InMemoryJournal.addEntry(node2ID, 4, new ApplyJournalEntries(1));
1319
1320         TestActorRef<MessageCollectorActor> node1Collector = actorFactory.createTestActor(
1321                 MessageCollectorActor.props().withDispatcher(Dispatchers.DefaultDispatcherId()),
1322                 actorFactory.generateActorId("collector"));
1323         TestActorRef<CollectingMockRaftActor> node1RaftActorRef = actorFactory.createTestActor(
1324                 CollectingMockRaftActor.props(node1ID, ImmutableMap.<String, String>of(), configParams,
1325                         PERSISTENT, node1Collector).withDispatcher(Dispatchers.DefaultDispatcherId()), node1ID);
1326         final CollectingMockRaftActor node1RaftActor = node1RaftActorRef.underlyingActor();
1327
1328         TestActorRef<MessageCollectorActor> node2Collector = actorFactory.createTestActor(
1329                 MessageCollectorActor.props().withDispatcher(Dispatchers.DefaultDispatcherId()),
1330                 actorFactory.generateActorId("collector"));
1331         TestActorRef<CollectingMockRaftActor> node2RaftActorRef = actorFactory.createTestActor(
1332                 CollectingMockRaftActor.props(node2ID, ImmutableMap.<String, String>of(), configParams,
1333                         PERSISTENT, node2Collector).withDispatcher(Dispatchers.DefaultDispatcherId()), node2ID);
1334         final CollectingMockRaftActor node2RaftActor = node2RaftActorRef.underlyingActor();
1335
1336         // Send a ChangeServersVotingStatus message to node1 to change mode1 to voting. This should cause
1337         // node1 to try to elect itself as leader in order to apply the new server config. However node1's log
1338         // is behind node2's so node2 should not grant node1's vote. This should cause node1 to time out and
1339         // forward the request to node2.
1340
1341         ChangeServersVotingStatus changeServers = new ChangeServersVotingStatus(
1342                 ImmutableMap.of(node1ID, true, node2ID, true));
1343         node1RaftActorRef.tell(changeServers, testKit.getRef());
1344         ServerChangeReply reply = testKit.expectMsgClass(JavaTestKit.duration("5 seconds"), ServerChangeReply.class);
1345         assertEquals("getStatus", ServerChangeStatus.OK, reply.getStatus());
1346
1347         MessageCollectorActor.expectFirstMatching(node2Collector, ApplyJournalEntries.class);
1348         verifyServerConfigurationPayloadEntry(node2RaftActor.getRaftActorContext().getReplicatedLog(),
1349                 votingServer(node1ID), votingServer(node2ID));
1350         assertEquals("getRaftState", RaftState.Leader, node2RaftActor.getRaftState());
1351
1352         MessageCollectorActor.expectFirstMatching(node1Collector, ApplyJournalEntries.class);
1353         verifyServerConfigurationPayloadEntry(node1RaftActor.getRaftActorContext().getReplicatedLog(),
1354                 votingServer(node1ID), votingServer(node2ID));
1355         assertEquals("isVotingMember", true, node1RaftActor.getRaftActorContext().isVotingMember());
1356         assertEquals("getRaftState", RaftState.Follower, node1RaftActor.getRaftState());
1357
1358         LOG.info("testChangeToVotingWithNoLeaderAndForwardedToOtherNodeAfterElectionTimeout ending");
1359     }
1360
1361     @Test
1362     public void testChangeToVotingWithNoLeaderAndOtherLeaderElected() {
1363         LOG.info("testChangeToVotingWithNoLeaderAndOtherLeaderElected starting");
1364
1365         DefaultConfigParamsImpl configParams = new DefaultConfigParamsImpl();
1366         configParams.setHeartBeatInterval(new FiniteDuration(100, TimeUnit.MILLISECONDS));
1367         configParams.setElectionTimeoutFactor(100000);
1368
1369         final String node1ID = "node1";
1370         final String node2ID = "node2";
1371
1372         configParams.setPeerAddressResolver(peerId -> peerId.equals(node1ID)
1373                 ? actorFactory.createTestActorPath(node1ID) : peerId.equals(node2ID)
1374                         ? actorFactory.createTestActorPath(node2ID) : null);
1375
1376         ServerConfigurationPayload persistedServerConfig = new ServerConfigurationPayload(Arrays.asList(
1377                 new ServerInfo(node1ID, false), new ServerInfo(node2ID, true)));
1378         ReplicatedLogImplEntry persistedServerConfigEntry = new ReplicatedLogImplEntry(0, 1, persistedServerConfig);
1379
1380         InMemoryJournal.addEntry(node1ID, 1, new UpdateElectionTerm(1, "node1"));
1381         InMemoryJournal.addEntry(node1ID, 2, persistedServerConfigEntry);
1382         InMemoryJournal.addEntry(node2ID, 1, new UpdateElectionTerm(1, "node1"));
1383         InMemoryJournal.addEntry(node2ID, 2, persistedServerConfigEntry);
1384
1385         TestActorRef<MessageCollectorActor> node1Collector = actorFactory.createTestActor(
1386                 MessageCollectorActor.props().withDispatcher(Dispatchers.DefaultDispatcherId()),
1387                 actorFactory.generateActorId("collector"));
1388         TestActorRef<CollectingMockRaftActor> node1RaftActorRef = actorFactory.createTestActor(
1389                 CollectingMockRaftActor.props(node1ID, ImmutableMap.<String, String>of(), configParams,
1390                         PERSISTENT, node1Collector).withDispatcher(Dispatchers.DefaultDispatcherId()), node1ID);
1391         final CollectingMockRaftActor node1RaftActor = node1RaftActorRef.underlyingActor();
1392
1393         TestActorRef<MessageCollectorActor> node2Collector = actorFactory.createTestActor(
1394                 MessageCollectorActor.props().withDispatcher(Dispatchers.DefaultDispatcherId()),
1395                 actorFactory.generateActorId("collector"));
1396         TestActorRef<CollectingMockRaftActor> node2RaftActorRef = actorFactory.createTestActor(
1397                 CollectingMockRaftActor.props(node2ID, ImmutableMap.<String, String>of(), configParams,
1398                         PERSISTENT, node2Collector).withDispatcher(Dispatchers.DefaultDispatcherId()), node2ID);
1399         CollectingMockRaftActor node2RaftActor = node2RaftActorRef.underlyingActor();
1400
1401         // Send a ChangeServersVotingStatus message to node1 to change node1 to voting. This should cause
1402         // node1 to try to elect itself as leader in order to apply the new server config. But we'll drop
1403         // RequestVote messages in node2 and make it the leader so node1 should forward the server change
1404         // request to node2 when node2 is elected.
1405
1406         node2RaftActor.setDropMessageOfType(RequestVote.class);
1407
1408         ChangeServersVotingStatus changeServers = new ChangeServersVotingStatus(ImmutableMap.of(node1ID, true,
1409                 node2ID, true));
1410         node1RaftActorRef.tell(changeServers, testKit.getRef());
1411
1412         MessageCollectorActor.expectFirstMatching(node2Collector, RequestVote.class);
1413
1414         node2RaftActorRef.tell(TimeoutNow.INSTANCE, ActorRef.noSender());
1415
1416         ServerChangeReply reply = testKit.expectMsgClass(JavaTestKit.duration("5 seconds"), ServerChangeReply.class);
1417         assertEquals("getStatus", ServerChangeStatus.OK, reply.getStatus());
1418
1419         MessageCollectorActor.expectFirstMatching(node1Collector, ApplyJournalEntries.class);
1420         verifyServerConfigurationPayloadEntry(node1RaftActor.getRaftActorContext().getReplicatedLog(),
1421                 votingServer(node1ID), votingServer(node2ID));
1422         assertEquals("isVotingMember", true, node1RaftActor.getRaftActorContext().isVotingMember());
1423         assertEquals("getRaftState", RaftState.Follower, node1RaftActor.getRaftState());
1424
1425         MessageCollectorActor.expectFirstMatching(node2Collector, ApplyJournalEntries.class);
1426         verifyServerConfigurationPayloadEntry(node2RaftActor.getRaftActorContext().getReplicatedLog(),
1427                 votingServer(node1ID), votingServer(node2ID));
1428         assertEquals("getRaftState", RaftState.Leader, node2RaftActor.getRaftState());
1429
1430         LOG.info("testChangeToVotingWithNoLeaderAndOtherLeaderElected ending");
1431     }
1432
1433     private static void verifyRaftState(RaftState expState, RaftActor... raftActors) {
1434         Stopwatch sw = Stopwatch.createStarted();
1435         while (sw.elapsed(TimeUnit.SECONDS) <= 5) {
1436             for (RaftActor raftActor : raftActors) {
1437                 if (raftActor.getRaftState() == expState) {
1438                     return;
1439                 }
1440             }
1441         }
1442
1443         fail("None of the RaftActors have state " + expState);
1444     }
1445
1446     private static ServerInfo votingServer(String id) {
1447         return new ServerInfo(id, true);
1448     }
1449
1450     private static ServerInfo nonVotingServer(String id) {
1451         return new ServerInfo(id, false);
1452     }
1453
1454     private TestActorRef<MessageCollectorActor> newLeaderCollectorActor(MockLeaderRaftActor leaderRaftActor) {
1455         return newCollectorActor(leaderRaftActor, LEADER_ID);
1456     }
1457
1458     private TestActorRef<MessageCollectorActor> newCollectorActor(AbstractMockRaftActor raftActor, String id) {
1459         TestActorRef<MessageCollectorActor> collectorActor = actorFactory.createTestActor(
1460                 MessageCollectorActor.props().withDispatcher(Dispatchers.DefaultDispatcherId()),
1461                 actorFactory.generateActorId(id + "Collector"));
1462         raftActor.setCollectorActor(collectorActor);
1463         return collectorActor;
1464     }
1465
1466     private static void verifyServerConfigurationPayloadEntry(ReplicatedLog log, ServerInfo... expected) {
1467         ReplicatedLogEntry logEntry = log.get(log.lastIndex());
1468         assertEquals("Last log entry payload class", ServerConfigurationPayload.class, logEntry.getData().getClass());
1469         ServerConfigurationPayload payload = (ServerConfigurationPayload)logEntry.getData();
1470         assertEquals("Server config", Sets.newHashSet(expected), Sets.newHashSet(payload.getServerConfig()));
1471     }
1472
1473     private static RaftActorContextImpl newFollowerContext(String id, TestActorRef<? extends UntypedActor> actor) {
1474         DefaultConfigParamsImpl configParams = new DefaultConfigParamsImpl();
1475         configParams.setHeartBeatInterval(new FiniteDuration(100, TimeUnit.MILLISECONDS));
1476         configParams.setElectionTimeoutFactor(100000);
1477         NonPersistentDataProvider noPersistence = new NonPersistentDataProvider();
1478         ElectionTermImpl termInfo = new ElectionTermImpl(noPersistence, id, LOG);
1479         termInfo.update(1, LEADER_ID);
1480         return new RaftActorContextImpl(actor, actor.underlyingActor().getContext(),
1481                 id, termInfo, -1, -1, ImmutableMap.of(LEADER_ID, ""), configParams, noPersistence, LOG);
1482     }
1483
1484     abstract static class AbstractMockRaftActor extends MockRaftActor {
1485         private volatile TestActorRef<MessageCollectorActor> collectorActor;
1486         private volatile Class<?> dropMessageOfType;
1487
1488         AbstractMockRaftActor(String id, Map<String, String> peerAddresses, Optional<ConfigParams> config,
1489                 boolean persistent, TestActorRef<MessageCollectorActor> collectorActor) {
1490             super(builder().id(id).peerAddresses(peerAddresses).config(config.get())
1491                     .persistent(Optional.of(persistent)));
1492             this.collectorActor = collectorActor;
1493         }
1494
1495         void setDropMessageOfType(Class<?> dropMessageOfType) {
1496             this.dropMessageOfType = dropMessageOfType;
1497         }
1498
1499         void setCollectorActor(TestActorRef<MessageCollectorActor> collectorActor) {
1500             this.collectorActor = collectorActor;
1501         }
1502
1503         @Override
1504         public void handleCommand(Object message) {
1505             if (dropMessageOfType == null || !dropMessageOfType.equals(message.getClass())) {
1506                 super.handleCommand(message);
1507             }
1508
1509             if (collectorActor != null) {
1510                 collectorActor.tell(message, getSender());
1511             }
1512         }
1513     }
1514
1515     public static class CollectingMockRaftActor extends AbstractMockRaftActor {
1516
1517         CollectingMockRaftActor(String id, Map<String, String> peerAddresses, Optional<ConfigParams> config,
1518                 boolean persistent, TestActorRef<MessageCollectorActor> collectorActor) {
1519             super(id, peerAddresses, config, persistent, collectorActor);
1520             snapshotCohortDelegate = new RaftActorSnapshotCohort() {
1521                 @Override
1522                 public void createSnapshot(ActorRef actorRef) {
1523                     actorRef.tell(new CaptureSnapshotReply(new byte[0]), actorRef);
1524                 }
1525
1526                 @Override
1527                 public void applySnapshot(byte[] snapshotBytes) {
1528                 }
1529             };
1530         }
1531
1532         public static Props props(final String id, final Map<String, String> peerAddresses,
1533                 ConfigParams config, boolean persistent, TestActorRef<MessageCollectorActor> collectorActor) {
1534
1535             return Props.create(CollectingMockRaftActor.class, id, peerAddresses, Optional.of(config),
1536                     persistent, collectorActor);
1537         }
1538
1539     }
1540
1541     public static class MockLeaderRaftActor extends AbstractMockRaftActor {
1542         public MockLeaderRaftActor(Map<String, String> peerAddresses, ConfigParams config,
1543                 RaftActorContext fromContext) {
1544             super(LEADER_ID, peerAddresses, Optional.of(config), NO_PERSISTENCE, null);
1545             setPersistence(false);
1546
1547             RaftActorContext context = getRaftActorContext();
1548             for (int i = 0; i < fromContext.getReplicatedLog().size(); i++) {
1549                 ReplicatedLogEntry entry = fromContext.getReplicatedLog().get(i);
1550                 getState().add(entry.getData());
1551                 context.getReplicatedLog().append(entry);
1552             }
1553
1554             context.setCommitIndex(fromContext.getCommitIndex());
1555             context.setLastApplied(fromContext.getLastApplied());
1556             context.getTermInformation().update(fromContext.getTermInformation().getCurrentTerm(),
1557                     fromContext.getTermInformation().getVotedFor());
1558         }
1559
1560         @Override
1561         protected void initializeBehavior() {
1562             changeCurrentBehavior(new Leader(getRaftActorContext()));
1563             initializeBehaviorComplete.countDown();
1564         }
1565
1566         @Override
1567         @SuppressWarnings("checkstyle:IllegalCatch")
1568         public void createSnapshot(ActorRef actorRef) {
1569             try {
1570                 actorRef.tell(new CaptureSnapshotReply(RaftActorTest.fromObject(getState()).toByteArray()), actorRef);
1571             } catch (Exception e) {
1572                 LOG.error("createSnapshot failed", e);
1573             }
1574         }
1575
1576         static Props props(Map<String, String> peerAddresses, RaftActorContext fromContext) {
1577             DefaultConfigParamsImpl configParams = new DefaultConfigParamsImpl();
1578             configParams.setHeartBeatInterval(new FiniteDuration(100, TimeUnit.MILLISECONDS));
1579             configParams.setElectionTimeoutFactor(10);
1580             return Props.create(MockLeaderRaftActor.class, peerAddresses, configParams, fromContext);
1581         }
1582     }
1583
1584     public static class MockNewFollowerRaftActor extends AbstractMockRaftActor {
1585         public MockNewFollowerRaftActor(ConfigParams config, TestActorRef<MessageCollectorActor> collectorActor) {
1586             super(NEW_SERVER_ID, Maps.<String, String>newHashMap(), Optional.of(config), NO_PERSISTENCE,
1587                     collectorActor);
1588             setPersistence(false);
1589         }
1590
1591         static Props props(ConfigParams config, TestActorRef<MessageCollectorActor> collectorActor) {
1592             return Props.create(MockNewFollowerRaftActor.class, config, collectorActor);
1593         }
1594     }
1595 }

©2013 OpenDaylight, A Linux Foundation Collaborative Project. All Rights Reserved.
OpenDaylight is a registered trademark of The OpenDaylight Project, Inc.
Linux Foundation and OpenDaylight are registered trademarks of the Linux Foundation.
Linux is a registered trademark of Linus Torvalds.