Bug 3570: Use SnapShot lastAppliedIndex for install snapshot
[controller.git] / opendaylight / md-sal / sal-akka-raft / src / test / java / org / opendaylight / controller / cluster / raft / ReplicationAndSnapshotsWithLaggingFollowerIntegrationTest.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 akka.persistence.SaveSnapshotSuccess;
12 import com.google.common.collect.ImmutableMap;
13 import java.util.Arrays;
14 import java.util.List;
15 import java.util.Map;
16 import org.junit.Assert;
17 import org.junit.Test;
18 import org.opendaylight.controller.cluster.raft.MockRaftActorContext.MockPayload;
19 import org.opendaylight.controller.cluster.raft.base.messages.ApplyJournalEntries;
20 import org.opendaylight.controller.cluster.raft.base.messages.ApplySnapshot;
21 import org.opendaylight.controller.cluster.raft.base.messages.ApplyState;
22 import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshot;
23 import org.opendaylight.controller.cluster.raft.base.messages.UpdateElectionTerm;
24 import org.opendaylight.controller.cluster.raft.messages.AppendEntries;
25 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
26 import org.opendaylight.controller.cluster.raft.messages.InstallSnapshot;
27 import org.opendaylight.controller.cluster.raft.messages.InstallSnapshotReply;
28 import org.opendaylight.controller.cluster.raft.messages.RequestVoteReply;
29 import org.opendaylight.controller.cluster.raft.utils.InMemoryJournal;
30 import org.opendaylight.controller.cluster.raft.utils.InMemorySnapshotStore;
31 import org.opendaylight.controller.cluster.raft.utils.MessageCollectorActor;
32
33 /**
34  * Tests replication and snapshots end-to-end using real RaftActors and behavior communication with a
35  * lagging follower.
36  *
37  * @author Thomas Pantelis
38  */
39 public class ReplicationAndSnapshotsWithLaggingFollowerIntegrationTest extends AbstractRaftActorIntegrationTest {
40
41     private MockPayload payload9;
42     private MockPayload payload11;
43     private MockPayload payload12;
44     private MockPayload payload13;
45
46     @Test
47     public void runTest() throws Exception {
48         testLog.info("testReplicationAndSnapshotsWithLaggingFollower starting");
49
50         leaderId = factory.generateActorId("leader");
51         follower1Id = factory.generateActorId("follower");
52         follower2Id = factory.generateActorId("follower");
53
54         // Setup the persistent journal for the leader - just an election term and no journal/snapshots.
55         InMemoryJournal.addEntry(leaderId, 1, new UpdateElectionTerm(initialTerm, leaderId));
56
57         // Create the leader and 2 follower actors.
58         follower1Actor = newTestRaftActor(follower1Id, ImmutableMap.of(leaderId, testActorPath(leaderId),
59                 follower2Id, testActorPath(follower2Id)), newFollowerConfigParams());
60
61         follower2Actor = newTestRaftActor(follower2Id, ImmutableMap.of(leaderId, testActorPath(leaderId),
62                 follower1Id, testActorPath(follower1Id)), newFollowerConfigParams());
63
64         Map<String, String> peerAddresses = ImmutableMap.<String, String>builder().
65                 put(follower1Id, follower1Actor.path().toString()).
66                 put(follower2Id, follower2Actor.path().toString()).build();
67
68         leaderConfigParams = newLeaderConfigParams();
69         leaderActor = newTestRaftActor(leaderId, peerAddresses, leaderConfigParams);
70
71         waitUntilLeader(leaderActor);
72
73         leaderContext = leaderActor.underlyingActor().getRaftActorContext();
74         leader = leaderActor.underlyingActor().getCurrentBehavior();
75
76         follower1Context = follower1Actor.underlyingActor().getRaftActorContext();
77         follower1 = follower1Actor.underlyingActor().getCurrentBehavior();
78
79         follower2Context = follower2Actor.underlyingActor().getRaftActorContext();
80         follower2 = follower2Actor.underlyingActor().getCurrentBehavior();
81
82         currentTerm = leaderContext.getTermInformation().getCurrentTerm();
83         assertEquals("Current term > " + initialTerm, true, currentTerm > initialTerm);
84
85         leaderCollectorActor = leaderActor.underlyingActor().collectorActor();
86         follower1CollectorActor = follower1Actor.underlyingActor().collectorActor();
87         follower2CollectorActor = follower2Actor.underlyingActor().collectorActor();
88
89         testLog.info("Leader created and elected");
90
91         testInitialReplications();
92
93         testSubsequentReplicationsAndSnapshots();
94
95         testLeaderSnapshotTriggeredByMemoryThresholdExceeded();
96
97         testInstallSnapshotToLaggingFollower();
98
99         verifyNoSubsequentSnapshotAfterMemoryThresholdExceededSnapshot();
100
101         testFinalReplicationsAndSnapshot();
102
103         testLeaderReinstatement();
104
105         testLog.info("testReplicationAndSnapshotsWithLaggingFollower ending");
106     }
107
108     /**
109      * Send 3 payload instances with follower 2 temporarily lagging.
110      *
111      * @throws Exception
112      */
113     private void testInitialReplications() throws Exception {
114
115         testLog.info("testInitialReplications starting: sending 2 new payloads");
116
117         // Simulate lagging by dropping AppendEntries messages in follower 2.
118         follower2Actor.underlyingActor().startDropMessages(AppendEntries.class);
119
120         // Send the payloads.
121         MockPayload payload0 = sendPayloadData(leaderActor, "zero");
122         MockPayload payload1 = sendPayloadData(leaderActor, "one");
123         MockPayload payload2 = sendPayloadData(leaderActor, "two");
124
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);
130
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);
136
137         // Ensure there's at least 1 more heartbeat.
138         MessageCollectorActor.clearMessages(leaderCollectorActor);
139         MessageCollectorActor.expectFirstMatching(leaderCollectorActor, AppendEntriesReply.class);
140
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());
150
151         testLog.info("Step 3: new entries applied - re-enabling follower {}", follower2Id);
152
153         // Now stop dropping AppendEntries in follower 2.
154         follower2Actor.underlyingActor().stopDropMessages(AppendEntries.class);
155
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);
161
162         // Ensure there's at least 1 more heartbeat.
163         MessageCollectorActor.clearMessages(leaderCollectorActor);
164         MessageCollectorActor.expectFirstMatching(leaderCollectorActor, AppendEntriesReply.class);
165
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());
176
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);
182
183         MessageCollectorActor.clearMessages(leaderCollectorActor);
184         MessageCollectorActor.clearMessages(follower1CollectorActor);
185         MessageCollectorActor.clearMessages(follower2CollectorActor);
186
187         expSnapshotState.add(payload0);
188         expSnapshotState.add(payload1);
189         expSnapshotState.add(payload2);
190
191         testLog.info("testInitialReplications complete");
192     }
193
194     /**
195      * Send 5 more payloads with follower 2 lagging. Since the snapshotBatch count is 4, this should cause
196      * 2 leader snapshots and follower 2's log will be behind by 5 entries.
197      *
198      * @throws Exception
199      */
200     private void testSubsequentReplicationsAndSnapshots() throws Exception {
201         testLog.info("testSubsequentReplicationsAndSnapshots starting: sending first payload, replicatedToAllIndex: {}",
202                 leader.getReplicatedToAllIndex());
203
204         follower2Actor.underlyingActor().startDropMessages(AppendEntries.class);
205
206         // Send the first payload - this should cause the first snapshot.
207         MockPayload payload3 = sendPayloadData(leaderActor, "three");
208
209         MessageCollectorActor.expectFirstMatching(leaderCollectorActor, SaveSnapshotSuccess.class);
210
211         expSnapshotState.add(payload3);
212
213         testLog.info("testSubsequentReplicationsAndSnapshots: sending 4 more payloads");
214
215         // Send the next 4. The last one should cause the second snapshot.
216         MockPayload payload4 = sendPayloadData(leaderActor, "four");
217         MockPayload payload5 = sendPayloadData(leaderActor, "five");
218         MockPayload payload6 = sendPayloadData(leaderActor, "six");
219         MockPayload payload7 = sendPayloadData(leaderActor, "seven");
220
221         // Verify the leader got consensus and applies each log entry even though follower 2 didn't respond.
222         List<ApplyState> applyStates = MessageCollectorActor.expectMatching(leaderCollectorActor, ApplyState.class, 5);
223         verifyApplyState(applyStates.get(0), leaderCollectorActor, payload3.toString(), currentTerm, 3, payload3);
224         verifyApplyState(applyStates.get(1), leaderCollectorActor, payload4.toString(), currentTerm, 4, payload4);
225         verifyApplyState(applyStates.get(2), leaderCollectorActor, payload5.toString(), currentTerm, 5, payload5);
226         verifyApplyState(applyStates.get(3), leaderCollectorActor, payload6.toString(), currentTerm, 6, payload6);
227         verifyApplyState(applyStates.get(4), leaderCollectorActor, payload7.toString(), currentTerm, 7, payload7);
228
229         // Verify follower 1 applies each log entry.
230         applyStates = MessageCollectorActor.expectMatching(follower1CollectorActor, ApplyState.class, 5);
231         verifyApplyState(applyStates.get(0), null, null, currentTerm, 3, payload3);
232         verifyApplyState(applyStates.get(1), null, null, currentTerm, 4, payload4);
233         verifyApplyState(applyStates.get(2), null, null, currentTerm, 5, payload5);
234         verifyApplyState(applyStates.get(3), null, null, currentTerm, 6, payload6);
235         verifyApplyState(applyStates.get(4), null, null, currentTerm, 7, payload7);
236
237         // Wait for snapshot completion.
238         MessageCollectorActor.expectFirstMatching(leaderCollectorActor, SaveSnapshotSuccess.class);
239
240         // The first new entry applied should have caused the leader to advanced the snapshot index to the
241         // last previously applied index (2) that was replicated to all followers.
242         assertEquals("Leader snapshot term", currentTerm, leaderContext.getReplicatedLog().getSnapshotTerm());
243         assertEquals("Leader snapshot index", 2, leaderContext.getReplicatedLog().getSnapshotIndex());
244         assertEquals("Leader journal log size", 5, leaderContext.getReplicatedLog().size());
245         assertEquals("Leader journal last index", 7, leaderContext.getReplicatedLog().lastIndex());
246         assertEquals("Leader commit index", 7, leaderContext.getCommitIndex());
247         assertEquals("Leader last applied", 7, leaderContext.getLastApplied());
248         assertEquals("Leader replicatedToAllIndex", 2, leader.getReplicatedToAllIndex());
249
250         // Now stop dropping AppendEntries in follower 2.
251         follower2Actor.underlyingActor().stopDropMessages(AppendEntries.class);
252
253         // Verify follower 2 applies each log entry.
254         applyStates = MessageCollectorActor.expectMatching(follower2CollectorActor, ApplyState.class, 5);
255         verifyApplyState(applyStates.get(0), null, null, currentTerm, 3, payload3);
256         verifyApplyState(applyStates.get(1), null, null, currentTerm, 4, payload4);
257         verifyApplyState(applyStates.get(2), null, null, currentTerm, 5, payload5);
258         verifyApplyState(applyStates.get(3), null, null, currentTerm, 6, payload6);
259         verifyApplyState(applyStates.get(4), null, null, currentTerm, 7, payload7);
260
261         // Ensure there's at least 1 more heartbeat.
262         MessageCollectorActor.clearMessages(leaderCollectorActor);
263         MessageCollectorActor.expectFirstMatching(leaderCollectorActor, AppendEntriesReply.class);
264
265         // The leader should now have performed fake snapshots to advance the snapshot index and to trim
266         // the log. In addition replicatedToAllIndex should've advanced.
267         assertEquals("Leader snapshot term", currentTerm, leaderContext.getReplicatedLog().getSnapshotTerm());
268         assertEquals("Leader snapshot index", 6, leaderContext.getReplicatedLog().getSnapshotIndex());
269         assertEquals("Leader journal log size", 1, leaderContext.getReplicatedLog().size());
270         assertEquals("Leader journal last index", 7, leaderContext.getReplicatedLog().lastIndex());
271         assertEquals("Leader replicatedToAllIndex", 6, leader.getReplicatedToAllIndex());
272
273         // Verify the leader's persisted snapshot.
274         List<Snapshot> persistedSnapshots = InMemorySnapshotStore.getSnapshots(leaderId, Snapshot.class);
275         assertEquals("Persisted snapshots size", 1, persistedSnapshots.size());
276         verifySnapshot("Persisted", persistedSnapshots.get(0), currentTerm, 3, currentTerm, 7);
277         List<ReplicatedLogEntry> unAppliedEntry = persistedSnapshots.get(0).getUnAppliedEntries();
278         assertEquals("Persisted Snapshot getUnAppliedEntries size", 4, unAppliedEntry.size());
279         verifyReplicatedLogEntry(unAppliedEntry.get(0), currentTerm, 4, payload4);
280         verifyReplicatedLogEntry(unAppliedEntry.get(1), currentTerm, 5, payload5);
281         verifyReplicatedLogEntry(unAppliedEntry.get(2), currentTerm, 6, payload6);
282         verifyReplicatedLogEntry(unAppliedEntry.get(3), currentTerm, 7, payload7);
283
284         // Even though follower 2's log was behind by 5 entries and 2 snapshots were done, the leader
285         // should not have tried to install a snapshot to catch it up because replicatedToAllIndex was also
286         // behind. Instead of installing a snapshot the leader would've sent AppendEntries with the log entries.
287         InstallSnapshot installSnapshot = MessageCollectorActor.getFirstMatching(follower2CollectorActor, InstallSnapshot.class);
288         Assert.assertNull("Follower 2 received unexpected InstallSnapshot", installSnapshot);
289
290         // Verify follower 1's log and snapshot indexes.
291         MessageCollectorActor.clearMessages(follower1CollectorActor);
292         MessageCollectorActor.expectFirstMatching(follower1CollectorActor, AppendEntries.class);
293         assertEquals("Follower 1 snapshot term", currentTerm, follower1Context.getReplicatedLog().getSnapshotTerm());
294         assertEquals("Follower 1 snapshot index", 6, follower1Context.getReplicatedLog().getSnapshotIndex());
295         assertEquals("Follower 1 journal log size", 1, follower1Context.getReplicatedLog().size());
296         assertEquals("Follower 1 journal last index", 7, follower1Context.getReplicatedLog().lastIndex());
297         assertEquals("Follower 1 commit index", 7, follower1Context.getCommitIndex());
298         assertEquals("Follower 1 last applied", 7, follower1Context.getLastApplied());
299         assertEquals("Follower 1 replicatedToAllIndex", 6, follower1.getReplicatedToAllIndex());
300
301         // Verify follower 2's log and snapshot indexes.
302         MessageCollectorActor.clearMessages(follower2CollectorActor);
303         MessageCollectorActor.expectFirstMatching(follower2CollectorActor, AppendEntries.class);
304         assertEquals("Follower 2 snapshot term", currentTerm, follower2Context.getReplicatedLog().getSnapshotTerm());
305         assertEquals("Follower 2 snapshot index", 6, follower2Context.getReplicatedLog().getSnapshotIndex());
306         assertEquals("Follower 2 journal log size", 1, follower2Context.getReplicatedLog().size());
307         assertEquals("Follower 2 journal last index", 7, follower2Context.getReplicatedLog().lastIndex());
308         assertEquals("Follower 2 commit index", 7, follower2Context.getCommitIndex());
309         assertEquals("Follower 2 last applied", 7, follower2Context.getLastApplied());
310         assertEquals("Follower 2 replicatedToAllIndex", 6, follower2.getReplicatedToAllIndex());
311
312         MessageCollectorActor.clearMessages(leaderCollectorActor);
313         MessageCollectorActor.clearMessages(follower1CollectorActor);
314         MessageCollectorActor.clearMessages(follower2CollectorActor);
315
316         expSnapshotState.add(payload4);
317         expSnapshotState.add(payload5);
318         expSnapshotState.add(payload6);
319         expSnapshotState.add(payload7);
320
321         testLog.info("testSubsequentReplicationsAndSnapshots complete");
322     }
323
324     /**
325      * Send a couple more payloads with follower 2 lagging. The last payload will have a large enough size
326      * to trigger a leader snapshot.
327      *
328      * @throws Exception
329      */
330     private void testLeaderSnapshotTriggeredByMemoryThresholdExceeded() throws Exception {
331         testLog.info("testLeaderSnapshotTriggeredByMemoryThresholdExceeded starting: sending 3 payloads, replicatedToAllIndex: {}",
332                 leader.getReplicatedToAllIndex());
333
334         leaderActor.underlyingActor().setMockTotalMemory(1000);
335
336         // We'll expect a ReplicatedLogImplEntry message and an ApplyJournalEntries message added to the journal.
337         InMemoryJournal.addWriteMessagesCompleteLatch(leaderId, 2);
338
339         follower2Actor.underlyingActor().startDropMessages(AppendEntries.class);
340
341         // Send a payload with a large relative size but not enough to trigger a snapshot.
342         MockPayload payload8 = sendPayloadData(leaderActor, "eight", 500);
343
344         // Verify the leader got consensus and applies the first log entry even though follower 2 didn't respond.
345         List<ApplyState> applyStates = MessageCollectorActor.expectMatching(leaderCollectorActor, ApplyState.class, 1);
346         verifyApplyState(applyStates.get(0), leaderCollectorActor, payload8.toString(), currentTerm, 8, payload8);
347
348         // Wait for all the ReplicatedLogImplEntry and ApplyJournalEntries messages to be added to the journal
349         // before the snapshot so the snapshot sequence # will be higher to ensure the snapshot gets
350         // purged from the snapshot store after subsequent snapshots.
351         InMemoryJournal.waitForWriteMessagesComplete(leaderId);
352
353         // Verify a snapshot is not triggered.
354         CaptureSnapshot captureSnapshot = MessageCollectorActor.getFirstMatching(leaderCollectorActor, CaptureSnapshot.class);
355         Assert.assertNull("Leader received unexpected CaptureSnapshot", captureSnapshot);
356
357         expSnapshotState.add(payload8);
358
359         // Send another payload with a large enough relative size in combination with the last payload
360         // that exceeds the memory threshold (70% * 1000 = 700) - this should do a snapshot.
361         payload9 = sendPayloadData(leaderActor, "nine", 201);
362
363         // Verify the leader applies the last log entry.
364         applyStates = MessageCollectorActor.expectMatching(leaderCollectorActor, ApplyState.class, 2);
365         verifyApplyState(applyStates.get(1), leaderCollectorActor, payload9.toString(), currentTerm, 9, payload9);
366
367         // Verify follower 1 applies each log entry.
368         applyStates = MessageCollectorActor.expectMatching(follower1CollectorActor, ApplyState.class, 2);
369         verifyApplyState(applyStates.get(0), null, null, currentTerm, 8, payload8);
370         verifyApplyState(applyStates.get(1), null, null, currentTerm, 9, payload9);
371
372         // A snapshot should've occurred - wait for it to complete.
373         MessageCollectorActor.expectFirstMatching(leaderCollectorActor, SaveSnapshotSuccess.class);
374
375         // Because the snapshot was triggered by exceeding the memory threshold the leader should've advanced
376         // the snapshot index to the last applied index and trimmed the log even though the entries weren't
377         // replicated to all followers.
378         assertEquals("Leader snapshot term", currentTerm, leaderContext.getReplicatedLog().getSnapshotTerm());
379         assertEquals("Leader snapshot index", 8, leaderContext.getReplicatedLog().getSnapshotIndex());
380         assertEquals("Leader journal log size", 1, leaderContext.getReplicatedLog().size());
381         assertEquals("Leader journal last index", 9, leaderContext.getReplicatedLog().lastIndex());
382         assertEquals("Leader commit index", 9, leaderContext.getCommitIndex());
383         assertEquals("Leader last applied", 9, leaderContext.getLastApplied());
384         // Note: replicatedToAllIndex should not be advanced since log entries 8 and 9 haven't yet been
385         // replicated to follower 2.
386         assertEquals("Leader replicatedToAllIndex", 7, leader.getReplicatedToAllIndex());
387
388         // Verify the leader's persisted snapshot.
389         List<Snapshot> persistedSnapshots = InMemorySnapshotStore.getSnapshots(leaderId, Snapshot.class);
390         assertEquals("Persisted snapshots size", 1, persistedSnapshots.size());
391         verifySnapshot("Persisted", persistedSnapshots.get(0), currentTerm, 8, currentTerm, 9);
392         List<ReplicatedLogEntry> unAppliedEntry = persistedSnapshots.get(0).getUnAppliedEntries();
393         assertEquals("Persisted Snapshot getUnAppliedEntries size", 1, unAppliedEntry.size());
394         verifyReplicatedLogEntry(unAppliedEntry.get(0), currentTerm, 9, payload9);
395
396         testLog.info("testLeaderSnapshotTriggeredByMemoryThresholdExceeded ending");
397     }
398
399     /**
400      * Send another payload to verify another snapshot is not done since the last snapshot trimmed the
401      * first log entry so the memory threshold should not be exceeded.
402      *
403      * @throws Exception
404      */
405     private void verifyNoSubsequentSnapshotAfterMemoryThresholdExceededSnapshot() throws Exception {
406         ApplyState applyState;
407         CaptureSnapshot captureSnapshot;
408
409         MockPayload payload10 = sendPayloadData(leaderActor, "ten");
410
411         // Verify the leader applies the state.
412         applyState = MessageCollectorActor.expectFirstMatching(leaderCollectorActor, ApplyState.class);
413         verifyApplyState(applyState, leaderCollectorActor, payload10.toString(), currentTerm, 10, payload10);
414
415         captureSnapshot = MessageCollectorActor.getFirstMatching(leaderCollectorActor, CaptureSnapshot.class);
416         Assert.assertNull("Leader received unexpected CaptureSnapshot", captureSnapshot);
417
418         // Verify the follower 1 applies the state.
419         applyState = MessageCollectorActor.expectFirstMatching(follower1CollectorActor, ApplyState.class);
420         verifyApplyState(applyState, null, null, currentTerm, 10, payload10);
421
422         // Verify the follower 2 applies the state.
423         applyState = MessageCollectorActor.expectFirstMatching(follower2CollectorActor, ApplyState.class);
424         verifyApplyState(applyState, null, null, currentTerm, 10, payload10);
425
426         // Verify the leader's state.
427         assertEquals("Leader snapshot term", currentTerm, leaderContext.getReplicatedLog().getSnapshotTerm());
428         assertEquals("Leader snapshot index", 9, leaderContext.getReplicatedLog().getSnapshotIndex());
429         assertEquals("Leader journal log size", 1, leaderContext.getReplicatedLog().size());
430         assertEquals("Leader journal last index", 10, leaderContext.getReplicatedLog().lastIndex());
431         assertEquals("Leader commit index", 10, leaderContext.getCommitIndex());
432         assertEquals("Leader last applied", 10, leaderContext.getLastApplied());
433         assertEquals("Leader replicatedToAllIndex", 9, leader.getReplicatedToAllIndex());
434
435         // Verify follower 1's state.
436         assertEquals("Follower 1 snapshot term", currentTerm, follower1Context.getReplicatedLog().getSnapshotTerm());
437         assertEquals("Follower 1 snapshot index", 9, follower1Context.getReplicatedLog().getSnapshotIndex());
438         assertEquals("Follower 1 journal log size", 1, follower1Context.getReplicatedLog().size());
439         assertEquals("Follower 1 journal last index", 10, follower1Context.getReplicatedLog().lastIndex());
440         assertEquals("Follower 1 commit index", 10, follower1Context.getCommitIndex());
441         assertEquals("Follower 1 last applied", 10, follower1Context.getLastApplied());
442         assertEquals("Follower 1 replicatedToAllIndex", 9, follower1.getReplicatedToAllIndex());
443
444         // Verify follower 2's state.
445         assertEquals("Follower 2 snapshot term", currentTerm, follower2Context.getReplicatedLog().getSnapshotTerm());
446         assertEquals("Follower 2 snapshot index", 9, follower2Context.getReplicatedLog().getSnapshotIndex());
447         assertEquals("Follower 2 journal log size", 1, follower2Context.getReplicatedLog().size());
448         assertEquals("Follower 2 journal last index", 10, follower2Context.getReplicatedLog().lastIndex());
449         assertEquals("Follower 2 commit index", 10, follower2Context.getCommitIndex());
450         assertEquals("Follower 2 last applied", 10, follower2Context.getLastApplied());
451         assertEquals("Follower 2 replicatedToAllIndex", 9, follower2.getReplicatedToAllIndex());
452
453         // Revert back to JVM total memory.
454         leaderActor.underlyingActor().setMockTotalMemory(0);
455
456         MessageCollectorActor.clearMessages(leaderCollectorActor);
457         MessageCollectorActor.clearMessages(follower1CollectorActor);
458         MessageCollectorActor.clearMessages(follower2CollectorActor);
459
460         expSnapshotState.add(payload10);
461     }
462
463     /**
464      * Following a snapshot due memory threshold exceeded, resume the lagging follower and verify it receives
465      * an install snapshot from the leader.
466      *
467      * @throws Exception
468      */
469     private void testInstallSnapshotToLaggingFollower() throws Exception {
470         List<Snapshot> persistedSnapshots;
471         List<ReplicatedLogEntry> unAppliedEntry;
472         ApplyState applyState;
473         ApplySnapshot applySnapshot;
474         InstallSnapshot installSnapshot;
475         InstallSnapshotReply installSnapshotReply;
476
477         expSnapshotState.add(payload9);
478
479         // Now stop dropping AppendEntries in follower 2.
480         follower2Actor.underlyingActor().stopDropMessages(AppendEntries.class);
481
482         installSnapshot = MessageCollectorActor.expectFirstMatching(follower2CollectorActor, InstallSnapshot.class);
483         assertEquals("InstallSnapshot getTerm", currentTerm, installSnapshot.getTerm());
484         assertEquals("InstallSnapshot getLeaderId", leaderId, installSnapshot.getLeaderId());
485         assertEquals("InstallSnapshot getChunkIndex", 1, installSnapshot.getChunkIndex());
486         assertEquals("InstallSnapshot getTotalChunks", 1, installSnapshot.getTotalChunks());
487         assertEquals("InstallSnapshot getLastIncludedTerm", currentTerm, installSnapshot.getLastIncludedTerm());
488         assertEquals("InstallSnapshot getLastIncludedIndex", 9, installSnapshot.getLastIncludedIndex());
489         //assertArrayEquals("InstallSnapshot getData", snapshot, installSnapshot.getData().toByteArray());
490
491         installSnapshotReply = MessageCollectorActor.expectFirstMatching(leaderCollectorActor, InstallSnapshotReply.class);
492         assertEquals("InstallSnapshotReply getTerm", currentTerm, installSnapshotReply.getTerm());
493         assertEquals("InstallSnapshotReply getChunkIndex", 1, installSnapshotReply.getChunkIndex());
494         assertEquals("InstallSnapshotReply getFollowerId", follower2Id, installSnapshotReply.getFollowerId());
495         assertEquals("InstallSnapshotReply isSuccess", true, installSnapshotReply.isSuccess());
496
497         // Verify follower 2 applies the snapshot.
498         applySnapshot = MessageCollectorActor.expectFirstMatching(follower2CollectorActor, ApplySnapshot.class);
499         verifySnapshot("Follower 2", applySnapshot.getSnapshot(), currentTerm, 9, currentTerm, 9);
500         assertEquals("Persisted Snapshot getUnAppliedEntries size", 0, applySnapshot.getSnapshot().getUnAppliedEntries().size());
501
502         // Wait for the snapshot to complete.
503         MessageCollectorActor.expectFirstMatching(leaderCollectorActor, SaveSnapshotSuccess.class);
504
505         // Ensure there's at least 1 more heartbeat.
506         MessageCollectorActor.clearMessages(leaderCollectorActor);
507         MessageCollectorActor.expectFirstMatching(leaderCollectorActor, AppendEntriesReply.class);
508
509         // The leader should now have performed fake snapshots to advance the snapshot index and to trim
510         // the log. In addition replicatedToAllIndex should've advanced.
511         assertEquals("Leader snapshot term", currentTerm, leaderContext.getReplicatedLog().getSnapshotTerm());
512         assertEquals("Leader snapshot index", 8, leaderContext.getReplicatedLog().getSnapshotIndex());
513         assertEquals("Leader journal log size", 1, leaderContext.getReplicatedLog().size());
514         assertEquals("Leader commit index", 9, leaderContext.getCommitIndex());
515         assertEquals("Leader last applied", 9, leaderContext.getLastApplied());
516         assertEquals("Leader replicatedToAllIndex", 8, leader.getReplicatedToAllIndex());
517
518         // Verify the leader's persisted snapshot. The previous snapshot (currently) won't be deleted from
519         // the snapshot store because the second snapshot was initiated by the follower install snapshot and
520         // not because the batch count was reached so the persisted journal sequence number wasn't advanced
521         // far enough to cause the previous snapshot to be deleted. This is because
522         // RaftActor#trimPersistentData subtracts the snapshotBatchCount from the snapshot's sequence number.
523         // This is OK - the next snapshot should delete it. In production, even if the system restarted
524         // before another snapshot, they would both get applied which wouldn't hurt anything.
525         persistedSnapshots = InMemorySnapshotStore.getSnapshots(leaderId, Snapshot.class);
526         Assert.assertTrue("Expected at least 1 persisted snapshots", persistedSnapshots.size() > 0);
527         Snapshot persistedSnapshot = persistedSnapshots.get(persistedSnapshots.size() - 1);
528         verifySnapshot("Persisted", persistedSnapshot, currentTerm, 9, currentTerm, 9);
529         unAppliedEntry = persistedSnapshot.getUnAppliedEntries();
530         assertEquals("Persisted Snapshot getUnAppliedEntries size", 0, unAppliedEntry.size());
531
532         MessageCollectorActor.clearMessages(leaderCollectorActor);
533         MessageCollectorActor.clearMessages(follower1CollectorActor);
534         MessageCollectorActor.clearMessages(follower2CollectorActor);
535     }
536
537     /**
538      * Do another round of payloads and snapshot to verify replicatedToAllIndex gets back on track and
539      * snapshots works as expected after doing a follower snapshot. In this step we don't lag a follower.
540      * @throws Exception
541      */
542     private void testFinalReplicationsAndSnapshot() throws Exception {
543         List<ApplyState> applyStates;
544         ApplyState applyState;
545
546         testLog.info("testFinalReplicationsAndSnapshot starting: replicatedToAllIndex: {}", leader.getReplicatedToAllIndex());
547
548         // Send another payload - a snapshot should occur.
549         payload11 = sendPayloadData(leaderActor, "eleven");
550
551         // Wait for the snapshot to complete.
552         MessageCollectorActor.expectFirstMatching(leaderCollectorActor, SaveSnapshotSuccess.class);
553
554         applyState = MessageCollectorActor.expectFirstMatching(leaderCollectorActor, ApplyState.class);
555         verifyApplyState(applyState, leaderCollectorActor, payload11.toString(), currentTerm, 11, payload11);
556
557         // Verify the leader's last persisted snapshot (previous ones may not be purged yet).
558         List<Snapshot> persistedSnapshots = InMemorySnapshotStore.getSnapshots(leaderId, Snapshot.class);
559         Snapshot persistedSnapshot = persistedSnapshots.get(persistedSnapshots.size() - 1);
560         verifySnapshot("Persisted", persistedSnapshot, currentTerm, 10, currentTerm, 11);
561         List<ReplicatedLogEntry> unAppliedEntry = persistedSnapshot.getUnAppliedEntries();
562         assertEquals("Persisted Snapshot getUnAppliedEntries size", 1, unAppliedEntry.size());
563         verifyReplicatedLogEntry(unAppliedEntry.get(0), currentTerm, 11, payload11);
564
565         // Send a couple more payloads.
566         payload12 = sendPayloadData(leaderActor, "twelve");
567         payload13 = sendPayloadData(leaderActor, "thirteen");
568
569         // Verify the leader applies the 2 log entries.
570         applyStates = MessageCollectorActor.expectMatching(leaderCollectorActor, ApplyState.class, 3);
571         verifyApplyState(applyStates.get(1), leaderCollectorActor, payload12.toString(), currentTerm, 12, payload12);
572         verifyApplyState(applyStates.get(2), leaderCollectorActor, payload13.toString(), currentTerm, 13, payload13);
573
574         // Verify the leader applies a log entry for at least the last entry index.
575         verifyApplyJournalEntries(leaderCollectorActor, 13);
576
577         // Ensure there's at least 1 more heartbeat to trim the log.
578         MessageCollectorActor.clearMessages(leaderCollectorActor);
579         MessageCollectorActor.expectFirstMatching(leaderCollectorActor, AppendEntriesReply.class);
580
581         // Verify the leader's final snapshot index et al.
582         assertEquals("Leader snapshot term", currentTerm, leaderContext.getReplicatedLog().getSnapshotTerm());
583         assertEquals("Leader snapshot index", 12, leaderContext.getReplicatedLog().getSnapshotIndex());
584         assertEquals("Leader journal log size", 1, leaderContext.getReplicatedLog().size());
585         assertEquals("Leader journal last index", 13, leaderContext.getReplicatedLog().lastIndex());
586         assertEquals("Leader commit index", 13, leaderContext.getCommitIndex());
587         assertEquals("Leader last applied", 13, leaderContext.getLastApplied());
588         assertEquals("Leader replicatedToAllIndex", 12, leader.getReplicatedToAllIndex());
589
590         InMemoryJournal.dumpJournal(leaderId);
591
592         // Verify the leaders's persisted journal log - should only contain the last 2 ReplicatedLogEntries
593         // added after the snapshot as the persisted journal should've been purged to the snapshot
594         // sequence number.
595         verifyPersistedJournal(leaderId, Arrays.asList(new ReplicatedLogImplEntry(12, currentTerm, payload12),
596                 new ReplicatedLogImplEntry(13, currentTerm, payload13)));
597
598         // Verify the leaders's persisted journal contains an ApplyJournalEntries for at least the last entry index.
599         List<ApplyJournalEntries> persistedApplyJournalEntries = InMemoryJournal.get(leaderId, ApplyJournalEntries.class);
600         boolean found = false;
601         for(ApplyJournalEntries entry: persistedApplyJournalEntries) {
602             if(entry.getToIndex() == 13) {
603                 found = true;
604                 break;
605             }
606         }
607
608         Assert.assertTrue(String.format("ApplyJournalEntries with index %d not found in leader's persisted journal", 13), found);
609
610         // Verify follower 1 applies the 2 log entries.
611         applyStates = MessageCollectorActor.expectMatching(follower1CollectorActor, ApplyState.class, 3);
612         verifyApplyState(applyStates.get(0), null, null, currentTerm, 11, payload11);
613         verifyApplyState(applyStates.get(1), null, null, currentTerm, 12, payload12);
614         verifyApplyState(applyStates.get(2), null, null, currentTerm, 13, payload13);
615
616         // Verify follower 1's log state.
617         assertEquals("Follower 1 snapshot term", currentTerm, follower1Context.getReplicatedLog().getSnapshotTerm());
618         assertEquals("Follower 1 snapshot index", 12, follower1Context.getReplicatedLog().getSnapshotIndex());
619         assertEquals("Follower 1 journal log size", 1, follower1Context.getReplicatedLog().size());
620         assertEquals("Follower 1 journal last index", 13, follower1Context.getReplicatedLog().lastIndex());
621         assertEquals("Follower 1 commit index", 13, follower1Context.getCommitIndex());
622         assertEquals("Follower 1 last applied", 13, follower1Context.getLastApplied());
623         assertEquals("Follower 1 replicatedToAllIndex", 12, follower1.getReplicatedToAllIndex());
624
625         // Verify follower 2 applies the 2 log entries.
626         applyStates = MessageCollectorActor.expectMatching(follower2CollectorActor, ApplyState.class, 3);
627         verifyApplyState(applyStates.get(0), null, null, currentTerm, 11, payload11);
628         verifyApplyState(applyStates.get(1), null, null, currentTerm, 12, payload12);
629         verifyApplyState(applyStates.get(2), null, null, currentTerm, 13, payload13);
630
631         // Verify follower 2's log state.
632         assertEquals("Follower 2 snapshot term", currentTerm, follower2Context.getReplicatedLog().getSnapshotTerm());
633         assertEquals("Follower 2 snapshot index", 12, follower2Context.getReplicatedLog().getSnapshotIndex());
634         assertEquals("Follower 2 journal log size", 1, follower2Context.getReplicatedLog().size());
635         assertEquals("Follower 2 journal last index", 13, follower2Context.getReplicatedLog().lastIndex());
636         assertEquals("Follower 2 commit index", 13, follower2Context.getCommitIndex());
637         assertEquals("Follower 2 last applied", 13, follower2Context.getLastApplied());
638         assertEquals("Follower 2 replicatedToAllIndex", 12, follower2.getReplicatedToAllIndex());
639
640         testLog.info("testFinalReplicationsAndSnapshot ending");
641     }
642
643     /**
644      * Kill the leader actor, reinstate it and verify the recovered journal.
645      */
646     private void testLeaderReinstatement() {
647         testLog.info("testLeaderReinstatement starting");
648
649         killActor(leaderActor);
650
651         leaderActor = newTestRaftActor(leaderId, peerAddresses, leaderConfigParams);
652
653         leaderActor.underlyingActor().startDropMessages(RequestVoteReply.class);
654
655         leaderContext = leaderActor.underlyingActor().getRaftActorContext();
656
657         leaderActor.underlyingActor().waitForRecoveryComplete();
658
659         assertEquals("Leader snapshot term", currentTerm, leaderContext.getReplicatedLog().getSnapshotTerm());
660         assertEquals("Leader snapshot index", 10, leaderContext.getReplicatedLog().getSnapshotIndex());
661         assertEquals("Leader journal log size", 3, leaderContext.getReplicatedLog().size());
662         assertEquals("Leader journal last index", 13, leaderContext.getReplicatedLog().lastIndex());
663         assertEquals("Leader commit index", 13, leaderContext.getCommitIndex());
664         assertEquals("Leader last applied", 13, leaderContext.getLastApplied());
665         verifyReplicatedLogEntry(leaderContext.getReplicatedLog().get(11), currentTerm, 11, payload11);
666         verifyReplicatedLogEntry(leaderContext.getReplicatedLog().get(12), currentTerm, 12, payload12);
667         verifyReplicatedLogEntry(leaderContext.getReplicatedLog().get(13), currentTerm, 13, payload13);
668
669         testLog.info("testLeaderReinstatement ending");
670     }
671 }

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