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

©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.