44dffe352c9816be8bce1e9a497afac1a7e8f603
[controller.git] / opendaylight / md-sal / sal-akka-raft / src / test / java / org / opendaylight / controller / cluster / raft / RaftActorTest.java
1 package org.opendaylight.controller.cluster.raft;
2
3 import static org.junit.Assert.assertEquals;
4 import static org.junit.Assert.assertFalse;
5 import static org.junit.Assert.assertNotNull;
6 import static org.junit.Assert.assertNull;
7 import static org.mockito.Matchers.any;
8 import static org.mockito.Matchers.anyObject;
9 import static org.mockito.Matchers.eq;
10 import static org.mockito.Matchers.same;
11 import static org.mockito.Mockito.doReturn;
12 import static org.mockito.Mockito.mock;
13 import static org.mockito.Mockito.times;
14 import static org.mockito.Mockito.verify;
15 import akka.actor.ActorRef;
16 import akka.actor.PoisonPill;
17 import akka.actor.Props;
18 import akka.actor.Terminated;
19 import akka.japi.Procedure;
20 import akka.persistence.SaveSnapshotFailure;
21 import akka.persistence.SaveSnapshotSuccess;
22 import akka.persistence.SnapshotMetadata;
23 import akka.persistence.SnapshotOffer;
24 import akka.testkit.JavaTestKit;
25 import akka.testkit.TestActorRef;
26 import com.google.common.base.Optional;
27 import com.google.common.collect.ImmutableMap;
28 import com.google.common.util.concurrent.Uninterruptibles;
29 import com.google.protobuf.ByteString;
30 import java.io.ByteArrayOutputStream;
31 import java.io.ObjectOutputStream;
32 import java.util.ArrayList;
33 import java.util.Arrays;
34 import java.util.Collections;
35 import java.util.HashMap;
36 import java.util.List;
37 import java.util.Map;
38 import java.util.concurrent.CountDownLatch;
39 import java.util.concurrent.TimeUnit;
40 import org.junit.After;
41 import org.junit.Before;
42 import org.junit.Test;
43 import org.opendaylight.controller.cluster.DataPersistenceProvider;
44 import org.opendaylight.controller.cluster.NonPersistentDataProvider;
45 import org.opendaylight.controller.cluster.datastore.DataPersistenceProviderMonitor;
46 import org.opendaylight.controller.cluster.notifications.LeaderStateChanged;
47 import org.opendaylight.controller.cluster.notifications.RoleChanged;
48 import org.opendaylight.controller.cluster.raft.RaftActor.DeleteEntries;
49 import org.opendaylight.controller.cluster.raft.RaftActor.UpdateElectionTerm;
50 import org.opendaylight.controller.cluster.raft.base.messages.ApplyJournalEntries;
51 import org.opendaylight.controller.cluster.raft.base.messages.ApplyLogEntries;
52 import org.opendaylight.controller.cluster.raft.base.messages.ApplySnapshot;
53 import org.opendaylight.controller.cluster.raft.base.messages.ApplyState;
54 import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshot;
55 import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshotReply;
56 import org.opendaylight.controller.cluster.raft.base.messages.SendHeartBeat;
57 import org.opendaylight.controller.cluster.raft.behaviors.Follower;
58 import org.opendaylight.controller.cluster.raft.behaviors.Leader;
59 import org.opendaylight.controller.cluster.raft.behaviors.RaftActorBehavior;
60 import org.opendaylight.controller.cluster.raft.messages.AppendEntries;
61 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
62 import org.opendaylight.controller.cluster.raft.utils.InMemoryJournal;
63 import org.opendaylight.controller.cluster.raft.utils.InMemorySnapshotStore;
64 import org.opendaylight.controller.cluster.raft.utils.MessageCollectorActor;
65 import scala.concurrent.duration.FiniteDuration;
66
67 public class RaftActorTest extends AbstractActorTest {
68
69     private TestActorFactory factory;
70
71     @Before
72     public void setUp(){
73         factory = new TestActorFactory(getSystem());
74     }
75
76     @After
77     public void tearDown() throws Exception {
78         factory.close();
79         InMemoryJournal.clear();
80         InMemorySnapshotStore.clear();
81     }
82
83     @Test
84     public void testConstruction() {
85         new RaftActorTestKit(getSystem(), "testConstruction").waitUntilLeader();
86     }
87
88     @Test
89     public void testFindLeaderWhenLeaderIsSelf(){
90         RaftActorTestKit kit = new RaftActorTestKit(getSystem(), "testFindLeader");
91         kit.waitUntilLeader();
92     }
93
94     @Test
95     public void testRaftActorRecoveryWithPersistenceEnabled() throws Exception {
96         new JavaTestKit(getSystem()) {{
97             String persistenceId = factory.generateActorId("follower-");
98
99             DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
100
101             // Set the heartbeat interval high to essentially disable election otherwise the test
102             // may fail if the actor is switched to Leader and the commitIndex is set to the last
103             // log entry.
104             config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
105
106             ActorRef followerActor = factory.createActor(MockRaftActor.props(persistenceId,
107                     ImmutableMap.<String, String>builder().put("member1", "address").build(),
108                     Optional.<ConfigParams>of(config)), persistenceId);
109
110             watch(followerActor);
111
112             List<ReplicatedLogEntry> snapshotUnappliedEntries = new ArrayList<>();
113             ReplicatedLogEntry entry1 = new MockRaftActorContext.MockReplicatedLogEntry(1, 4,
114                     new MockRaftActorContext.MockPayload("E"));
115             snapshotUnappliedEntries.add(entry1);
116
117             int lastAppliedDuringSnapshotCapture = 3;
118             int lastIndexDuringSnapshotCapture = 4;
119
120             // 4 messages as part of snapshot, which are applied to state
121             ByteString snapshotBytes = fromObject(Arrays.asList(
122                     new MockRaftActorContext.MockPayload("A"),
123                     new MockRaftActorContext.MockPayload("B"),
124                     new MockRaftActorContext.MockPayload("C"),
125                     new MockRaftActorContext.MockPayload("D")));
126
127             Snapshot snapshot = Snapshot.create(snapshotBytes.toByteArray(),
128                     snapshotUnappliedEntries, lastIndexDuringSnapshotCapture, 1,
129                     lastAppliedDuringSnapshotCapture, 1);
130             InMemorySnapshotStore.addSnapshot(persistenceId, snapshot);
131
132             // add more entries after snapshot is taken
133             List<ReplicatedLogEntry> entries = new ArrayList<>();
134             ReplicatedLogEntry entry2 = new MockRaftActorContext.MockReplicatedLogEntry(1, 5,
135                     new MockRaftActorContext.MockPayload("F", 2));
136             ReplicatedLogEntry entry3 = new MockRaftActorContext.MockReplicatedLogEntry(1, 6,
137                     new MockRaftActorContext.MockPayload("G", 3));
138             ReplicatedLogEntry entry4 = new MockRaftActorContext.MockReplicatedLogEntry(1, 7,
139                     new MockRaftActorContext.MockPayload("H", 4));
140             entries.add(entry2);
141             entries.add(entry3);
142             entries.add(entry4);
143
144             int lastAppliedToState = 5;
145             int lastIndex = 7;
146
147             InMemoryJournal.addEntry(persistenceId, 5, entry2);
148             // 2 entries are applied to state besides the 4 entries in snapshot
149             InMemoryJournal.addEntry(persistenceId, 6, new ApplyJournalEntries(lastAppliedToState));
150             InMemoryJournal.addEntry(persistenceId, 7, entry3);
151             InMemoryJournal.addEntry(persistenceId, 8, entry4);
152
153             // kill the actor
154             followerActor.tell(PoisonPill.getInstance(), null);
155             expectMsgClass(duration("5 seconds"), Terminated.class);
156
157             unwatch(followerActor);
158
159             //reinstate the actor
160             TestActorRef<MockRaftActor> ref = factory.createTestActor(
161                     MockRaftActor.props(persistenceId, Collections.<String, String>emptyMap(),
162                             Optional.<ConfigParams>of(config)));
163
164             MockRaftActor mockRaftActor = ref.underlyingActor();
165
166             mockRaftActor.waitForRecoveryComplete();
167
168             RaftActorContext context = mockRaftActor.getRaftActorContext();
169             assertEquals("Journal log size", snapshotUnappliedEntries.size() + entries.size(),
170                     context.getReplicatedLog().size());
171             assertEquals("Journal data size", 10, context.getReplicatedLog().dataSize());
172             assertEquals("Last index", lastIndex, context.getReplicatedLog().lastIndex());
173             assertEquals("Last applied", lastAppliedToState, context.getLastApplied());
174             assertEquals("Commit index", lastAppliedToState, context.getCommitIndex());
175             assertEquals("Recovered state size", 6, mockRaftActor.getState().size());
176
177             mockRaftActor.waitForInitializeBehaviorComplete();
178
179             assertEquals("getRaftState", RaftState.Follower, mockRaftActor.getRaftState());
180         }};
181     }
182
183     @Test
184     public void testRaftActorRecoveryWithPersistenceDisabled() throws Exception {
185         new JavaTestKit(getSystem()) {{
186             String persistenceId = factory.generateActorId("follower-");
187
188             DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
189
190             config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
191
192             TestActorRef<MockRaftActor> ref = factory.createTestActor(MockRaftActor.props(persistenceId,
193                     ImmutableMap.<String, String>builder().put("member1", "address").build(),
194                     Optional.<ConfigParams>of(config), new NonPersistentDataProvider()), persistenceId);
195
196             MockRaftActor mockRaftActor = ref.underlyingActor();
197
198             mockRaftActor.waitForRecoveryComplete();
199
200             mockRaftActor.waitForInitializeBehaviorComplete();
201
202             assertEquals("getRaftState", RaftState.Follower, mockRaftActor.getRaftState());
203         }};
204     }
205
206     @Test
207     public void testRaftActorForwardsToRaftActorRecoverySupport() {
208         String persistenceId = factory.generateActorId("leader-");
209
210         DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
211
212         config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
213
214         TestActorRef<MockRaftActor> mockActorRef = factory.createTestActor(MockRaftActor.props(persistenceId,
215                 Collections.<String, String>emptyMap(), Optional.<ConfigParams>of(config)), persistenceId);
216
217         MockRaftActor mockRaftActor = mockActorRef.underlyingActor();
218
219         // Wait for akka's recovery to complete so it doesn't interfere.
220         mockRaftActor.waitForRecoveryComplete();
221
222         RaftActorRecoverySupport mockSupport = mock(RaftActorRecoverySupport.class);
223         mockRaftActor.setRaftActorRecoverySupport(mockSupport );
224
225         Snapshot snapshot = Snapshot.create(new byte[]{1}, Collections.<ReplicatedLogEntry>emptyList(), 3, 1, 3, 1);
226         SnapshotOffer snapshotOffer = new SnapshotOffer(new SnapshotMetadata("test", 6, 12345), snapshot);
227         mockRaftActor.handleRecover(snapshotOffer);
228
229         MockRaftActorContext.MockReplicatedLogEntry logEntry = new MockRaftActorContext.MockReplicatedLogEntry(1,
230                 1, new MockRaftActorContext.MockPayload("1", 5));
231         mockRaftActor.handleRecover(logEntry);
232
233         ApplyJournalEntries applyJournalEntries = new ApplyJournalEntries(2);
234         mockRaftActor.handleRecover(applyJournalEntries);
235
236         ApplyLogEntries applyLogEntries = new ApplyLogEntries(0);
237         mockRaftActor.handleRecover(applyLogEntries);
238
239         DeleteEntries deleteEntries = new DeleteEntries(1);
240         mockRaftActor.handleRecover(deleteEntries);
241
242         UpdateElectionTerm updateElectionTerm = new UpdateElectionTerm(5, "member2");
243         mockRaftActor.handleRecover(updateElectionTerm);
244
245         verify(mockSupport).handleRecoveryMessage(same(snapshotOffer));
246         verify(mockSupport).handleRecoveryMessage(same(logEntry));
247         verify(mockSupport).handleRecoveryMessage(same(applyJournalEntries));
248         verify(mockSupport).handleRecoveryMessage(same(applyLogEntries));
249         verify(mockSupport).handleRecoveryMessage(same(deleteEntries));
250         verify(mockSupport).handleRecoveryMessage(same(updateElectionTerm));
251     }
252
253     @Test
254     public void testRaftActorForwardsToRaftActorSnapshotMessageSupport() {
255         String persistenceId = factory.generateActorId("leader-");
256
257         DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
258
259         config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
260
261         RaftActorSnapshotMessageSupport mockSupport = mock(RaftActorSnapshotMessageSupport.class);
262
263         TestActorRef<MockRaftActor> mockActorRef = factory.createTestActor(MockRaftActor.props(persistenceId,
264                 Collections.<String, String>emptyMap(), Optional.<ConfigParams>of(config), mockSupport), persistenceId);
265
266         MockRaftActor mockRaftActor = mockActorRef.underlyingActor();
267
268         // Wait for akka's recovery to complete so it doesn't interfere.
269         mockRaftActor.waitForRecoveryComplete();
270
271         ApplySnapshot applySnapshot = new ApplySnapshot(mock(Snapshot.class));
272         doReturn(true).when(mockSupport).handleSnapshotMessage(same(applySnapshot));
273         mockRaftActor.handleCommand(applySnapshot);
274
275         CaptureSnapshot captureSnapshot = new CaptureSnapshot(1, 1, 1, 1, 0, 1);
276         doReturn(true).when(mockSupport).handleSnapshotMessage(same(captureSnapshot));
277         mockRaftActor.handleCommand(captureSnapshot);
278
279         CaptureSnapshotReply captureSnapshotReply = new CaptureSnapshotReply(new byte[0]);
280         doReturn(true).when(mockSupport).handleSnapshotMessage(same(captureSnapshotReply));
281         mockRaftActor.handleCommand(captureSnapshotReply);
282
283         SaveSnapshotSuccess saveSnapshotSuccess = new SaveSnapshotSuccess(mock(SnapshotMetadata.class));
284         doReturn(true).when(mockSupport).handleSnapshotMessage(same(saveSnapshotSuccess));
285         mockRaftActor.handleCommand(saveSnapshotSuccess);
286
287         SaveSnapshotFailure saveSnapshotFailure = new SaveSnapshotFailure(mock(SnapshotMetadata.class), new Throwable());
288         doReturn(true).when(mockSupport).handleSnapshotMessage(same(saveSnapshotFailure));
289         mockRaftActor.handleCommand(saveSnapshotFailure);
290
291         doReturn(true).when(mockSupport).handleSnapshotMessage(same(RaftActorSnapshotMessageSupport.COMMIT_SNAPSHOT));
292         mockRaftActor.handleCommand(RaftActorSnapshotMessageSupport.COMMIT_SNAPSHOT);
293
294         verify(mockSupport).handleSnapshotMessage(same(applySnapshot));
295         verify(mockSupport).handleSnapshotMessage(same(captureSnapshot));
296         verify(mockSupport).handleSnapshotMessage(same(captureSnapshotReply));
297         verify(mockSupport).handleSnapshotMessage(same(saveSnapshotSuccess));
298         verify(mockSupport).handleSnapshotMessage(same(saveSnapshotFailure));
299         verify(mockSupport).handleSnapshotMessage(same(RaftActorSnapshotMessageSupport.COMMIT_SNAPSHOT));
300     }
301
302     @Test
303     public void testUpdatingElectionTermCallsDataPersistence() throws Exception {
304         new JavaTestKit(getSystem()) {
305             {
306                 String persistenceId = factory.generateActorId("leader-");
307
308                 DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
309
310                 config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
311
312                 CountDownLatch persistLatch = new CountDownLatch(1);
313                 DataPersistenceProviderMonitor dataPersistenceProviderMonitor = new DataPersistenceProviderMonitor();
314                 dataPersistenceProviderMonitor.setPersistLatch(persistLatch);
315
316                 TestActorRef<MockRaftActor> mockActorRef = factory.createTestActor(MockRaftActor.props(persistenceId,
317                         Collections.<String, String>emptyMap(), Optional.<ConfigParams>of(config), dataPersistenceProviderMonitor), persistenceId);
318
319                 MockRaftActor mockRaftActor = mockActorRef.underlyingActor();
320
321                 mockRaftActor.waitForInitializeBehaviorComplete();
322
323                 mockRaftActor.getRaftActorContext().getTermInformation().updateAndPersist(10, "foobar");
324
325                 assertEquals("Persist called", true, persistLatch.await(5, TimeUnit.SECONDS));
326             }
327         };
328     }
329
330     @Test
331     public void testApplyJournalEntriesCallsDataPersistence() throws Exception {
332         new JavaTestKit(getSystem()) {
333             {
334                 String persistenceId = factory.generateActorId("leader-");
335
336                 DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
337
338                 config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
339
340                 DataPersistenceProvider dataPersistenceProvider = mock(DataPersistenceProvider.class);
341
342                 TestActorRef<MockRaftActor> mockActorRef = factory.createTestActor(MockRaftActor.props(persistenceId,
343                         Collections.<String, String>emptyMap(), Optional.<ConfigParams>of(config), dataPersistenceProvider), persistenceId);
344
345                 MockRaftActor mockRaftActor = mockActorRef.underlyingActor();
346
347                 mockRaftActor.waitForInitializeBehaviorComplete();
348
349                 mockRaftActor.waitUntilLeader();
350
351                 mockRaftActor.onReceiveCommand(new ApplyJournalEntries(10));
352
353                 verify(dataPersistenceProvider, times(2)).persist(anyObject(), any(Procedure.class));
354
355             }
356
357         };
358     }
359
360     @Test
361     public void testApplyState() throws Exception {
362
363         new JavaTestKit(getSystem()) {
364             {
365                 String persistenceId = factory.generateActorId("leader-");
366
367                 DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
368
369                 config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
370
371                 DataPersistenceProvider dataPersistenceProvider = mock(DataPersistenceProvider.class);
372
373                 TestActorRef<MockRaftActor> mockActorRef = factory.createTestActor(MockRaftActor.props(persistenceId,
374                         Collections.<String, String>emptyMap(), Optional.<ConfigParams>of(config), dataPersistenceProvider), persistenceId);
375
376                 MockRaftActor mockRaftActor = mockActorRef.underlyingActor();
377
378                 mockRaftActor.waitForInitializeBehaviorComplete();
379
380                 ReplicatedLogEntry entry = new MockRaftActorContext.MockReplicatedLogEntry(1, 5,
381                         new MockRaftActorContext.MockPayload("F"));
382
383                 mockRaftActor.onReceiveCommand(new ApplyState(mockActorRef, "apply-state", entry));
384
385                 verify(mockRaftActor.actorDelegate).applyState(eq(mockActorRef), eq("apply-state"), anyObject());
386
387             }
388         };
389     }
390
391     @Test
392     public void testRaftRoleChangeNotifierWhenRaftActorHasNoPeers() throws Exception {
393         new JavaTestKit(getSystem()) {{
394             TestActorRef<MessageCollectorActor> notifierActor = factory.createTestActor(
395                     Props.create(MessageCollectorActor.class));
396             MessageCollectorActor.waitUntilReady(notifierActor);
397
398             DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
399             long heartBeatInterval = 100;
400             config.setHeartBeatInterval(FiniteDuration.create(heartBeatInterval, TimeUnit.MILLISECONDS));
401             config.setElectionTimeoutFactor(20);
402
403             String persistenceId = factory.generateActorId("notifier-");
404
405             TestActorRef<MockRaftActor> raftActorRef = factory.createTestActor(MockRaftActor.props(persistenceId,
406                     Collections.<String, String>emptyMap(), Optional.<ConfigParams>of(config), notifierActor,
407                     new NonPersistentDataProvider()), persistenceId);
408
409             List<RoleChanged> matches =  MessageCollectorActor.expectMatching(notifierActor, RoleChanged.class, 3);
410
411
412             // check if the notifier got a role change from null to Follower
413             RoleChanged raftRoleChanged = matches.get(0);
414             assertEquals(persistenceId, raftRoleChanged.getMemberId());
415             assertNull(raftRoleChanged.getOldRole());
416             assertEquals(RaftState.Follower.name(), raftRoleChanged.getNewRole());
417
418             // check if the notifier got a role change from Follower to Candidate
419             raftRoleChanged = matches.get(1);
420             assertEquals(persistenceId, raftRoleChanged.getMemberId());
421             assertEquals(RaftState.Follower.name(), raftRoleChanged.getOldRole());
422             assertEquals(RaftState.Candidate.name(), raftRoleChanged.getNewRole());
423
424             // check if the notifier got a role change from Candidate to Leader
425             raftRoleChanged = matches.get(2);
426             assertEquals(persistenceId, raftRoleChanged.getMemberId());
427             assertEquals(RaftState.Candidate.name(), raftRoleChanged.getOldRole());
428             assertEquals(RaftState.Leader.name(), raftRoleChanged.getNewRole());
429
430             LeaderStateChanged leaderStateChange = MessageCollectorActor.expectFirstMatching(
431                     notifierActor, LeaderStateChanged.class);
432
433             assertEquals(raftRoleChanged.getMemberId(), leaderStateChange.getLeaderId());
434
435             notifierActor.underlyingActor().clear();
436
437             MockRaftActor raftActor = raftActorRef.underlyingActor();
438             final String newLeaderId = "new-leader";
439             Follower follower = new Follower(raftActor.getRaftActorContext()) {
440                 @Override
441                 public RaftActorBehavior handleMessage(ActorRef sender, Object message) {
442                     leaderId = newLeaderId;
443                     return this;
444                 }
445             };
446
447             raftActor.changeCurrentBehavior(follower);
448
449             leaderStateChange = MessageCollectorActor.expectFirstMatching(notifierActor, LeaderStateChanged.class);
450             assertEquals(persistenceId, leaderStateChange.getMemberId());
451             assertEquals(null, leaderStateChange.getLeaderId());
452
453             raftRoleChanged = MessageCollectorActor.expectFirstMatching(notifierActor, RoleChanged.class);
454             assertEquals(RaftState.Leader.name(), raftRoleChanged.getOldRole());
455             assertEquals(RaftState.Follower.name(), raftRoleChanged.getNewRole());
456
457             notifierActor.underlyingActor().clear();
458
459             raftActor.handleCommand("any");
460
461             leaderStateChange = MessageCollectorActor.expectFirstMatching(notifierActor, LeaderStateChanged.class);
462             assertEquals(persistenceId, leaderStateChange.getMemberId());
463             assertEquals(newLeaderId, leaderStateChange.getLeaderId());
464         }};
465     }
466
467     @Test
468     public void testRaftRoleChangeNotifierWhenRaftActorHasPeers() throws Exception {
469         new JavaTestKit(getSystem()) {{
470             ActorRef notifierActor = factory.createActor(Props.create(MessageCollectorActor.class));
471             MessageCollectorActor.waitUntilReady(notifierActor);
472
473             DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
474             long heartBeatInterval = 100;
475             config.setHeartBeatInterval(FiniteDuration.create(heartBeatInterval, TimeUnit.MILLISECONDS));
476             config.setElectionTimeoutFactor(1);
477
478             String persistenceId = factory.generateActorId("notifier-");
479
480             factory.createActor(MockRaftActor.props(persistenceId,
481                     ImmutableMap.of("leader", "fake/path"), Optional.<ConfigParams>of(config), notifierActor), persistenceId);
482
483             List<RoleChanged> matches =  null;
484             for(int i = 0; i < 5000 / heartBeatInterval; i++) {
485                 matches = MessageCollectorActor.getAllMatching(notifierActor, RoleChanged.class);
486                 assertNotNull(matches);
487                 if(matches.size() == 3) {
488                     break;
489                 }
490                 Uninterruptibles.sleepUninterruptibly(heartBeatInterval, TimeUnit.MILLISECONDS);
491             }
492
493             assertEquals(2, matches.size());
494
495             // check if the notifier got a role change from null to Follower
496             RoleChanged raftRoleChanged = matches.get(0);
497             assertEquals(persistenceId, raftRoleChanged.getMemberId());
498             assertNull(raftRoleChanged.getOldRole());
499             assertEquals(RaftState.Follower.name(), raftRoleChanged.getNewRole());
500
501             // check if the notifier got a role change from Follower to Candidate
502             raftRoleChanged = matches.get(1);
503             assertEquals(persistenceId, raftRoleChanged.getMemberId());
504             assertEquals(RaftState.Follower.name(), raftRoleChanged.getOldRole());
505             assertEquals(RaftState.Candidate.name(), raftRoleChanged.getNewRole());
506
507         }};
508     }
509
510     @Test
511     public void testFakeSnapshotsForLeaderWithInRealSnapshots() throws Exception {
512         new JavaTestKit(getSystem()) {
513             {
514                 String persistenceId = factory.generateActorId("leader-");
515                 String follower1Id = factory.generateActorId("follower-");
516
517                 ActorRef followerActor1 =
518                         factory.createActor(Props.create(MessageCollectorActor.class));
519
520                 DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
521                 config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
522                 config.setIsolatedLeaderCheckInterval(new FiniteDuration(1, TimeUnit.DAYS));
523
524                 DataPersistenceProvider dataPersistenceProvider = mock(DataPersistenceProvider.class);
525
526                 Map<String, String> peerAddresses = new HashMap<>();
527                 peerAddresses.put(follower1Id, followerActor1.path().toString());
528
529                 TestActorRef<MockRaftActor> mockActorRef = factory.createTestActor(
530                         MockRaftActor.props(persistenceId, peerAddresses,
531                                 Optional.<ConfigParams>of(config), dataPersistenceProvider), persistenceId);
532
533                 MockRaftActor leaderActor = mockActorRef.underlyingActor();
534
535                 leaderActor.getRaftActorContext().setCommitIndex(4);
536                 leaderActor.getRaftActorContext().setLastApplied(4);
537                 leaderActor.getRaftActorContext().getTermInformation().update(1, persistenceId);
538
539                 leaderActor.waitForInitializeBehaviorComplete();
540
541                 // create 8 entries in the log - 0 to 4 are applied and will get picked up as part of the capture snapshot
542
543                 Leader leader = new Leader(leaderActor.getRaftActorContext());
544                 leaderActor.setCurrentBehavior(leader);
545                 assertEquals(RaftState.Leader, leaderActor.getCurrentBehavior().state());
546
547                 MockRaftActorContext.MockReplicatedLogBuilder logBuilder = new MockRaftActorContext.MockReplicatedLogBuilder();
548                 leaderActor.getRaftActorContext().setReplicatedLog(logBuilder.createEntries(0, 8, 1).build());
549
550                 assertEquals(8, leaderActor.getReplicatedLog().size());
551
552                 leaderActor.getRaftActorContext().getSnapshotManager()
553                         .capture(new MockRaftActorContext.MockReplicatedLogEntry(1, 6,
554                                 new MockRaftActorContext.MockPayload("x")), 4);
555
556                 verify(leaderActor.snapshotCohortDelegate).createSnapshot(any(ActorRef.class));
557
558                 assertEquals(8, leaderActor.getReplicatedLog().size());
559
560                 assertEquals(RaftState.Leader, leaderActor.getCurrentBehavior().state());
561                 //fake snapshot on index 5
562                 leaderActor.onReceiveCommand(new AppendEntriesReply(follower1Id, 1, true, 5, 1));
563
564                 assertEquals(8, leaderActor.getReplicatedLog().size());
565
566                 //fake snapshot on index 6
567                 assertEquals(RaftState.Leader, leaderActor.getCurrentBehavior().state());
568                 leaderActor.onReceiveCommand(new AppendEntriesReply(follower1Id, 1, true, 6, 1));
569                 assertEquals(8, leaderActor.getReplicatedLog().size());
570
571                 assertEquals(RaftState.Leader, leaderActor.getCurrentBehavior().state());
572
573                 assertEquals(8, leaderActor.getReplicatedLog().size());
574
575                 ByteString snapshotBytes = fromObject(Arrays.asList(
576                         new MockRaftActorContext.MockPayload("foo-0"),
577                         new MockRaftActorContext.MockPayload("foo-1"),
578                         new MockRaftActorContext.MockPayload("foo-2"),
579                         new MockRaftActorContext.MockPayload("foo-3"),
580                         new MockRaftActorContext.MockPayload("foo-4")));
581
582                 leaderActor.getRaftActorContext().getSnapshotManager().persist(new NonPersistentDataProvider()
583                         , snapshotBytes.toByteArray(), leader, Runtime.getRuntime().totalMemory());
584
585                 assertFalse(leaderActor.getRaftActorContext().getSnapshotManager().isCapturing());
586
587                 // The commit is needed to complete the snapshot creation process
588                 leaderActor.getRaftActorContext().getSnapshotManager().commit(new NonPersistentDataProvider(), -1);
589
590                 // capture snapshot reply should remove the snapshotted entries only
591                 assertEquals(3, leaderActor.getReplicatedLog().size());
592                 assertEquals(7, leaderActor.getReplicatedLog().lastIndex());
593
594                 // add another non-replicated entry
595                 leaderActor.getReplicatedLog().append(
596                         new ReplicatedLogImplEntry(8, 1, new MockRaftActorContext.MockPayload("foo-8")));
597
598                 //fake snapshot on index 7, since lastApplied = 7 , we would keep the last applied
599                 leaderActor.onReceiveCommand(new AppendEntriesReply(follower1Id, 1, true, 7, 1));
600                 assertEquals(2, leaderActor.getReplicatedLog().size());
601                 assertEquals(8, leaderActor.getReplicatedLog().lastIndex());
602
603             }
604         };
605     }
606
607     @Test
608     public void testFakeSnapshotsForFollowerWithInRealSnapshots() throws Exception {
609         new JavaTestKit(getSystem()) {
610             {
611                 String persistenceId = factory.generateActorId("follower-");
612                 String leaderId = factory.generateActorId("leader-");
613
614
615                 ActorRef leaderActor1 =
616                         factory.createActor(Props.create(MessageCollectorActor.class));
617
618                 DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
619                 config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
620                 config.setIsolatedLeaderCheckInterval(new FiniteDuration(1, TimeUnit.DAYS));
621
622                 DataPersistenceProvider dataPersistenceProvider = mock(DataPersistenceProvider.class);
623
624                 Map<String, String> peerAddresses = new HashMap<>();
625                 peerAddresses.put(leaderId, leaderActor1.path().toString());
626
627                 TestActorRef<MockRaftActor> mockActorRef = factory.createTestActor(
628                         MockRaftActor.props(persistenceId, peerAddresses,
629                                 Optional.<ConfigParams>of(config), dataPersistenceProvider), persistenceId);
630
631                 MockRaftActor followerActor = mockActorRef.underlyingActor();
632                 followerActor.getRaftActorContext().setCommitIndex(4);
633                 followerActor.getRaftActorContext().setLastApplied(4);
634                 followerActor.getRaftActorContext().getTermInformation().update(1, persistenceId);
635
636                 followerActor.waitForInitializeBehaviorComplete();
637
638
639                 Follower follower = new Follower(followerActor.getRaftActorContext());
640                 followerActor.setCurrentBehavior(follower);
641                 assertEquals(RaftState.Follower, followerActor.getCurrentBehavior().state());
642
643                 // create 6 entries in the log - 0 to 4 are applied and will get picked up as part of the capture snapshot
644                 MockRaftActorContext.MockReplicatedLogBuilder logBuilder = new MockRaftActorContext.MockReplicatedLogBuilder();
645                 followerActor.getRaftActorContext().setReplicatedLog(logBuilder.createEntries(0, 6, 1).build());
646
647                 // log has indices 0-5
648                 assertEquals(6, followerActor.getReplicatedLog().size());
649
650                 //snapshot on 4
651                 followerActor.getRaftActorContext().getSnapshotManager().capture(
652                         new MockRaftActorContext.MockReplicatedLogEntry(1, 5,
653                                 new MockRaftActorContext.MockPayload("D")), 4);
654
655                 verify(followerActor.snapshotCohortDelegate).createSnapshot(any(ActorRef.class));
656
657                 assertEquals(6, followerActor.getReplicatedLog().size());
658
659                 //fake snapshot on index 6
660                 List<ReplicatedLogEntry> entries =
661                         Arrays.asList(
662                                 (ReplicatedLogEntry) new MockRaftActorContext.MockReplicatedLogEntry(1, 6,
663                                         new MockRaftActorContext.MockPayload("foo-6"))
664                         );
665                 followerActor.onReceiveCommand(new AppendEntries(1, leaderId, 5, 1, entries, 5, 5));
666                 assertEquals(7, followerActor.getReplicatedLog().size());
667
668                 //fake snapshot on index 7
669                 assertEquals(RaftState.Follower, followerActor.getCurrentBehavior().state());
670
671                 entries =
672                         Arrays.asList(
673                                 (ReplicatedLogEntry) new MockRaftActorContext.MockReplicatedLogEntry(1, 7,
674                                         new MockRaftActorContext.MockPayload("foo-7"))
675                         );
676                 followerActor.onReceiveCommand(new AppendEntries(1, leaderId, 6, 1, entries, 6, 6));
677                 assertEquals(8, followerActor.getReplicatedLog().size());
678
679                 assertEquals(RaftState.Follower, followerActor.getCurrentBehavior().state());
680
681
682                 ByteString snapshotBytes = fromObject(Arrays.asList(
683                         new MockRaftActorContext.MockPayload("foo-0"),
684                         new MockRaftActorContext.MockPayload("foo-1"),
685                         new MockRaftActorContext.MockPayload("foo-2"),
686                         new MockRaftActorContext.MockPayload("foo-3"),
687                         new MockRaftActorContext.MockPayload("foo-4")));
688                 followerActor.onReceiveCommand(new CaptureSnapshotReply(snapshotBytes.toByteArray()));
689                 assertFalse(followerActor.getRaftActorContext().getSnapshotManager().isCapturing());
690
691                 // The commit is needed to complete the snapshot creation process
692                 followerActor.getRaftActorContext().getSnapshotManager().commit(new NonPersistentDataProvider(), -1);
693
694                 // capture snapshot reply should remove the snapshotted entries only till replicatedToAllIndex
695                 assertEquals(3, followerActor.getReplicatedLog().size()); //indexes 5,6,7 left in the log
696                 assertEquals(7, followerActor.getReplicatedLog().lastIndex());
697
698                 entries =
699                         Arrays.asList(
700                                 (ReplicatedLogEntry) new MockRaftActorContext.MockReplicatedLogEntry(1, 8,
701                                         new MockRaftActorContext.MockPayload("foo-7"))
702                         );
703                 // send an additional entry 8 with leaderCommit = 7
704                 followerActor.onReceiveCommand(new AppendEntries(1, leaderId, 7, 1, entries, 7, 7));
705
706                 // 7 and 8, as lastapplied is 7
707                 assertEquals(2, followerActor.getReplicatedLog().size());
708
709             }
710         };
711     }
712
713     @Test
714     public void testFakeSnapshotsForLeaderWithInInitiateSnapshots() throws Exception {
715         new JavaTestKit(getSystem()) {
716             {
717                 String persistenceId = factory.generateActorId("leader-");
718                 String follower1Id = factory.generateActorId("follower-");
719                 String follower2Id = factory.generateActorId("follower-");
720
721                 ActorRef followerActor1 =
722                         factory.createActor(Props.create(MessageCollectorActor.class), follower1Id);
723                 ActorRef followerActor2 =
724                         factory.createActor(Props.create(MessageCollectorActor.class), follower2Id);
725
726                 DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
727                 config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
728                 config.setIsolatedLeaderCheckInterval(new FiniteDuration(1, TimeUnit.DAYS));
729
730                 DataPersistenceProvider dataPersistenceProvider = mock(DataPersistenceProvider.class);
731
732                 Map<String, String> peerAddresses = new HashMap<>();
733                 peerAddresses.put(follower1Id, followerActor1.path().toString());
734                 peerAddresses.put(follower2Id, followerActor2.path().toString());
735
736                 TestActorRef<MockRaftActor> mockActorRef = factory.createTestActor(
737                         MockRaftActor.props(persistenceId, peerAddresses,
738                                 Optional.<ConfigParams>of(config), dataPersistenceProvider), persistenceId);
739
740                 MockRaftActor leaderActor = mockActorRef.underlyingActor();
741                 leaderActor.getRaftActorContext().setCommitIndex(9);
742                 leaderActor.getRaftActorContext().setLastApplied(9);
743                 leaderActor.getRaftActorContext().getTermInformation().update(1, persistenceId);
744
745                 leaderActor.waitForInitializeBehaviorComplete();
746
747                 Leader leader = new Leader(leaderActor.getRaftActorContext());
748                 leaderActor.setCurrentBehavior(leader);
749                 assertEquals(RaftState.Leader, leaderActor.getCurrentBehavior().state());
750
751                 // create 5 entries in the log
752                 MockRaftActorContext.MockReplicatedLogBuilder logBuilder = new MockRaftActorContext.MockReplicatedLogBuilder();
753                 leaderActor.getRaftActorContext().setReplicatedLog(logBuilder.createEntries(5, 10, 1).build());
754
755                 //set the snapshot index to 4 , 0 to 4 are snapshotted
756                 leaderActor.getRaftActorContext().getReplicatedLog().setSnapshotIndex(4);
757                 //setting replicatedToAllIndex = 9, for the log to clear
758                 leader.setReplicatedToAllIndex(9);
759                 assertEquals(5, leaderActor.getReplicatedLog().size());
760                 assertEquals(RaftState.Leader, leaderActor.getCurrentBehavior().state());
761
762                 leaderActor.onReceiveCommand(new AppendEntriesReply(follower1Id, 1, true, 9, 1));
763                 assertEquals(5, leaderActor.getReplicatedLog().size());
764                 assertEquals(RaftState.Leader, leaderActor.getCurrentBehavior().state());
765
766                 // set the 2nd follower nextIndex to 1 which has been snapshotted
767                 leaderActor.onReceiveCommand(new AppendEntriesReply(follower2Id, 1, true, 0, 1));
768                 assertEquals(5, leaderActor.getReplicatedLog().size());
769                 assertEquals(RaftState.Leader, leaderActor.getCurrentBehavior().state());
770
771                 // simulate a real snapshot
772                 leaderActor.onReceiveCommand(new SendHeartBeat());
773                 assertEquals(5, leaderActor.getReplicatedLog().size());
774                 assertEquals(String.format("expected to be Leader but was %s. Current Leader = %s ",
775                         leaderActor.getCurrentBehavior().state(), leaderActor.getLeaderId())
776                         , RaftState.Leader, leaderActor.getCurrentBehavior().state());
777
778
779                 //reply from a slow follower does not initiate a fake snapshot
780                 leaderActor.onReceiveCommand(new AppendEntriesReply(follower2Id, 1, true, 9, 1));
781                 assertEquals("Fake snapshot should not happen when Initiate is in progress", 5, leaderActor.getReplicatedLog().size());
782
783                 ByteString snapshotBytes = fromObject(Arrays.asList(
784                         new MockRaftActorContext.MockPayload("foo-0"),
785                         new MockRaftActorContext.MockPayload("foo-1"),
786                         new MockRaftActorContext.MockPayload("foo-2"),
787                         new MockRaftActorContext.MockPayload("foo-3"),
788                         new MockRaftActorContext.MockPayload("foo-4")));
789                 leaderActor.onReceiveCommand(new CaptureSnapshotReply(snapshotBytes.toByteArray()));
790                 assertFalse(leaderActor.getRaftActorContext().getSnapshotManager().isCapturing());
791
792                 assertEquals("Real snapshot didn't clear the log till replicatedToAllIndex", 0, leaderActor.getReplicatedLog().size());
793
794                 //reply from a slow follower after should not raise errors
795                 leaderActor.onReceiveCommand(new AppendEntriesReply(follower2Id, 1, true, 5, 1));
796                 assertEquals(0, leaderActor.getReplicatedLog().size());
797             }
798         };
799     }
800
801     @Test
802     public void testRealSnapshotWhenReplicatedToAllIndexMinusOne() throws Exception {
803         new JavaTestKit(getSystem()) {{
804             String persistenceId = factory.generateActorId("leader-");
805             DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
806             config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
807             config.setIsolatedLeaderCheckInterval(new FiniteDuration(1, TimeUnit.DAYS));
808             config.setSnapshotBatchCount(5);
809
810             DataPersistenceProvider dataPersistenceProvider = new NonPersistentDataProvider();
811
812             Map<String, String> peerAddresses = new HashMap<>();
813
814             TestActorRef<MockRaftActor> mockActorRef = factory.createTestActor(
815                     MockRaftActor.props(persistenceId, peerAddresses,
816                             Optional.<ConfigParams>of(config), dataPersistenceProvider), persistenceId);
817
818             MockRaftActor leaderActor = mockActorRef.underlyingActor();
819             leaderActor.getRaftActorContext().setCommitIndex(3);
820             leaderActor.getRaftActorContext().setLastApplied(3);
821             leaderActor.getRaftActorContext().getTermInformation().update(1, persistenceId);
822
823             leaderActor.waitForInitializeBehaviorComplete();
824             for(int i=0;i< 4;i++) {
825                 leaderActor.getReplicatedLog()
826                         .append(new MockRaftActorContext.MockReplicatedLogEntry(1, i,
827                                 new MockRaftActorContext.MockPayload("A")));
828             }
829
830             Leader leader = new Leader(leaderActor.getRaftActorContext());
831             leaderActor.setCurrentBehavior(leader);
832             assertEquals(RaftState.Leader, leaderActor.getCurrentBehavior().state());
833
834             // Persist another entry (this will cause a CaptureSnapshot to be triggered
835             leaderActor.persistData(mockActorRef, "x", new MockRaftActorContext.MockPayload("duh"));
836
837             // Now send a CaptureSnapshotReply
838             mockActorRef.tell(new CaptureSnapshotReply(fromObject("foo").toByteArray()), mockActorRef);
839
840             // Trimming log in this scenario is a no-op
841             assertEquals(-1, leaderActor.getReplicatedLog().getSnapshotIndex());
842             assertFalse(leaderActor.getRaftActorContext().getSnapshotManager().isCapturing());
843             assertEquals(-1, leader.getReplicatedToAllIndex());
844
845         }};
846     }
847
848     @Test
849     public void testRealSnapshotWhenReplicatedToAllIndexNotInReplicatedLog() throws Exception {
850         new JavaTestKit(getSystem()) {{
851             String persistenceId = factory.generateActorId("leader-");
852             DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
853             config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
854             config.setIsolatedLeaderCheckInterval(new FiniteDuration(1, TimeUnit.DAYS));
855             config.setSnapshotBatchCount(5);
856
857             DataPersistenceProvider dataPersistenceProvider = new NonPersistentDataProvider();
858
859             Map<String, String> peerAddresses = new HashMap<>();
860
861             TestActorRef<MockRaftActor> mockActorRef = factory.createTestActor(
862                     MockRaftActor.props(persistenceId, peerAddresses,
863                             Optional.<ConfigParams>of(config), dataPersistenceProvider), persistenceId);
864
865             MockRaftActor leaderActor = mockActorRef.underlyingActor();
866             leaderActor.getRaftActorContext().setCommitIndex(3);
867             leaderActor.getRaftActorContext().setLastApplied(3);
868             leaderActor.getRaftActorContext().getTermInformation().update(1, persistenceId);
869             leaderActor.getReplicatedLog().setSnapshotIndex(3);
870
871             leaderActor.waitForInitializeBehaviorComplete();
872             Leader leader = new Leader(leaderActor.getRaftActorContext());
873             leaderActor.setCurrentBehavior(leader);
874             leader.setReplicatedToAllIndex(3);
875             assertEquals(RaftState.Leader, leaderActor.getCurrentBehavior().state());
876
877             // Persist another entry (this will cause a CaptureSnapshot to be triggered
878             leaderActor.persistData(mockActorRef, "x", new MockRaftActorContext.MockPayload("duh"));
879
880             // Now send a CaptureSnapshotReply
881             mockActorRef.tell(new CaptureSnapshotReply(fromObject("foo").toByteArray()), mockActorRef);
882
883             // Trimming log in this scenario is a no-op
884             assertEquals(3, leaderActor.getReplicatedLog().getSnapshotIndex());
885             assertFalse(leaderActor.getRaftActorContext().getSnapshotManager().isCapturing());
886             assertEquals(3, leader.getReplicatedToAllIndex());
887
888         }};
889     }
890
891     private ByteString fromObject(Object snapshot) throws Exception {
892         ByteArrayOutputStream b = null;
893         ObjectOutputStream o = null;
894         try {
895             b = new ByteArrayOutputStream();
896             o = new ObjectOutputStream(b);
897             o.writeObject(snapshot);
898             byte[] snapshotBytes = b.toByteArray();
899             return ByteString.copyFrom(snapshotBytes);
900         } finally {
901             if (o != null) {
902                 o.flush();
903                 o.close();
904             }
905             if (b != null) {
906                 b.close();
907             }
908         }
909     }
910
911 }

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