Add RaftActor integration tests
[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.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;
16 import java.util.Map;
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;
33
34 /**
35  * Tests replication and snapshots end-to-end using real RaftActors and behavior communication with a
36  * lagging follower.
37  *
38  * @author Thomas Pantelis
39  */
40 public class ReplicationAndSnapshotsWithLaggingFollowerIntegrationTest extends AbstractRaftActorIntegrationTest {
41
42     private MockPayload payload9;
43     private MockPayload payload11;
44     private MockPayload payload12;
45     private MockPayload payload13;
46
47     @Test
48     public void runTest() throws Exception {
49         testLog.info("testReplicationAndSnapshotsWithLaggingFollower starting");
50
51         leaderId = factory.generateActorId("leader");
52         follower1Id = factory.generateActorId("follower");
53         follower2Id = factory.generateActorId("follower");
54
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));
57
58         // Create the leader and 2 follower actors.
59
60         follower1Actor = newTestRaftActor(follower1Id, null, newFollowerConfigParams());
61
62         follower2Actor = newTestRaftActor(follower2Id, null, 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         testLog.info("testInitialReplications complete");
188     }
189
190     /**
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.
193      *
194      * @throws Exception
195      */
196     private void testSubsequentReplicationsAndSnapshots() throws Exception {
197         testLog.info("testSubsequentReplicationsAndSnapshots starting: sending first payload, replicatedToAllIndex: {}",
198                 leader.getReplicatedToAllIndex());
199
200         leaderActor.underlyingActor().setSnapshot(new byte[] {2});
201
202         follower2Actor.underlyingActor().startDropMessages(AppendEntries.class);
203
204         // Send the first payload - this should cause the first snapshot.
205         MockPayload payload3 = sendPayloadData(leaderActor, "three");
206
207         MessageCollectorActor.expectFirstMatching(leaderCollectorActor, SaveSnapshotSuccess.class);
208
209         byte[] snapshot = new byte[] {6};
210         leaderActor.underlyingActor().setSnapshot(snapshot);
211
212         testLog.info("testSubsequentReplicationsAndSnapshots: sending 4 more payloads");
213
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");
219
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);
227
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);
235
236         // Wait for snapshot completion.
237         MessageCollectorActor.expectFirstMatching(leaderCollectorActor, SaveSnapshotSuccess.class);
238
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());
248
249         // Now stop dropping AppendEntries in follower 2.
250         follower2Actor.underlyingActor().stopDropMessages(AppendEntries.class);
251
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);
259
260         // Ensure there's at least 1 more heartbeat.
261         MessageCollectorActor.clearMessages(leaderCollectorActor);
262         MessageCollectorActor.expectFirstMatching(leaderCollectorActor, AppendEntriesReply.class);
263
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());
271
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);
282
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);
288
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());
299
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());
310
311         MessageCollectorActor.clearMessages(leaderCollectorActor);
312         MessageCollectorActor.clearMessages(follower1CollectorActor);
313         MessageCollectorActor.clearMessages(follower2CollectorActor);
314
315         testLog.info("testSubsequentReplicationsAndSnapshots complete");
316     }
317
318     /**
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.
321      *
322      * @throws Exception
323      */
324     private void testLeaderSnapshotTriggeredByMemoryThresholdExceeded() throws Exception {
325         testLog.info("testLeaderSnapshotTriggeredByMemoryThresholdExceeded starting: sending 3 payloads, replicatedToAllIndex: {}",
326                 leader.getReplicatedToAllIndex());
327
328         leaderActor.underlyingActor().setMockTotalMemory(1000);
329         byte[] snapshot = new byte[] {6};
330         leaderActor.underlyingActor().setSnapshot(snapshot);
331
332         // We'll expect a ReplicatedLogImplEntry message and an ApplyJournalEntries message added to the journal.
333         InMemoryJournal.addWriteMessagesCompleteLatch(leaderId, 2);
334
335         follower2Actor.underlyingActor().startDropMessages(AppendEntries.class);
336
337         // Send a payload with a large relative size but not enough to trigger a snapshot.
338         MockPayload payload8 = sendPayloadData(leaderActor, "eight", 500);
339
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);
343
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);
348
349         // Verify a snapshot is not triggered.
350         CaptureSnapshot captureSnapshot = MessageCollectorActor.getFirstMatching(leaderCollectorActor, CaptureSnapshot.class);
351         Assert.assertNull("Leader received unexpected CaptureSnapshot", captureSnapshot);
352
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);
356
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);
360
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);
365
366         // A snapshot should've occurred - wait for it to complete.
367         MessageCollectorActor.expectFirstMatching(leaderCollectorActor, SaveSnapshotSuccess.class);
368
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());
381
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);
389
390         testLog.info("testLeaderSnapshotTriggeredByMemoryThresholdExceeded ending");
391     }
392
393     /**
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.
396      *
397      * @throws Exception
398      */
399     private void verifyNoSubsequentSnapshotAfterMemoryThresholdExceededSnapshot() throws Exception {
400         ApplyState applyState;
401         CaptureSnapshot captureSnapshot;
402
403         MockPayload payload10 = sendPayloadData(leaderActor, "ten");
404
405         // Verify the leader applies the state.
406         applyState = MessageCollectorActor.expectFirstMatching(leaderCollectorActor, ApplyState.class);
407         verifyApplyState(applyState, leaderCollectorActor, payload10.toString(), currentTerm, 10, payload10);
408
409         captureSnapshot = MessageCollectorActor.getFirstMatching(leaderCollectorActor, CaptureSnapshot.class);
410         Assert.assertNull("Leader received unexpected CaptureSnapshot", captureSnapshot);
411
412         // Verify the follower 1 applies the state.
413         applyState = MessageCollectorActor.expectFirstMatching(follower1CollectorActor, ApplyState.class);
414         verifyApplyState(applyState, null, null, currentTerm, 10, payload10);
415
416         // Verify the follower 2 applies the state.
417         applyState = MessageCollectorActor.expectFirstMatching(follower2CollectorActor, ApplyState.class);
418         verifyApplyState(applyState, null, null, currentTerm, 10, payload10);
419
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());
428
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());
437
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());
446
447         // Revert back to JVM total memory.
448         leaderActor.underlyingActor().setMockTotalMemory(0);
449
450         MessageCollectorActor.clearMessages(leaderCollectorActor);
451         MessageCollectorActor.clearMessages(follower1CollectorActor);
452         MessageCollectorActor.clearMessages(follower2CollectorActor);
453     }
454
455     /**
456      * Following a snapshot due memory threshold exceeded, resume the lagging follower and verify it receives
457      * an install snapshot from the leader.
458      *
459      * @throws Exception
460      */
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;
468
469         byte[] snapshot = new byte[] {10};
470         leaderActor.underlyingActor().setSnapshot(snapshot);
471
472         // Now stop dropping AppendEntries in follower 2.
473         follower2Actor.underlyingActor().stopDropMessages(AppendEntries.class);
474
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());
483
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());
489
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());
494
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);
498
499         // Wait for the snapshot to complete.
500         MessageCollectorActor.expectFirstMatching(leaderCollectorActor, SaveSnapshotSuccess.class);
501
502         // Ensure there's at least 1 more heartbeat.
503         MessageCollectorActor.clearMessages(leaderCollectorActor);
504         MessageCollectorActor.expectFirstMatching(leaderCollectorActor, AppendEntriesReply.class);
505
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());
514
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());
528
529         MessageCollectorActor.clearMessages(leaderCollectorActor);
530         MessageCollectorActor.clearMessages(follower1CollectorActor);
531         MessageCollectorActor.clearMessages(follower2CollectorActor);
532     }
533
534     /**
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.
537      */
538     private void testFinalReplicationsAndSnapshot() {
539         List<ApplyState> applyStates;
540         ApplyState applyState;
541
542         testLog.info("testFinalReplicationsAndSnapshot starting: replicatedToAllIndex: {}", leader.getReplicatedToAllIndex());
543
544         byte[] snapshot = new byte[] {14};
545         leaderActor.underlyingActor().setSnapshot(snapshot);
546
547         // Send another payload - a snapshot should occur.
548         payload11 = sendPayloadData(leaderActor, "eleven");
549
550         // Wait for the snapshot to complete.
551         MessageCollectorActor.expectFirstMatching(leaderCollectorActor, SaveSnapshotSuccess.class);
552
553         applyState = MessageCollectorActor.expectFirstMatching(leaderCollectorActor, ApplyState.class);
554         verifyApplyState(applyState, leaderCollectorActor, payload11.toString(), currentTerm, 11, payload11);
555
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);
563
564         // Send a couple more payloads.
565         payload12 = sendPayloadData(leaderActor, "twelve");
566         payload13 = sendPayloadData(leaderActor, "thirteen");
567
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);
572
573         // Verify the leader applies a log entry for at least the last entry index.
574         verifyApplyJournalEntries(leaderCollectorActor, 13);
575
576         // Ensure there's at least 1 more heartbeat to trim the log.
577         MessageCollectorActor.clearMessages(leaderCollectorActor);
578         MessageCollectorActor.expectFirstMatching(leaderCollectorActor, AppendEntriesReply.class);
579
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());
588
589         InMemoryJournal.dumpJournal(leaderId);
590
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
593         // sequence number.
594         verifyPersistedJournal(leaderId, Arrays.asList(new ReplicatedLogImplEntry(12, currentTerm, payload12),
595                 new ReplicatedLogImplEntry(13, currentTerm, payload13)));
596
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) {
602                 found = true;
603                 break;
604             }
605         }
606
607         Assert.assertTrue(String.format("ApplyJournalEntries with index %d not found in leader's persisted journal", 13), found);
608
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);
614
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());
623
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);
629
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());
638
639         testLog.info("testFinalReplicationsAndSnapshot ending");
640     }
641
642     /**
643      * Kill the leader actor, reinstate it and verify the recovered journal.
644      */
645     private void testLeaderReinstatement() {
646         testLog.info("testLeaderReinstatement starting");
647
648         killActor(leaderActor);
649
650         leaderActor = newTestRaftActor(leaderId, peerAddresses, leaderConfigParams);
651
652         leaderActor.underlyingActor().startDropMessages(RequestVoteReply.class);
653
654         leaderContext = leaderActor.underlyingActor().getRaftActorContext();
655
656         leaderActor.underlyingActor().waitForRecoveryComplete();
657
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);
667
668         testLog.info("testLeaderReinstatement ending");
669     }
670 }

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