2 * Copyright (c) 2015 Brocade Communications Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.controller.cluster.raft;
10 import static org.junit.Assert.assertArrayEquals;
11 import static org.junit.Assert.assertEquals;
12 import akka.persistence.SaveSnapshotSuccess;
13 import com.google.common.collect.ImmutableMap;
14 import java.util.Arrays;
15 import java.util.List;
17 import org.junit.Assert;
18 import org.junit.Test;
19 import org.opendaylight.controller.cluster.raft.MockRaftActorContext.MockPayload;
20 import org.opendaylight.controller.cluster.raft.RaftActor.UpdateElectionTerm;
21 import org.opendaylight.controller.cluster.raft.base.messages.ApplyJournalEntries;
22 import org.opendaylight.controller.cluster.raft.base.messages.ApplySnapshot;
23 import org.opendaylight.controller.cluster.raft.base.messages.ApplyState;
24 import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshot;
25 import org.opendaylight.controller.cluster.raft.messages.AppendEntries;
26 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
27 import org.opendaylight.controller.cluster.raft.messages.InstallSnapshot;
28 import org.opendaylight.controller.cluster.raft.messages.InstallSnapshotReply;
29 import org.opendaylight.controller.cluster.raft.messages.RequestVoteReply;
30 import org.opendaylight.controller.cluster.raft.utils.InMemoryJournal;
31 import org.opendaylight.controller.cluster.raft.utils.InMemorySnapshotStore;
32 import org.opendaylight.controller.cluster.raft.utils.MessageCollectorActor;
35 * Tests replication and snapshots end-to-end using real RaftActors and behavior communication with a
38 * @author Thomas Pantelis
40 public class ReplicationAndSnapshotsWithLaggingFollowerIntegrationTest extends AbstractRaftActorIntegrationTest {
42 private MockPayload payload9;
43 private MockPayload payload11;
44 private MockPayload payload12;
45 private MockPayload payload13;
48 public void runTest() throws Exception {
49 testLog.info("testReplicationAndSnapshotsWithLaggingFollower starting");
51 leaderId = factory.generateActorId("leader");
52 follower1Id = factory.generateActorId("follower");
53 follower2Id = factory.generateActorId("follower");
55 // Setup the persistent journal for the leader - just an election term and no journal/snapshots.
56 InMemoryJournal.addEntry(leaderId, 1, new UpdateElectionTerm(initialTerm, leaderId));
58 // Create the leader and 2 follower actors.
60 follower1Actor = newTestRaftActor(follower1Id, null, newFollowerConfigParams());
62 follower2Actor = newTestRaftActor(follower2Id, null, newFollowerConfigParams());
64 Map<String, String> peerAddresses = ImmutableMap.<String, String>builder().
65 put(follower1Id, follower1Actor.path().toString()).
66 put(follower2Id, follower2Actor.path().toString()).build();
68 leaderConfigParams = newLeaderConfigParams();
69 leaderActor = newTestRaftActor(leaderId, peerAddresses, leaderConfigParams);
71 waitUntilLeader(leaderActor);
73 leaderContext = leaderActor.underlyingActor().getRaftActorContext();
74 leader = leaderActor.underlyingActor().getCurrentBehavior();
76 follower1Context = follower1Actor.underlyingActor().getRaftActorContext();
77 follower1 = follower1Actor.underlyingActor().getCurrentBehavior();
79 follower2Context = follower2Actor.underlyingActor().getRaftActorContext();
80 follower2 = follower2Actor.underlyingActor().getCurrentBehavior();
82 currentTerm = leaderContext.getTermInformation().getCurrentTerm();
83 assertEquals("Current term > " + initialTerm, true, currentTerm > initialTerm);
85 leaderCollectorActor = leaderActor.underlyingActor().collectorActor();
86 follower1CollectorActor = follower1Actor.underlyingActor().collectorActor();
87 follower2CollectorActor = follower2Actor.underlyingActor().collectorActor();
89 testLog.info("Leader created and elected");
91 testInitialReplications();
93 testSubsequentReplicationsAndSnapshots();
95 testLeaderSnapshotTriggeredByMemoryThresholdExceeded();
97 testInstallSnapshotToLaggingFollower();
99 verifyNoSubsequentSnapshotAfterMemoryThresholdExceededSnapshot();
101 testFinalReplicationsAndSnapshot();
103 testLeaderReinstatement();
105 testLog.info("testReplicationAndSnapshotsWithLaggingFollower ending");
109 * Send 3 payload instances with follower 2 temporarily lagging.
113 private void testInitialReplications() throws Exception {
115 testLog.info("testInitialReplications starting: sending 2 new payloads");
117 // Simulate lagging by dropping AppendEntries messages in follower 2.
118 follower2Actor.underlyingActor().startDropMessages(AppendEntries.class);
120 // Send the payloads.
121 MockPayload payload0 = sendPayloadData(leaderActor, "zero");
122 MockPayload payload1 = sendPayloadData(leaderActor, "one");
123 MockPayload payload2 = sendPayloadData(leaderActor, "two");
125 // Verify the leader got consensus and applies each log entry even though follower 2 didn't respond.
126 List<ApplyState> applyStates = MessageCollectorActor.expectMatching(leaderCollectorActor, ApplyState.class, 3);
127 verifyApplyState(applyStates.get(0), leaderCollectorActor, payload0.toString(), currentTerm, 0, payload0);
128 verifyApplyState(applyStates.get(1), leaderCollectorActor, payload1.toString(), currentTerm, 1, payload1);
129 verifyApplyState(applyStates.get(2), leaderCollectorActor, payload2.toString(), currentTerm, 2, payload2);
131 // Verify follower 1 applies each log entry.
132 applyStates = MessageCollectorActor.expectMatching(follower1CollectorActor, ApplyState.class, 3);
133 verifyApplyState(applyStates.get(0), null, null, currentTerm, 0, payload0);
134 verifyApplyState(applyStates.get(1), null, null, currentTerm, 1, payload1);
135 verifyApplyState(applyStates.get(2), null, null, currentTerm, 2, payload2);
137 // Ensure there's at least 1 more heartbeat.
138 MessageCollectorActor.clearMessages(leaderCollectorActor);
139 MessageCollectorActor.expectFirstMatching(leaderCollectorActor, AppendEntriesReply.class);
141 // The leader should not have performed fake snapshots to trim the log because the entries have not
142 // been replicated to follower 2.
143 assertEquals("Leader snapshot term", -1, leaderContext.getReplicatedLog().getSnapshotTerm());
144 assertEquals("Leader snapshot index", -1, leaderContext.getReplicatedLog().getSnapshotIndex());
145 assertEquals("Leader journal log size", 3, leaderContext.getReplicatedLog().size());
146 assertEquals("Leader journal last index", 2, leaderContext.getReplicatedLog().lastIndex());
147 assertEquals("Leader commit index", 2, leaderContext.getCommitIndex());
148 assertEquals("Leader last applied", 2, leaderContext.getLastApplied());
149 assertEquals("Leader replicatedToAllIndex", -1, leader.getReplicatedToAllIndex());
151 testLog.info("Step 3: new entries applied - re-enabling follower {}", follower2Id);
153 // Now stop dropping AppendEntries in follower 2.
154 follower2Actor.underlyingActor().stopDropMessages(AppendEntries.class);
156 // Verify follower 2 applies each log entry.
157 applyStates = MessageCollectorActor.expectMatching(follower2CollectorActor, ApplyState.class, 3);
158 verifyApplyState(applyStates.get(0), null, null, currentTerm, 0, payload0);
159 verifyApplyState(applyStates.get(1), null, null, currentTerm, 1, payload1);
160 verifyApplyState(applyStates.get(2), null, null, currentTerm, 2, payload2);
162 // Ensure there's at least 1 more heartbeat.
163 MessageCollectorActor.clearMessages(leaderCollectorActor);
164 MessageCollectorActor.expectFirstMatching(leaderCollectorActor, AppendEntriesReply.class);
166 // The leader should now have performed fake snapshots to trim the log.
167 assertEquals("Leader snapshot term", currentTerm, leaderContext.getReplicatedLog().getSnapshotTerm());
168 assertEquals("Leader snapshot index", 1, leaderContext.getReplicatedLog().getSnapshotIndex());
169 assertEquals("Leader journal log size", 1, leaderContext.getReplicatedLog().size());
170 assertEquals("Leader journal last index", 2, leaderContext.getReplicatedLog().lastIndex());
171 assertEquals("Leader commit index", 2, leaderContext.getCommitIndex());
172 assertEquals("Leader last applied", 2, leaderContext.getLastApplied());
173 // Note - replicatedToAllIndex always lags 1 behind last applied since it trims the log up to the
174 // last applied index. The next entry successfully replicated to followers woild advance it.
175 assertEquals("Leader replicatedToAllIndex", 1, leader.getReplicatedToAllIndex());
177 // Even though follower 2 lagged behind, the leader should not have tried to install a snapshot
178 // to catch it up because no snapshotting was done so the follower's next index was present in the log.
179 InstallSnapshot installSnapshot = MessageCollectorActor.getFirstMatching(follower2CollectorActor,
180 InstallSnapshot.class);
181 Assert.assertNull("Follower 2 received unexpected InstallSnapshot", installSnapshot);
183 MessageCollectorActor.clearMessages(leaderCollectorActor);
184 MessageCollectorActor.clearMessages(follower1CollectorActor);
185 MessageCollectorActor.clearMessages(follower2CollectorActor);
187 testLog.info("testInitialReplications complete");
191 * Send 5 more payloads with follower 2 lagging. Since the snapshotBatch count is 4, this should cause
192 * 2 leader snapshots and follower 2's log will be behind by 5 entries.
196 private void testSubsequentReplicationsAndSnapshots() throws Exception {
197 testLog.info("testSubsequentReplicationsAndSnapshots starting: sending first payload, replicatedToAllIndex: {}",
198 leader.getReplicatedToAllIndex());
200 leaderActor.underlyingActor().setSnapshot(new byte[] {2});
202 follower2Actor.underlyingActor().startDropMessages(AppendEntries.class);
204 // Send the first payload - this should cause the first snapshot.
205 MockPayload payload3 = sendPayloadData(leaderActor, "three");
207 MessageCollectorActor.expectFirstMatching(leaderCollectorActor, SaveSnapshotSuccess.class);
209 byte[] snapshot = new byte[] {6};
210 leaderActor.underlyingActor().setSnapshot(snapshot);
212 testLog.info("testSubsequentReplicationsAndSnapshots: sending 4 more payloads");
214 // Send the next 4. The last one should cause the second snapshot.
215 MockPayload payload4 = sendPayloadData(leaderActor, "four");
216 MockPayload payload5 = sendPayloadData(leaderActor, "five");
217 MockPayload payload6 = sendPayloadData(leaderActor, "six");
218 MockPayload payload7 = sendPayloadData(leaderActor, "seven");
220 // Verify the leader got consensus and applies each log entry even though follower 2 didn't respond.
221 List<ApplyState> applyStates = MessageCollectorActor.expectMatching(leaderCollectorActor, ApplyState.class, 5);
222 verifyApplyState(applyStates.get(0), leaderCollectorActor, payload3.toString(), currentTerm, 3, payload3);
223 verifyApplyState(applyStates.get(1), leaderCollectorActor, payload4.toString(), currentTerm, 4, payload4);
224 verifyApplyState(applyStates.get(2), leaderCollectorActor, payload5.toString(), currentTerm, 5, payload5);
225 verifyApplyState(applyStates.get(3), leaderCollectorActor, payload6.toString(), currentTerm, 6, payload6);
226 verifyApplyState(applyStates.get(4), leaderCollectorActor, payload7.toString(), currentTerm, 7, payload7);
228 // Verify follower 1 applies each log entry.
229 applyStates = MessageCollectorActor.expectMatching(follower1CollectorActor, ApplyState.class, 5);
230 verifyApplyState(applyStates.get(0), null, null, currentTerm, 3, payload3);
231 verifyApplyState(applyStates.get(1), null, null, currentTerm, 4, payload4);
232 verifyApplyState(applyStates.get(2), null, null, currentTerm, 5, payload5);
233 verifyApplyState(applyStates.get(3), null, null, currentTerm, 6, payload6);
234 verifyApplyState(applyStates.get(4), null, null, currentTerm, 7, payload7);
236 // Wait for snapshot completion.
237 MessageCollectorActor.expectFirstMatching(leaderCollectorActor, SaveSnapshotSuccess.class);
239 // The first new entry applied should have caused the leader to advanced the snapshot index to the
240 // last previously applied index (2) that was replicated to all followers.
241 assertEquals("Leader snapshot term", currentTerm, leaderContext.getReplicatedLog().getSnapshotTerm());
242 assertEquals("Leader snapshot index", 2, leaderContext.getReplicatedLog().getSnapshotIndex());
243 assertEquals("Leader journal log size", 5, leaderContext.getReplicatedLog().size());
244 assertEquals("Leader journal last index", 7, leaderContext.getReplicatedLog().lastIndex());
245 assertEquals("Leader commit index", 7, leaderContext.getCommitIndex());
246 assertEquals("Leader last applied", 7, leaderContext.getLastApplied());
247 assertEquals("Leader replicatedToAllIndex", 2, leader.getReplicatedToAllIndex());
249 // Now stop dropping AppendEntries in follower 2.
250 follower2Actor.underlyingActor().stopDropMessages(AppendEntries.class);
252 // Verify follower 2 applies each log entry.
253 applyStates = MessageCollectorActor.expectMatching(follower2CollectorActor, ApplyState.class, 5);
254 verifyApplyState(applyStates.get(0), null, null, currentTerm, 3, payload3);
255 verifyApplyState(applyStates.get(1), null, null, currentTerm, 4, payload4);
256 verifyApplyState(applyStates.get(2), null, null, currentTerm, 5, payload5);
257 verifyApplyState(applyStates.get(3), null, null, currentTerm, 6, payload6);
258 verifyApplyState(applyStates.get(4), null, null, currentTerm, 7, payload7);
260 // Ensure there's at least 1 more heartbeat.
261 MessageCollectorActor.clearMessages(leaderCollectorActor);
262 MessageCollectorActor.expectFirstMatching(leaderCollectorActor, AppendEntriesReply.class);
264 // The leader should now have performed fake snapshots to advance the snapshot index and to trim
265 // the log. In addition replicatedToAllIndex should've advanced.
266 assertEquals("Leader snapshot term", currentTerm, leaderContext.getReplicatedLog().getSnapshotTerm());
267 assertEquals("Leader snapshot index", 6, leaderContext.getReplicatedLog().getSnapshotIndex());
268 assertEquals("Leader journal log size", 1, leaderContext.getReplicatedLog().size());
269 assertEquals("Leader journal last index", 7, leaderContext.getReplicatedLog().lastIndex());
270 assertEquals("Leader replicatedToAllIndex", 6, leader.getReplicatedToAllIndex());
272 // Verify the leader's persisted snapshot.
273 List<Snapshot> persistedSnapshots = InMemorySnapshotStore.getSnapshots(leaderId, Snapshot.class);
274 assertEquals("Persisted snapshots size", 1, persistedSnapshots.size());
275 verifySnapshot("Persisted", persistedSnapshots.get(0), currentTerm, 3, currentTerm, 7, snapshot);
276 List<ReplicatedLogEntry> unAppliedEntry = persistedSnapshots.get(0).getUnAppliedEntries();
277 assertEquals("Persisted Snapshot getUnAppliedEntries size", 4, unAppliedEntry.size());
278 verifyReplicatedLogEntry(unAppliedEntry.get(0), currentTerm, 4, payload4);
279 verifyReplicatedLogEntry(unAppliedEntry.get(1), currentTerm, 5, payload5);
280 verifyReplicatedLogEntry(unAppliedEntry.get(2), currentTerm, 6, payload6);
281 verifyReplicatedLogEntry(unAppliedEntry.get(3), currentTerm, 7, payload7);
283 // Even though follower 2's log was behind by 5 entries and 2 snapshots were done, the leader
284 // should not have tried to install a snapshot to catch it up because replicatedToAllIndex was also
285 // behind. Instead of installing a snapshot the leader would've sent AppendEntries with the log entries.
286 InstallSnapshot installSnapshot = MessageCollectorActor.getFirstMatching(follower2CollectorActor, InstallSnapshot.class);
287 Assert.assertNull("Follower 2 received unexpected InstallSnapshot", installSnapshot);
289 // Verify follower 1's log and snapshot indexes.
290 MessageCollectorActor.clearMessages(follower1CollectorActor);
291 MessageCollectorActor.expectFirstMatching(follower1CollectorActor, AppendEntries.class);
292 assertEquals("Follower 1 snapshot term", currentTerm, follower1Context.getReplicatedLog().getSnapshotTerm());
293 assertEquals("Follower 1 snapshot index", 6, follower1Context.getReplicatedLog().getSnapshotIndex());
294 assertEquals("Follower 1 journal log size", 1, follower1Context.getReplicatedLog().size());
295 assertEquals("Follower 1 journal last index", 7, follower1Context.getReplicatedLog().lastIndex());
296 assertEquals("Follower 1 commit index", 7, follower1Context.getCommitIndex());
297 assertEquals("Follower 1 last applied", 7, follower1Context.getLastApplied());
298 assertEquals("Follower 1 replicatedToAllIndex", 6, follower1.getReplicatedToAllIndex());
300 // Verify follower 2's log and snapshot indexes.
301 MessageCollectorActor.clearMessages(follower2CollectorActor);
302 MessageCollectorActor.expectFirstMatching(follower2CollectorActor, AppendEntries.class);
303 assertEquals("Follower 2 snapshot term", currentTerm, follower2Context.getReplicatedLog().getSnapshotTerm());
304 assertEquals("Follower 2 snapshot index", 6, follower2Context.getReplicatedLog().getSnapshotIndex());
305 assertEquals("Follower 2 journal log size", 1, follower2Context.getReplicatedLog().size());
306 assertEquals("Follower 2 journal last index", 7, follower2Context.getReplicatedLog().lastIndex());
307 assertEquals("Follower 2 commit index", 7, follower2Context.getCommitIndex());
308 assertEquals("Follower 2 last applied", 7, follower2Context.getLastApplied());
309 assertEquals("Follower 2 replicatedToAllIndex", 6, follower2.getReplicatedToAllIndex());
311 MessageCollectorActor.clearMessages(leaderCollectorActor);
312 MessageCollectorActor.clearMessages(follower1CollectorActor);
313 MessageCollectorActor.clearMessages(follower2CollectorActor);
315 testLog.info("testSubsequentReplicationsAndSnapshots complete");
319 * Send a couple more payloads with follower 2 lagging. The last payload will have a large enough size
320 * to trigger a leader snapshot.
324 private void testLeaderSnapshotTriggeredByMemoryThresholdExceeded() throws Exception {
325 testLog.info("testLeaderSnapshotTriggeredByMemoryThresholdExceeded starting: sending 3 payloads, replicatedToAllIndex: {}",
326 leader.getReplicatedToAllIndex());
328 leaderActor.underlyingActor().setMockTotalMemory(1000);
329 byte[] snapshot = new byte[] {6};
330 leaderActor.underlyingActor().setSnapshot(snapshot);
332 // We'll expect a ReplicatedLogImplEntry message and an ApplyJournalEntries message added to the journal.
333 InMemoryJournal.addWriteMessagesCompleteLatch(leaderId, 2);
335 follower2Actor.underlyingActor().startDropMessages(AppendEntries.class);
337 // Send a payload with a large relative size but not enough to trigger a snapshot.
338 MockPayload payload8 = sendPayloadData(leaderActor, "eight", 500);
340 // Verify the leader got consensus and applies the first log entry even though follower 2 didn't respond.
341 List<ApplyState> applyStates = MessageCollectorActor.expectMatching(leaderCollectorActor, ApplyState.class, 1);
342 verifyApplyState(applyStates.get(0), leaderCollectorActor, payload8.toString(), currentTerm, 8, payload8);
344 // Wait for all the ReplicatedLogImplEntry and ApplyJournalEntries messages to be added to the journal
345 // before the snapshot so the snapshot sequence # will be higher to ensure the snapshot gets
346 // purged from the snapshot store after subsequent snapshots.
347 InMemoryJournal.waitForWriteMessagesComplete(leaderId);
349 // Verify a snapshot is not triggered.
350 CaptureSnapshot captureSnapshot = MessageCollectorActor.getFirstMatching(leaderCollectorActor, CaptureSnapshot.class);
351 Assert.assertNull("Leader received unexpected CaptureSnapshot", captureSnapshot);
353 // Send another payload with a large enough relative size in combination with the last payload
354 // that exceeds the memory threshold (70% * 1000 = 700) - this should do a snapshot.
355 payload9 = sendPayloadData(leaderActor, "nine", 201);
357 // Verify the leader applies the last log entry.
358 applyStates = MessageCollectorActor.expectMatching(leaderCollectorActor, ApplyState.class, 2);
359 verifyApplyState(applyStates.get(1), leaderCollectorActor, payload9.toString(), currentTerm, 9, payload9);
361 // Verify follower 1 applies each log entry.
362 applyStates = MessageCollectorActor.expectMatching(follower1CollectorActor, ApplyState.class, 2);
363 verifyApplyState(applyStates.get(0), null, null, currentTerm, 8, payload8);
364 verifyApplyState(applyStates.get(1), null, null, currentTerm, 9, payload9);
366 // A snapshot should've occurred - wait for it to complete.
367 MessageCollectorActor.expectFirstMatching(leaderCollectorActor, SaveSnapshotSuccess.class);
369 // Because the snapshot was triggered by exceeding the memory threshold the leader should've advanced
370 // the snapshot index to the last applied index and trimmed the log even though the entries weren't
371 // replicated to all followers.
372 assertEquals("Leader snapshot term", currentTerm, leaderContext.getReplicatedLog().getSnapshotTerm());
373 assertEquals("Leader snapshot index", 8, leaderContext.getReplicatedLog().getSnapshotIndex());
374 assertEquals("Leader journal log size", 1, leaderContext.getReplicatedLog().size());
375 assertEquals("Leader journal last index", 9, leaderContext.getReplicatedLog().lastIndex());
376 assertEquals("Leader commit index", 9, leaderContext.getCommitIndex());
377 assertEquals("Leader last applied", 9, leaderContext.getLastApplied());
378 // Note: replicatedToAllIndex should not be advanced since log entries 8 and 9 haven't yet been
379 // replicated to follower 2.
380 assertEquals("Leader replicatedToAllIndex", 7, leader.getReplicatedToAllIndex());
382 // Verify the leader's persisted snapshot.
383 List<Snapshot> persistedSnapshots = InMemorySnapshotStore.getSnapshots(leaderId, Snapshot.class);
384 assertEquals("Persisted snapshots size", 1, persistedSnapshots.size());
385 verifySnapshot("Persisted", persistedSnapshots.get(0), currentTerm, 8, currentTerm, 9, snapshot);
386 List<ReplicatedLogEntry> unAppliedEntry = persistedSnapshots.get(0).getUnAppliedEntries();
387 assertEquals("Persisted Snapshot getUnAppliedEntries size", 1, unAppliedEntry.size());
388 verifyReplicatedLogEntry(unAppliedEntry.get(0), currentTerm, 9, payload9);
390 testLog.info("testLeaderSnapshotTriggeredByMemoryThresholdExceeded ending");
394 * Send another payload to verify another snapshot is not done since the last snapshot trimmed the
395 * first log entry so the memory threshold should not be exceeded.
399 private void verifyNoSubsequentSnapshotAfterMemoryThresholdExceededSnapshot() throws Exception {
400 ApplyState applyState;
401 CaptureSnapshot captureSnapshot;
403 MockPayload payload10 = sendPayloadData(leaderActor, "ten");
405 // Verify the leader applies the state.
406 applyState = MessageCollectorActor.expectFirstMatching(leaderCollectorActor, ApplyState.class);
407 verifyApplyState(applyState, leaderCollectorActor, payload10.toString(), currentTerm, 10, payload10);
409 captureSnapshot = MessageCollectorActor.getFirstMatching(leaderCollectorActor, CaptureSnapshot.class);
410 Assert.assertNull("Leader received unexpected CaptureSnapshot", captureSnapshot);
412 // Verify the follower 1 applies the state.
413 applyState = MessageCollectorActor.expectFirstMatching(follower1CollectorActor, ApplyState.class);
414 verifyApplyState(applyState, null, null, currentTerm, 10, payload10);
416 // Verify the follower 2 applies the state.
417 applyState = MessageCollectorActor.expectFirstMatching(follower2CollectorActor, ApplyState.class);
418 verifyApplyState(applyState, null, null, currentTerm, 10, payload10);
420 // Verify the leader's state.
421 assertEquals("Leader snapshot term", currentTerm, leaderContext.getReplicatedLog().getSnapshotTerm());
422 assertEquals("Leader snapshot index", 9, leaderContext.getReplicatedLog().getSnapshotIndex());
423 assertEquals("Leader journal log size", 1, leaderContext.getReplicatedLog().size());
424 assertEquals("Leader journal last index", 10, leaderContext.getReplicatedLog().lastIndex());
425 assertEquals("Leader commit index", 10, leaderContext.getCommitIndex());
426 assertEquals("Leader last applied", 10, leaderContext.getLastApplied());
427 assertEquals("Leader replicatedToAllIndex", 9, leader.getReplicatedToAllIndex());
429 // Verify follower 1's state.
430 assertEquals("Follower 1 snapshot term", currentTerm, follower1Context.getReplicatedLog().getSnapshotTerm());
431 assertEquals("Follower 1 snapshot index", 9, follower1Context.getReplicatedLog().getSnapshotIndex());
432 assertEquals("Follower 1 journal log size", 1, follower1Context.getReplicatedLog().size());
433 assertEquals("Follower 1 journal last index", 10, follower1Context.getReplicatedLog().lastIndex());
434 assertEquals("Follower 1 commit index", 10, follower1Context.getCommitIndex());
435 assertEquals("Follower 1 last applied", 10, follower1Context.getLastApplied());
436 assertEquals("Follower 1 replicatedToAllIndex", 9, follower1.getReplicatedToAllIndex());
438 // Verify follower 2's state.
439 assertEquals("Follower 2 snapshot term", currentTerm, follower2Context.getReplicatedLog().getSnapshotTerm());
440 assertEquals("Follower 2 snapshot index", 9, follower2Context.getReplicatedLog().getSnapshotIndex());
441 assertEquals("Follower 2 journal log size", 1, follower2Context.getReplicatedLog().size());
442 assertEquals("Follower 2 journal last index", 10, follower2Context.getReplicatedLog().lastIndex());
443 assertEquals("Follower 2 commit index", 10, follower2Context.getCommitIndex());
444 assertEquals("Follower 2 last applied", 10, follower2Context.getLastApplied());
445 assertEquals("Follower 2 replicatedToAllIndex", 9, follower2.getReplicatedToAllIndex());
447 // Revert back to JVM total memory.
448 leaderActor.underlyingActor().setMockTotalMemory(0);
450 MessageCollectorActor.clearMessages(leaderCollectorActor);
451 MessageCollectorActor.clearMessages(follower1CollectorActor);
452 MessageCollectorActor.clearMessages(follower2CollectorActor);
456 * Following a snapshot due memory threshold exceeded, resume the lagging follower and verify it receives
457 * an install snapshot from the leader.
461 private void testInstallSnapshotToLaggingFollower() throws Exception {
462 List<Snapshot> persistedSnapshots;
463 List<ReplicatedLogEntry> unAppliedEntry;
464 ApplyState applyState;
465 ApplySnapshot applySnapshot;
466 InstallSnapshot installSnapshot;
467 InstallSnapshotReply installSnapshotReply;
469 byte[] snapshot = new byte[] {10};
470 leaderActor.underlyingActor().setSnapshot(snapshot);
472 // Now stop dropping AppendEntries in follower 2.
473 follower2Actor.underlyingActor().stopDropMessages(AppendEntries.class);
475 installSnapshot = MessageCollectorActor.expectFirstMatching(follower2CollectorActor, InstallSnapshot.class);
476 assertEquals("InstallSnapshot getTerm", currentTerm, installSnapshot.getTerm());
477 assertEquals("InstallSnapshot getLeaderId", leaderId, installSnapshot.getLeaderId());
478 assertEquals("InstallSnapshot getChunkIndex", 1, installSnapshot.getChunkIndex());
479 assertEquals("InstallSnapshot getTotalChunks", 1, installSnapshot.getTotalChunks());
480 assertEquals("InstallSnapshot getLastIncludedTerm", currentTerm, installSnapshot.getLastIncludedTerm());
481 assertEquals("InstallSnapshot getLastIncludedIndex", 8, installSnapshot.getLastIncludedIndex());
482 assertArrayEquals("InstallSnapshot getData", snapshot, installSnapshot.getData().toByteArray());
484 installSnapshotReply = MessageCollectorActor.expectFirstMatching(leaderCollectorActor, InstallSnapshotReply.class);
485 assertEquals("InstallSnapshotReply getTerm", currentTerm, installSnapshotReply.getTerm());
486 assertEquals("InstallSnapshotReply getChunkIndex", 1, installSnapshotReply.getChunkIndex());
487 assertEquals("InstallSnapshotReply getFollowerId", follower2Id, installSnapshotReply.getFollowerId());
488 assertEquals("InstallSnapshotReply isSuccess", true, installSnapshotReply.isSuccess());
490 // Verify follower 2 applies the snapshot.
491 applySnapshot = MessageCollectorActor.expectFirstMatching(follower2CollectorActor, ApplySnapshot.class);
492 verifySnapshot("Follower 2", applySnapshot.getSnapshot(), currentTerm, 8, currentTerm, 8, snapshot);
493 assertEquals("Persisted Snapshot getUnAppliedEntries size", 0, applySnapshot.getSnapshot().getUnAppliedEntries().size());
495 // Verify follower 2 only applies the second log entry (9) as the first one (8) was in the snapshot.
496 applyState = MessageCollectorActor.expectFirstMatching(follower2CollectorActor, ApplyState.class);
497 verifyApplyState(applyState, null, null, currentTerm, 9, payload9);
499 // Wait for the snapshot to complete.
500 MessageCollectorActor.expectFirstMatching(leaderCollectorActor, SaveSnapshotSuccess.class);
502 // Ensure there's at least 1 more heartbeat.
503 MessageCollectorActor.clearMessages(leaderCollectorActor);
504 MessageCollectorActor.expectFirstMatching(leaderCollectorActor, AppendEntriesReply.class);
506 // The leader should now have performed fake snapshots to advance the snapshot index and to trim
507 // the log. In addition replicatedToAllIndex should've advanced.
508 assertEquals("Leader snapshot term", currentTerm, leaderContext.getReplicatedLog().getSnapshotTerm());
509 assertEquals("Leader snapshot index", 8, leaderContext.getReplicatedLog().getSnapshotIndex());
510 assertEquals("Leader journal log size", 1, leaderContext.getReplicatedLog().size());
511 assertEquals("Leader commit index", 9, leaderContext.getCommitIndex());
512 assertEquals("Leader last applied", 9, leaderContext.getLastApplied());
513 assertEquals("Leader replicatedToAllIndex", 8, leader.getReplicatedToAllIndex());
515 // Verify the leader's persisted snapshot. The previous snapshot (currently) won't be deleted from
516 // the snapshot store because the second snapshot was initiated by the follower install snapshot and
517 // not because the batch count was reached so the persisted journal sequence number wasn't advanced
518 // far enough to cause the previous snapshot to be deleted. This is because
519 // RaftActor#trimPersistentData subtracts the snapshotBatchCount from the snapshot's sequence number.
520 // This is OK - the next snapshot should delete it. In production, even if the system restarted
521 // before another snapshot, they would both get applied which wouldn't hurt anything.
522 persistedSnapshots = InMemorySnapshotStore.getSnapshots(leaderId, Snapshot.class);
523 Assert.assertTrue("Expected at least 1 persisted snapshots", persistedSnapshots.size() > 0);
524 Snapshot persistedSnapshot = persistedSnapshots.get(persistedSnapshots.size() - 1);
525 verifySnapshot("Persisted", persistedSnapshot, currentTerm, 9, currentTerm, 9, snapshot);
526 unAppliedEntry = persistedSnapshot.getUnAppliedEntries();
527 assertEquals("Persisted Snapshot getUnAppliedEntries size", 0, unAppliedEntry.size());
529 MessageCollectorActor.clearMessages(leaderCollectorActor);
530 MessageCollectorActor.clearMessages(follower1CollectorActor);
531 MessageCollectorActor.clearMessages(follower2CollectorActor);
535 * Do another round of payloads and snapshot to verify replicatedToAllIndex gets back on track and
536 * snapshots works as expected after doing a follower snapshot. In this step we don't lag a follower.
538 private void testFinalReplicationsAndSnapshot() {
539 List<ApplyState> applyStates;
540 ApplyState applyState;
542 testLog.info("testFinalReplicationsAndSnapshot starting: replicatedToAllIndex: {}", leader.getReplicatedToAllIndex());
544 byte[] snapshot = new byte[] {14};
545 leaderActor.underlyingActor().setSnapshot(snapshot);
547 // Send another payload - a snapshot should occur.
548 payload11 = sendPayloadData(leaderActor, "eleven");
550 // Wait for the snapshot to complete.
551 MessageCollectorActor.expectFirstMatching(leaderCollectorActor, SaveSnapshotSuccess.class);
553 applyState = MessageCollectorActor.expectFirstMatching(leaderCollectorActor, ApplyState.class);
554 verifyApplyState(applyState, leaderCollectorActor, payload11.toString(), currentTerm, 11, payload11);
556 // Verify the leader's last persisted snapshot (previous ones may not be purged yet).
557 List<Snapshot> persistedSnapshots = InMemorySnapshotStore.getSnapshots(leaderId, Snapshot.class);
558 Snapshot persistedSnapshot = persistedSnapshots.get(persistedSnapshots.size() - 1);
559 verifySnapshot("Persisted", persistedSnapshot, currentTerm, 10, currentTerm, 11, snapshot);
560 List<ReplicatedLogEntry> unAppliedEntry = persistedSnapshot.getUnAppliedEntries();
561 assertEquals("Persisted Snapshot getUnAppliedEntries size", 1, unAppliedEntry.size());
562 verifyReplicatedLogEntry(unAppliedEntry.get(0), currentTerm, 11, payload11);
564 // Send a couple more payloads.
565 payload12 = sendPayloadData(leaderActor, "twelve");
566 payload13 = sendPayloadData(leaderActor, "thirteen");
568 // Verify the leader applies the 2 log entries.
569 applyStates = MessageCollectorActor.expectMatching(leaderCollectorActor, ApplyState.class, 3);
570 verifyApplyState(applyStates.get(1), leaderCollectorActor, payload12.toString(), currentTerm, 12, payload12);
571 verifyApplyState(applyStates.get(2), leaderCollectorActor, payload13.toString(), currentTerm, 13, payload13);
573 // Verify the leader applies a log entry for at least the last entry index.
574 verifyApplyJournalEntries(leaderCollectorActor, 13);
576 // Ensure there's at least 1 more heartbeat to trim the log.
577 MessageCollectorActor.clearMessages(leaderCollectorActor);
578 MessageCollectorActor.expectFirstMatching(leaderCollectorActor, AppendEntriesReply.class);
580 // Verify the leader's final snapshot index et al.
581 assertEquals("Leader snapshot term", currentTerm, leaderContext.getReplicatedLog().getSnapshotTerm());
582 assertEquals("Leader snapshot index", 12, leaderContext.getReplicatedLog().getSnapshotIndex());
583 assertEquals("Leader journal log size", 1, leaderContext.getReplicatedLog().size());
584 assertEquals("Leader journal last index", 13, leaderContext.getReplicatedLog().lastIndex());
585 assertEquals("Leader commit index", 13, leaderContext.getCommitIndex());
586 assertEquals("Leader last applied", 13, leaderContext.getLastApplied());
587 assertEquals("Leader replicatedToAllIndex", 12, leader.getReplicatedToAllIndex());
589 InMemoryJournal.dumpJournal(leaderId);
591 // Verify the leaders's persisted journal log - should only contain the last 2 ReplicatedLogEntries
592 // added after the snapshot as the persisted journal should've been purged to the snapshot
594 verifyPersistedJournal(leaderId, Arrays.asList(new ReplicatedLogImplEntry(12, currentTerm, payload12),
595 new ReplicatedLogImplEntry(13, currentTerm, payload13)));
597 // Verify the leaders's persisted journal contains an ApplyJournalEntries for at least the last entry index.
598 List<ApplyJournalEntries> persistedApplyJournalEntries = InMemoryJournal.get(leaderId, ApplyJournalEntries.class);
599 boolean found = false;
600 for(ApplyJournalEntries entry: persistedApplyJournalEntries) {
601 if(entry.getToIndex() == 13) {
607 Assert.assertTrue(String.format("ApplyJournalEntries with index %d not found in leader's persisted journal", 13), found);
609 // Verify follower 1 applies the 2 log entries.
610 applyStates = MessageCollectorActor.expectMatching(follower1CollectorActor, ApplyState.class, 3);
611 verifyApplyState(applyStates.get(0), null, null, currentTerm, 11, payload11);
612 verifyApplyState(applyStates.get(1), null, null, currentTerm, 12, payload12);
613 verifyApplyState(applyStates.get(2), null, null, currentTerm, 13, payload13);
615 // Verify follower 1's log state.
616 assertEquals("Follower 1 snapshot term", currentTerm, follower1Context.getReplicatedLog().getSnapshotTerm());
617 assertEquals("Follower 1 snapshot index", 12, follower1Context.getReplicatedLog().getSnapshotIndex());
618 assertEquals("Follower 1 journal log size", 1, follower1Context.getReplicatedLog().size());
619 assertEquals("Follower 1 journal last index", 13, follower1Context.getReplicatedLog().lastIndex());
620 assertEquals("Follower 1 commit index", 13, follower1Context.getCommitIndex());
621 assertEquals("Follower 1 last applied", 13, follower1Context.getLastApplied());
622 assertEquals("Follower 1 replicatedToAllIndex", 12, follower1.getReplicatedToAllIndex());
624 // Verify follower 2 applies the 2 log entries.
625 applyStates = MessageCollectorActor.expectMatching(follower2CollectorActor, ApplyState.class, 3);
626 verifyApplyState(applyStates.get(0), null, null, currentTerm, 11, payload11);
627 verifyApplyState(applyStates.get(1), null, null, currentTerm, 12, payload12);
628 verifyApplyState(applyStates.get(2), null, null, currentTerm, 13, payload13);
630 // Verify follower 2's log state.
631 assertEquals("Follower 2 snapshot term", currentTerm, follower2Context.getReplicatedLog().getSnapshotTerm());
632 assertEquals("Follower 2 snapshot index", 12, follower2Context.getReplicatedLog().getSnapshotIndex());
633 assertEquals("Follower 2 journal log size", 1, follower2Context.getReplicatedLog().size());
634 assertEquals("Follower 2 journal last index", 13, follower2Context.getReplicatedLog().lastIndex());
635 assertEquals("Follower 2 commit index", 13, follower2Context.getCommitIndex());
636 assertEquals("Follower 2 last applied", 13, follower2Context.getLastApplied());
637 assertEquals("Follower 2 replicatedToAllIndex", 12, follower2.getReplicatedToAllIndex());
639 testLog.info("testFinalReplicationsAndSnapshot ending");
643 * Kill the leader actor, reinstate it and verify the recovered journal.
645 private void testLeaderReinstatement() {
646 testLog.info("testLeaderReinstatement starting");
648 killActor(leaderActor);
650 leaderActor = newTestRaftActor(leaderId, peerAddresses, leaderConfigParams);
652 leaderActor.underlyingActor().startDropMessages(RequestVoteReply.class);
654 leaderContext = leaderActor.underlyingActor().getRaftActorContext();
656 leaderActor.underlyingActor().waitForRecoveryComplete();
658 assertEquals("Leader snapshot term", currentTerm, leaderContext.getReplicatedLog().getSnapshotTerm());
659 assertEquals("Leader snapshot index", 10, leaderContext.getReplicatedLog().getSnapshotIndex());
660 assertEquals("Leader journal log size", 3, leaderContext.getReplicatedLog().size());
661 assertEquals("Leader journal last index", 13, leaderContext.getReplicatedLog().lastIndex());
662 assertEquals("Leader commit index", 13, leaderContext.getCommitIndex());
663 assertEquals("Leader last applied", 13, leaderContext.getLastApplied());
664 verifyReplicatedLogEntry(leaderContext.getReplicatedLog().get(11), currentTerm, 11, payload11);
665 verifyReplicatedLogEntry(leaderContext.getReplicatedLog().get(12), currentTerm, 12, payload12);
666 verifyReplicatedLogEntry(leaderContext.getReplicatedLog().get(13), currentTerm, 13, payload13);
668 testLog.info("testLeaderReinstatement ending");