Merge "BUG 2676 : Introduce API for accessing akka dispatchers"
[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.assertNotEquals;
6 import static org.junit.Assert.assertNotNull;
7 import static org.junit.Assert.assertNull;
8 import static org.junit.Assert.assertTrue;
9 import static org.mockito.Matchers.any;
10 import static org.mockito.Matchers.anyObject;
11 import static org.mockito.Matchers.eq;
12 import static org.mockito.Mockito.doReturn;
13 import static org.mockito.Mockito.mock;
14 import static org.mockito.Mockito.times;
15 import static org.mockito.Mockito.verify;
16 import akka.actor.ActorRef;
17 import akka.actor.ActorSystem;
18 import akka.actor.PoisonPill;
19 import akka.actor.Props;
20 import akka.actor.Terminated;
21 import akka.japi.Creator;
22 import akka.japi.Procedure;
23 import akka.pattern.Patterns;
24 import akka.persistence.RecoveryCompleted;
25 import akka.persistence.SaveSnapshotFailure;
26 import akka.persistence.SaveSnapshotSuccess;
27 import akka.persistence.SnapshotMetadata;
28 import akka.persistence.SnapshotOffer;
29 import akka.persistence.SnapshotSelectionCriteria;
30 import akka.testkit.JavaTestKit;
31 import akka.testkit.TestActorRef;
32 import akka.util.Timeout;
33 import com.google.common.base.Optional;
34 import com.google.common.collect.Lists;
35 import com.google.common.util.concurrent.Uninterruptibles;
36 import com.google.protobuf.ByteString;
37 import java.io.ByteArrayInputStream;
38 import java.io.ByteArrayOutputStream;
39 import java.io.IOException;
40 import java.io.ObjectInputStream;
41 import java.io.ObjectOutputStream;
42 import java.util.ArrayList;
43 import java.util.Arrays;
44 import java.util.Collections;
45 import java.util.HashMap;
46 import java.util.List;
47 import java.util.Map;
48 import java.util.concurrent.CountDownLatch;
49 import java.util.concurrent.TimeUnit;
50 import java.util.concurrent.TimeoutException;
51 import org.junit.After;
52 import org.junit.Assert;
53 import org.junit.Before;
54 import org.junit.Test;
55 import org.opendaylight.controller.cluster.DataPersistenceProvider;
56 import org.opendaylight.controller.cluster.datastore.DataPersistenceProviderMonitor;
57 import org.opendaylight.controller.cluster.notifications.RoleChanged;
58 import org.opendaylight.controller.cluster.raft.base.messages.ApplyLogEntries;
59 import org.opendaylight.controller.cluster.raft.base.messages.ApplySnapshot;
60 import org.opendaylight.controller.cluster.raft.base.messages.ApplyState;
61 import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshot;
62 import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshotReply;
63 import org.opendaylight.controller.cluster.raft.base.messages.SendHeartBeat;
64 import org.opendaylight.controller.cluster.raft.behaviors.Follower;
65 import org.opendaylight.controller.cluster.raft.behaviors.Leader;
66 import org.opendaylight.controller.cluster.raft.client.messages.FindLeader;
67 import org.opendaylight.controller.cluster.raft.client.messages.FindLeaderReply;
68 import org.opendaylight.controller.cluster.raft.messages.AppendEntries;
69 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
70 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
71 import org.opendaylight.controller.cluster.raft.utils.MessageCollectorActor;
72 import org.opendaylight.controller.cluster.raft.utils.MockAkkaJournal;
73 import org.opendaylight.controller.cluster.raft.utils.MockSnapshotStore;
74 import scala.concurrent.Await;
75 import scala.concurrent.Future;
76 import scala.concurrent.duration.Duration;
77 import scala.concurrent.duration.FiniteDuration;
78
79 public class RaftActorTest extends AbstractActorTest {
80
81     private TestActorFactory factory;
82
83     @Before
84     public void setUp(){
85         factory = new TestActorFactory(getSystem());
86     }
87
88     @After
89     public void tearDown() throws Exception {
90         factory.close();
91         MockAkkaJournal.clearJournal();
92         MockSnapshotStore.setMockSnapshot(null);
93     }
94
95     public static class MockRaftActor extends RaftActor {
96
97         private final DataPersistenceProvider dataPersistenceProvider;
98         private final RaftActor delegate;
99         private final CountDownLatch recoveryComplete = new CountDownLatch(1);
100         private final List<Object> state;
101         private ActorRef roleChangeNotifier;
102         private final CountDownLatch initializeBehaviorComplete = new CountDownLatch(1);
103
104         public static final class MockRaftActorCreator implements Creator<MockRaftActor> {
105             private static final long serialVersionUID = 1L;
106             private final Map<String, String> peerAddresses;
107             private final String id;
108             private final Optional<ConfigParams> config;
109             private final DataPersistenceProvider dataPersistenceProvider;
110             private final ActorRef roleChangeNotifier;
111
112             private MockRaftActorCreator(Map<String, String> peerAddresses, String id,
113                 Optional<ConfigParams> config, DataPersistenceProvider dataPersistenceProvider,
114                 ActorRef roleChangeNotifier) {
115                 this.peerAddresses = peerAddresses;
116                 this.id = id;
117                 this.config = config;
118                 this.dataPersistenceProvider = dataPersistenceProvider;
119                 this.roleChangeNotifier = roleChangeNotifier;
120             }
121
122             @Override
123             public MockRaftActor create() throws Exception {
124                 MockRaftActor mockRaftActor = new MockRaftActor(id, peerAddresses, config,
125                     dataPersistenceProvider);
126                 mockRaftActor.roleChangeNotifier = this.roleChangeNotifier;
127                 return mockRaftActor;
128             }
129         }
130
131         public MockRaftActor(String id, Map<String, String> peerAddresses, Optional<ConfigParams> config,
132                              DataPersistenceProvider dataPersistenceProvider) {
133             super(id, peerAddresses, config);
134             state = new ArrayList<>();
135             this.delegate = mock(RaftActor.class);
136             if(dataPersistenceProvider == null){
137                 this.dataPersistenceProvider = new PersistentDataProvider();
138             } else {
139                 this.dataPersistenceProvider = dataPersistenceProvider;
140             }
141         }
142
143         public void waitForRecoveryComplete() {
144             try {
145                 assertEquals("Recovery complete", true, recoveryComplete.await(5,  TimeUnit.SECONDS));
146             } catch (InterruptedException e) {
147                 e.printStackTrace();
148             }
149         }
150
151         public void waitForInitializeBehaviorComplete() {
152             try {
153                 assertEquals("Behavior initialized", true, initializeBehaviorComplete.await(5,  TimeUnit.SECONDS));
154             } catch (InterruptedException e) {
155                 e.printStackTrace();
156             }
157         }
158
159         public List<Object> getState() {
160             return state;
161         }
162
163         public static Props props(final String id, final Map<String, String> peerAddresses,
164                 Optional<ConfigParams> config){
165             return Props.create(new MockRaftActorCreator(peerAddresses, id, config, null, null));
166         }
167
168         public static Props props(final String id, final Map<String, String> peerAddresses,
169                                   Optional<ConfigParams> config, DataPersistenceProvider dataPersistenceProvider){
170             return Props.create(new MockRaftActorCreator(peerAddresses, id, config, dataPersistenceProvider, null));
171         }
172
173         public static Props props(final String id, final Map<String, String> peerAddresses,
174             Optional<ConfigParams> config, ActorRef roleChangeNotifier){
175             return Props.create(new MockRaftActorCreator(peerAddresses, id, config, null, roleChangeNotifier));
176         }
177
178         @Override protected void applyState(ActorRef clientActor, String identifier, Object data) {
179             delegate.applyState(clientActor, identifier, data);
180             LOG.info("applyState called");
181         }
182
183         @Override
184         protected void startLogRecoveryBatch(int maxBatchSize) {
185         }
186
187         @Override
188         protected void appendRecoveredLogEntry(Payload data) {
189             state.add(data);
190         }
191
192         @Override
193         protected void applyCurrentLogRecoveryBatch() {
194         }
195
196         @Override
197         protected void onRecoveryComplete() {
198             delegate.onRecoveryComplete();
199             recoveryComplete.countDown();
200         }
201
202         @Override
203         protected void initializeBehavior() {
204             super.initializeBehavior();
205             initializeBehaviorComplete.countDown();
206         }
207
208         @Override
209         protected void applyRecoverySnapshot(byte[] bytes) {
210             delegate.applyRecoverySnapshot(bytes);
211             try {
212                 Object data = toObject(bytes);
213                 if (data instanceof List) {
214                     state.addAll((List<?>) data);
215                 }
216             } catch (Exception e) {
217                 e.printStackTrace();
218             }
219         }
220
221         @Override protected void createSnapshot() {
222             delegate.createSnapshot();
223         }
224
225         @Override protected void applySnapshot(byte [] snapshot) {
226             delegate.applySnapshot(snapshot);
227         }
228
229         @Override protected void onStateChanged() {
230             delegate.onStateChanged();
231         }
232
233         @Override
234         protected DataPersistenceProvider persistence() {
235             return this.dataPersistenceProvider;
236         }
237
238         @Override
239         protected Optional<ActorRef> getRoleChangeNotifier() {
240             return Optional.fromNullable(roleChangeNotifier);
241         }
242
243         @Override public String persistenceId() {
244             return this.getId();
245         }
246
247         private Object toObject(byte[] bs) throws ClassNotFoundException, IOException {
248             Object obj = null;
249             ByteArrayInputStream bis = null;
250             ObjectInputStream ois = null;
251             try {
252                 bis = new ByteArrayInputStream(bs);
253                 ois = new ObjectInputStream(bis);
254                 obj = ois.readObject();
255             } finally {
256                 if (bis != null) {
257                     bis.close();
258                 }
259                 if (ois != null) {
260                     ois.close();
261                 }
262             }
263             return obj;
264         }
265
266         public ReplicatedLog getReplicatedLog(){
267             return this.getRaftActorContext().getReplicatedLog();
268         }
269
270     }
271
272
273     private static class RaftActorTestKit extends JavaTestKit {
274         private final ActorRef raftActor;
275
276         public RaftActorTestKit(ActorSystem actorSystem, String actorName) {
277             super(actorSystem);
278
279             raftActor = this.getSystem().actorOf(MockRaftActor.props(actorName,
280                     Collections.<String,String>emptyMap(), Optional.<ConfigParams>absent()), actorName);
281
282         }
283
284
285         public ActorRef getRaftActor() {
286             return raftActor;
287         }
288
289         public boolean waitForLogMessage(final Class<?> logEventClass, String message){
290             // Wait for a specific log message to show up
291             return
292                 new JavaTestKit.EventFilter<Boolean>(logEventClass
293                 ) {
294                     @Override
295                     protected Boolean run() {
296                         return true;
297                     }
298                 }.from(raftActor.path().toString())
299                     .message(message)
300                     .occurrences(1).exec();
301
302
303         }
304
305         protected void waitUntilLeader(){
306             waitUntilLeader(raftActor);
307         }
308
309         protected void waitUntilLeader(ActorRef actorRef) {
310             FiniteDuration duration = Duration.create(100, TimeUnit.MILLISECONDS);
311             for(int i = 0; i < 20 * 5; i++) {
312                 Future<Object> future = Patterns.ask(actorRef, new FindLeader(), new Timeout(duration));
313                 try {
314                     FindLeaderReply resp = (FindLeaderReply) Await.result(future, duration);
315                     if(resp.getLeaderActor() != null) {
316                         return;
317                     }
318                 } catch(TimeoutException e) {
319                 } catch(Exception e) {
320                     System.err.println("FindLeader threw ex");
321                     e.printStackTrace();
322                 }
323
324
325                 Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
326             }
327
328             Assert.fail("Leader not found for actorRef " + actorRef.path());
329         }
330
331     }
332
333
334     @Test
335     public void testConstruction() {
336         new RaftActorTestKit(getSystem(), "testConstruction").waitUntilLeader();
337     }
338
339     @Test
340     public void testFindLeaderWhenLeaderIsSelf(){
341         RaftActorTestKit kit = new RaftActorTestKit(getSystem(), "testFindLeader");
342         kit.waitUntilLeader();
343     }
344
345     @Test
346     public void testRaftActorRecovery() throws Exception {
347         new JavaTestKit(getSystem()) {{
348             String persistenceId = factory.generateActorId("follower-");
349
350             DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
351             // Set the heartbeat interval high to essentially disable election otherwise the test
352             // may fail if the actor is switched to Leader and the commitIndex is set to the last
353             // log entry.
354             config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
355
356             ActorRef followerActor = factory.createActor(MockRaftActor.props(persistenceId,
357                     Collections.<String, String>emptyMap(), Optional.<ConfigParams>of(config)), persistenceId);
358
359             watch(followerActor);
360
361             List<ReplicatedLogEntry> snapshotUnappliedEntries = new ArrayList<>();
362             ReplicatedLogEntry entry1 = new MockRaftActorContext.MockReplicatedLogEntry(1, 4,
363                     new MockRaftActorContext.MockPayload("E"));
364             snapshotUnappliedEntries.add(entry1);
365
366             int lastAppliedDuringSnapshotCapture = 3;
367             int lastIndexDuringSnapshotCapture = 4;
368
369             // 4 messages as part of snapshot, which are applied to state
370             ByteString snapshotBytes = fromObject(Arrays.asList(
371                     new MockRaftActorContext.MockPayload("A"),
372                     new MockRaftActorContext.MockPayload("B"),
373                     new MockRaftActorContext.MockPayload("C"),
374                     new MockRaftActorContext.MockPayload("D")));
375
376             Snapshot snapshot = Snapshot.create(snapshotBytes.toByteArray(),
377                     snapshotUnappliedEntries, lastIndexDuringSnapshotCapture, 1,
378                     lastAppliedDuringSnapshotCapture, 1);
379             MockSnapshotStore.setMockSnapshot(snapshot);
380             MockSnapshotStore.setPersistenceId(persistenceId);
381
382             // add more entries after snapshot is taken
383             List<ReplicatedLogEntry> entries = new ArrayList<>();
384             ReplicatedLogEntry entry2 = new MockRaftActorContext.MockReplicatedLogEntry(1, 5,
385                     new MockRaftActorContext.MockPayload("F"));
386             ReplicatedLogEntry entry3 = new MockRaftActorContext.MockReplicatedLogEntry(1, 6,
387                     new MockRaftActorContext.MockPayload("G"));
388             ReplicatedLogEntry entry4 = new MockRaftActorContext.MockReplicatedLogEntry(1, 7,
389                     new MockRaftActorContext.MockPayload("H"));
390             entries.add(entry2);
391             entries.add(entry3);
392             entries.add(entry4);
393
394             int lastAppliedToState = 5;
395             int lastIndex = 7;
396
397             MockAkkaJournal.addToJournal(5, entry2);
398             // 2 entries are applied to state besides the 4 entries in snapshot
399             MockAkkaJournal.addToJournal(6, new ApplyLogEntries(lastAppliedToState));
400             MockAkkaJournal.addToJournal(7, entry3);
401             MockAkkaJournal.addToJournal(8, entry4);
402
403             // kill the actor
404             followerActor.tell(PoisonPill.getInstance(), null);
405             expectMsgClass(duration("5 seconds"), Terminated.class);
406
407             unwatch(followerActor);
408
409             //reinstate the actor
410             TestActorRef<MockRaftActor> ref = factory.createTestActor(
411                     MockRaftActor.props(persistenceId, Collections.<String, String>emptyMap(),
412                             Optional.<ConfigParams>of(config)));
413
414             ref.underlyingActor().waitForRecoveryComplete();
415
416             RaftActorContext context = ref.underlyingActor().getRaftActorContext();
417             assertEquals("Journal log size", snapshotUnappliedEntries.size() + entries.size(),
418                     context.getReplicatedLog().size());
419             assertEquals("Last index", lastIndex, context.getReplicatedLog().lastIndex());
420             assertEquals("Last applied", lastAppliedToState, context.getLastApplied());
421             assertEquals("Commit index", lastAppliedToState, context.getCommitIndex());
422             assertEquals("Recovered state size", 6, ref.underlyingActor().getState().size());
423         }};
424     }
425
426     /**
427      * This test verifies that when recovery is applicable (typically when persistence is true) the RaftActor does
428      * process recovery messages
429      *
430      * @throws Exception
431      */
432
433     @Test
434     public void testHandleRecoveryWhenDataPersistenceRecoveryApplicable() throws Exception {
435         new JavaTestKit(getSystem()) {
436             {
437                 String persistenceId = factory.generateActorId("leader-");
438
439                 DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
440
441                 config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
442
443                 TestActorRef<MockRaftActor> mockActorRef = factory.createTestActor(MockRaftActor.props(persistenceId,
444                         Collections.<String, String>emptyMap(), Optional.<ConfigParams>of(config)), persistenceId);
445
446                 MockRaftActor mockRaftActor = mockActorRef.underlyingActor();
447
448                 // Wait for akka's recovery to complete so it doesn't interfere.
449                 mockRaftActor.waitForRecoveryComplete();
450
451                 ByteString snapshotBytes = fromObject(Arrays.asList(
452                         new MockRaftActorContext.MockPayload("A"),
453                         new MockRaftActorContext.MockPayload("B"),
454                         new MockRaftActorContext.MockPayload("C"),
455                         new MockRaftActorContext.MockPayload("D")));
456
457                 Snapshot snapshot = Snapshot.create(snapshotBytes.toByteArray(),
458                         Lists.<ReplicatedLogEntry>newArrayList(), 3, 1, 3, 1);
459
460                 mockRaftActor.onReceiveRecover(new SnapshotOffer(new SnapshotMetadata(persistenceId, 100, 100), snapshot));
461
462                 verify(mockRaftActor.delegate).applyRecoverySnapshot(eq(snapshotBytes.toByteArray()));
463
464                 mockRaftActor.onReceiveRecover(new ReplicatedLogImplEntry(0, 1, new MockRaftActorContext.MockPayload("A")));
465
466                 ReplicatedLog replicatedLog = mockRaftActor.getReplicatedLog();
467
468                 assertEquals("add replicated log entry", 1, replicatedLog.size());
469
470                 mockRaftActor.onReceiveRecover(new ReplicatedLogImplEntry(1, 1, new MockRaftActorContext.MockPayload("A")));
471
472                 assertEquals("add replicated log entry", 2, replicatedLog.size());
473
474                 mockRaftActor.onReceiveRecover(new ApplyLogEntries(1));
475
476                 assertEquals("commit index 1", 1, mockRaftActor.getRaftActorContext().getCommitIndex());
477
478                 // The snapshot had 4 items + we added 2 more items during the test
479                 // We start removing from 5 and we should get 1 item in the replicated log
480                 mockRaftActor.onReceiveRecover(new RaftActor.DeleteEntries(5));
481
482                 assertEquals("remove log entries", 1, replicatedLog.size());
483
484                 mockRaftActor.onReceiveRecover(new RaftActor.UpdateElectionTerm(10, "foobar"));
485
486                 assertEquals("election term", 10, mockRaftActor.getRaftActorContext().getTermInformation().getCurrentTerm());
487                 assertEquals("voted for", "foobar", mockRaftActor.getRaftActorContext().getTermInformation().getVotedFor());
488
489                 mockRaftActor.onReceiveRecover(mock(RecoveryCompleted.class));
490
491             }};
492     }
493
494     /**
495      * This test verifies that when recovery is not applicable (typically when persistence is false) the RaftActor does
496      * not process recovery messages
497      *
498      * @throws Exception
499      */
500     @Test
501     public void testHandleRecoveryWhenDataPersistenceRecoveryNotApplicable() throws Exception {
502         new JavaTestKit(getSystem()) {
503             {
504                 String persistenceId = factory.generateActorId("leader-");
505
506                 DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
507
508                 config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
509
510                 TestActorRef<MockRaftActor> mockActorRef = factory.createTestActor(MockRaftActor.props(persistenceId,
511                         Collections.<String, String>emptyMap(), Optional.<ConfigParams>of(config), new DataPersistenceProviderMonitor()), persistenceId);
512
513                 MockRaftActor mockRaftActor = mockActorRef.underlyingActor();
514
515                 // Wait for akka's recovery to complete so it doesn't interfere.
516                 mockRaftActor.waitForRecoveryComplete();
517
518                 ByteString snapshotBytes = fromObject(Arrays.asList(
519                         new MockRaftActorContext.MockPayload("A"),
520                         new MockRaftActorContext.MockPayload("B"),
521                         new MockRaftActorContext.MockPayload("C"),
522                         new MockRaftActorContext.MockPayload("D")));
523
524                 Snapshot snapshot = Snapshot.create(snapshotBytes.toByteArray(),
525                         Lists.<ReplicatedLogEntry>newArrayList(), 3, 1, 3, 1);
526
527                 mockRaftActor.onReceiveRecover(new SnapshotOffer(new SnapshotMetadata(persistenceId, 100, 100), snapshot));
528
529                 verify(mockRaftActor.delegate, times(0)).applyRecoverySnapshot(any(byte[].class));
530
531                 mockRaftActor.onReceiveRecover(new ReplicatedLogImplEntry(0, 1, new MockRaftActorContext.MockPayload("A")));
532
533                 ReplicatedLog replicatedLog = mockRaftActor.getReplicatedLog();
534
535                 assertEquals("add replicated log entry", 0, replicatedLog.size());
536
537                 mockRaftActor.onReceiveRecover(new ReplicatedLogImplEntry(1, 1, new MockRaftActorContext.MockPayload("A")));
538
539                 assertEquals("add replicated log entry", 0, replicatedLog.size());
540
541                 mockRaftActor.onReceiveRecover(new ApplyLogEntries(1));
542
543                 assertEquals("commit index -1", -1, mockRaftActor.getRaftActorContext().getCommitIndex());
544
545                 mockRaftActor.onReceiveRecover(new RaftActor.DeleteEntries(2));
546
547                 assertEquals("remove log entries", 0, replicatedLog.size());
548
549                 mockRaftActor.onReceiveRecover(new RaftActor.UpdateElectionTerm(10, "foobar"));
550
551                 assertNotEquals("election term", 10, mockRaftActor.getRaftActorContext().getTermInformation().getCurrentTerm());
552                 assertNotEquals("voted for", "foobar", mockRaftActor.getRaftActorContext().getTermInformation().getVotedFor());
553
554                 mockRaftActor.onReceiveRecover(mock(RecoveryCompleted.class));
555             }};
556     }
557
558
559     @Test
560     public void testUpdatingElectionTermCallsDataPersistence() throws Exception {
561         new JavaTestKit(getSystem()) {
562             {
563                 String persistenceId = factory.generateActorId("leader-");
564
565                 DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
566
567                 config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
568
569                 CountDownLatch persistLatch = new CountDownLatch(1);
570                 DataPersistenceProviderMonitor dataPersistenceProviderMonitor = new DataPersistenceProviderMonitor();
571                 dataPersistenceProviderMonitor.setPersistLatch(persistLatch);
572
573                 TestActorRef<MockRaftActor> mockActorRef = factory.createTestActor(MockRaftActor.props(persistenceId,
574                         Collections.<String, String>emptyMap(), Optional.<ConfigParams>of(config), dataPersistenceProviderMonitor), persistenceId);
575
576                 MockRaftActor mockRaftActor = mockActorRef.underlyingActor();
577
578                 mockRaftActor.waitForInitializeBehaviorComplete();
579
580                 mockRaftActor.getRaftActorContext().getTermInformation().updateAndPersist(10, "foobar");
581
582                 assertEquals("Persist called", true, persistLatch.await(5, TimeUnit.SECONDS));
583             }
584         };
585     }
586
587     @Test
588     public void testAddingReplicatedLogEntryCallsDataPersistence() throws Exception {
589         new JavaTestKit(getSystem()) {
590             {
591                 String persistenceId = factory.generateActorId("leader-");
592
593                 DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
594
595                 config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
596
597                 DataPersistenceProvider dataPersistenceProvider = mock(DataPersistenceProvider.class);
598
599                 TestActorRef<MockRaftActor> mockActorRef = factory.createTestActor(MockRaftActor.props(persistenceId,
600                         Collections.<String, String>emptyMap(), Optional.<ConfigParams>of(config), dataPersistenceProvider), persistenceId);
601
602                 MockRaftActor mockRaftActor = mockActorRef.underlyingActor();
603
604                 mockRaftActor.waitForInitializeBehaviorComplete();
605
606                 MockRaftActorContext.MockReplicatedLogEntry logEntry = new MockRaftActorContext.MockReplicatedLogEntry(10, 10, mock(Payload.class));
607
608                 mockRaftActor.getRaftActorContext().getReplicatedLog().appendAndPersist(logEntry);
609
610                 verify(dataPersistenceProvider).persist(eq(logEntry), any(Procedure.class));
611             }
612         };
613     }
614
615     @Test
616     public void testRemovingReplicatedLogEntryCallsDataPersistence() throws Exception {
617         new JavaTestKit(getSystem()) {
618             {
619                 String persistenceId = factory.generateActorId("leader-");
620
621                 DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
622
623                 config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
624
625                 DataPersistenceProvider dataPersistenceProvider = mock(DataPersistenceProvider.class);
626
627                 TestActorRef<MockRaftActor> mockActorRef = factory.createTestActor(MockRaftActor.props(persistenceId,
628                         Collections.<String, String>emptyMap(), Optional.<ConfigParams>of(config), dataPersistenceProvider), persistenceId);
629
630                 MockRaftActor mockRaftActor = mockActorRef.underlyingActor();
631
632                 mockRaftActor.waitForInitializeBehaviorComplete();
633
634                 mockRaftActor.getReplicatedLog().appendAndPersist(new MockRaftActorContext.MockReplicatedLogEntry(1, 0, mock(Payload.class)));
635
636                 mockRaftActor.getRaftActorContext().getReplicatedLog().removeFromAndPersist(0);
637
638                 verify(dataPersistenceProvider, times(2)).persist(anyObject(), any(Procedure.class));
639             }
640         };
641     }
642
643     @Test
644     public void testApplyLogEntriesCallsDataPersistence() throws Exception {
645         new JavaTestKit(getSystem()) {
646             {
647                 String persistenceId = factory.generateActorId("leader-");
648
649                 DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
650
651                 config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
652
653                 DataPersistenceProvider dataPersistenceProvider = mock(DataPersistenceProvider.class);
654
655                 TestActorRef<MockRaftActor> mockActorRef = factory.createTestActor(MockRaftActor.props(persistenceId,
656                         Collections.<String, String>emptyMap(), Optional.<ConfigParams>of(config), dataPersistenceProvider), persistenceId);
657
658                 MockRaftActor mockRaftActor = mockActorRef.underlyingActor();
659
660                 mockRaftActor.waitForInitializeBehaviorComplete();
661
662                 mockRaftActor.onReceiveCommand(new ApplyLogEntries(10));
663
664                 verify(dataPersistenceProvider, times(1)).persist(anyObject(), any(Procedure.class));
665
666             }
667
668         };
669     }
670
671     @Test
672     public void testCaptureSnapshotReplyCallsDataPersistence() throws Exception {
673         new JavaTestKit(getSystem()) {
674             {
675                 String persistenceId = factory.generateActorId("leader-");
676
677                 DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
678
679                 config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
680
681                 DataPersistenceProvider dataPersistenceProvider = mock(DataPersistenceProvider.class);
682
683                 TestActorRef<MockRaftActor> mockActorRef = factory.createTestActor(
684                         MockRaftActor.props(persistenceId, Collections.<String, String>emptyMap(),
685                                 Optional.<ConfigParams>of(config), dataPersistenceProvider), persistenceId);
686
687                 MockRaftActor mockRaftActor = mockActorRef.underlyingActor();
688
689                 mockRaftActor.waitForInitializeBehaviorComplete();
690
691                 ByteString snapshotBytes = fromObject(Arrays.asList(
692                         new MockRaftActorContext.MockPayload("A"),
693                         new MockRaftActorContext.MockPayload("B"),
694                         new MockRaftActorContext.MockPayload("C"),
695                         new MockRaftActorContext.MockPayload("D")));
696
697                 mockRaftActor.onReceiveCommand(new CaptureSnapshot(-1, 1,-1, 1, -1, 1));
698
699                 RaftActorContext raftActorContext = mockRaftActor.getRaftActorContext();
700
701                 mockRaftActor.setCurrentBehavior(new Leader(raftActorContext));
702
703                 mockRaftActor.onReceiveCommand(new CaptureSnapshotReply(snapshotBytes.toByteArray()));
704
705                 verify(dataPersistenceProvider).saveSnapshot(anyObject());
706
707             }
708         };
709     }
710
711     @Test
712     public void testSaveSnapshotSuccessCallsDataPersistence() throws Exception {
713         new JavaTestKit(getSystem()) {
714             {
715                 String persistenceId = factory.generateActorId("leader-");
716
717                 DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
718
719                 config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
720
721                 DataPersistenceProvider dataPersistenceProvider = mock(DataPersistenceProvider.class);
722
723                 TestActorRef<MockRaftActor> mockActorRef = factory.createTestActor(MockRaftActor.props(persistenceId,
724                         Collections.<String, String>emptyMap(), Optional.<ConfigParams>of(config), dataPersistenceProvider), persistenceId);
725
726                 MockRaftActor mockRaftActor = mockActorRef.underlyingActor();
727
728                 mockRaftActor.waitForInitializeBehaviorComplete();
729
730                 mockRaftActor.getReplicatedLog().append(new MockRaftActorContext.MockReplicatedLogEntry(1, 0, mock(Payload.class)));
731                 mockRaftActor.getReplicatedLog().append(new MockRaftActorContext.MockReplicatedLogEntry(1, 1, mock(Payload.class)));
732                 mockRaftActor.getReplicatedLog().append(new MockRaftActorContext.MockReplicatedLogEntry(1, 2, mock(Payload.class)));
733                 mockRaftActor.getReplicatedLog().append(new MockRaftActorContext.MockReplicatedLogEntry(1, 3, mock(Payload.class)));
734                 mockRaftActor.getReplicatedLog().append(new MockRaftActorContext.MockReplicatedLogEntry(1, 4, mock(Payload.class)));
735
736                 ByteString snapshotBytes = fromObject(Arrays.asList(
737                         new MockRaftActorContext.MockPayload("A"),
738                         new MockRaftActorContext.MockPayload("B"),
739                         new MockRaftActorContext.MockPayload("C"),
740                         new MockRaftActorContext.MockPayload("D")));
741
742                 RaftActorContext raftActorContext = mockRaftActor.getRaftActorContext();
743                 mockRaftActor.setCurrentBehavior(new Follower(raftActorContext));
744
745                 long replicatedToAllIndex = 1;
746                 mockRaftActor.onReceiveCommand(new CaptureSnapshot(-1, 1, 2, 1, replicatedToAllIndex, 1));
747
748                 verify(mockRaftActor.delegate).createSnapshot();
749
750                 mockRaftActor.onReceiveCommand(new CaptureSnapshotReply(snapshotBytes.toByteArray()));
751
752                 mockRaftActor.onReceiveCommand(new SaveSnapshotSuccess(new SnapshotMetadata("foo", 100, 100)));
753
754                 verify(dataPersistenceProvider).deleteSnapshots(any(SnapshotSelectionCriteria.class));
755
756                 verify(dataPersistenceProvider).deleteMessages(100);
757
758                 assertEquals(3, mockRaftActor.getReplicatedLog().size());
759                 assertEquals(1, mockRaftActor.getCurrentBehavior().getReplicatedToAllIndex());
760
761                 assertNotNull(mockRaftActor.getReplicatedLog().get(2));
762                 assertNotNull(mockRaftActor.getReplicatedLog().get(3));
763                 assertNotNull(mockRaftActor.getReplicatedLog().get(4));
764
765                 // Index 2 will not be in the log because it was removed due to snapshotting
766                 assertNull(mockRaftActor.getReplicatedLog().get(1));
767                 assertNull(mockRaftActor.getReplicatedLog().get(0));
768
769             }
770         };
771     }
772
773     @Test
774     public void testApplyState() throws Exception {
775
776         new JavaTestKit(getSystem()) {
777             {
778                 String persistenceId = factory.generateActorId("leader-");
779
780                 DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
781
782                 config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
783
784                 DataPersistenceProvider dataPersistenceProvider = mock(DataPersistenceProvider.class);
785
786                 TestActorRef<MockRaftActor> mockActorRef = factory.createTestActor(MockRaftActor.props(persistenceId,
787                         Collections.<String, String>emptyMap(), Optional.<ConfigParams>of(config), dataPersistenceProvider), persistenceId);
788
789                 MockRaftActor mockRaftActor = mockActorRef.underlyingActor();
790
791                 mockRaftActor.waitForInitializeBehaviorComplete();
792
793                 ReplicatedLogEntry entry = new MockRaftActorContext.MockReplicatedLogEntry(1, 5,
794                         new MockRaftActorContext.MockPayload("F"));
795
796                 mockRaftActor.onReceiveCommand(new ApplyState(mockActorRef, "apply-state", entry));
797
798                 verify(mockRaftActor.delegate).applyState(eq(mockActorRef), eq("apply-state"), anyObject());
799
800             }
801         };
802     }
803
804     @Test
805     public void testApplySnapshot() throws Exception {
806         new JavaTestKit(getSystem()) {
807             {
808                 String persistenceId = factory.generateActorId("leader-");
809
810                 DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
811
812                 config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
813
814                 DataPersistenceProviderMonitor dataPersistenceProviderMonitor = new DataPersistenceProviderMonitor();
815
816                 TestActorRef<MockRaftActor> mockActorRef = factory.createTestActor(MockRaftActor.props(persistenceId,
817                         Collections.<String, String>emptyMap(), Optional.<ConfigParams>of(config), dataPersistenceProviderMonitor), persistenceId);
818
819                 MockRaftActor mockRaftActor = mockActorRef.underlyingActor();
820
821                 mockRaftActor.waitForInitializeBehaviorComplete();
822
823                 ReplicatedLog oldReplicatedLog = mockRaftActor.getReplicatedLog();
824
825                 oldReplicatedLog.append(new MockRaftActorContext.MockReplicatedLogEntry(1, 0, mock(Payload.class)));
826                 oldReplicatedLog.append(new MockRaftActorContext.MockReplicatedLogEntry(1, 1, mock(Payload.class)));
827                 oldReplicatedLog.append(
828                         new MockRaftActorContext.MockReplicatedLogEntry(1, 2,
829                                 mock(Payload.class)));
830
831                 ByteString snapshotBytes = fromObject(Arrays.asList(
832                         new MockRaftActorContext.MockPayload("A"),
833                         new MockRaftActorContext.MockPayload("B"),
834                         new MockRaftActorContext.MockPayload("C"),
835                         new MockRaftActorContext.MockPayload("D")));
836
837                 Snapshot snapshot = mock(Snapshot.class);
838
839                 doReturn(snapshotBytes.toByteArray()).when(snapshot).getState();
840
841                 doReturn(3L).when(snapshot).getLastAppliedIndex();
842
843                 mockRaftActor.onReceiveCommand(new ApplySnapshot(snapshot));
844
845                 verify(mockRaftActor.delegate).applySnapshot(eq(snapshot.getState()));
846
847                 assertTrue("The replicatedLog should have changed",
848                         oldReplicatedLog != mockRaftActor.getReplicatedLog());
849
850                 assertEquals("lastApplied should be same as in the snapshot",
851                         (Long) 3L, mockRaftActor.getLastApplied());
852
853                 assertEquals(0, mockRaftActor.getReplicatedLog().size());
854
855             }
856         };
857     }
858
859     @Test
860     public void testSaveSnapshotFailure() throws Exception {
861         new JavaTestKit(getSystem()) {
862             {
863                 String persistenceId = factory.generateActorId("leader-");
864
865                 DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
866
867                 config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
868
869                 DataPersistenceProviderMonitor dataPersistenceProviderMonitor = new DataPersistenceProviderMonitor();
870
871                 TestActorRef<MockRaftActor> mockActorRef = factory.createTestActor(MockRaftActor.props(persistenceId,
872                         Collections.<String, String>emptyMap(), Optional.<ConfigParams>of(config), dataPersistenceProviderMonitor), persistenceId);
873
874                 MockRaftActor mockRaftActor = mockActorRef.underlyingActor();
875
876                 mockRaftActor.waitForInitializeBehaviorComplete();
877
878                 ByteString snapshotBytes = fromObject(Arrays.asList(
879                         new MockRaftActorContext.MockPayload("A"),
880                         new MockRaftActorContext.MockPayload("B"),
881                         new MockRaftActorContext.MockPayload("C"),
882                         new MockRaftActorContext.MockPayload("D")));
883
884                 RaftActorContext raftActorContext = mockRaftActor.getRaftActorContext();
885
886                 mockRaftActor.setCurrentBehavior(new Leader(raftActorContext));
887
888                 mockRaftActor.onReceiveCommand(new CaptureSnapshot(-1, 1, -1, 1, -1, 1));
889
890                 mockRaftActor.onReceiveCommand(new CaptureSnapshotReply(snapshotBytes.toByteArray()));
891
892                 mockRaftActor.onReceiveCommand(new SaveSnapshotFailure(new SnapshotMetadata("foobar", 10L, 1234L),
893                         new Exception()));
894
895                 assertEquals("Snapshot index should not have advanced because save snapshot failed", -1,
896                         mockRaftActor.getReplicatedLog().getSnapshotIndex());
897
898             }
899         };
900     }
901
902     @Test
903     public void testRaftRoleChangeNotifier() throws Exception {
904         new JavaTestKit(getSystem()) {{
905             ActorRef notifierActor = factory.createActor(Props.create(MessageCollectorActor.class));
906             MessageCollectorActor.waitUntilReady(notifierActor);
907
908             DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
909             long heartBeatInterval = 100;
910             config.setHeartBeatInterval(FiniteDuration.create(heartBeatInterval, TimeUnit.MILLISECONDS));
911             config.setElectionTimeoutFactor(1);
912
913             String persistenceId = factory.generateActorId("notifier-");
914
915             factory.createTestActor(MockRaftActor.props(persistenceId,
916                     Collections.<String, String>emptyMap(), Optional.<ConfigParams>of(config), notifierActor), persistenceId);
917
918             List<RoleChanged> matches =  null;
919             for(int i = 0; i < 5000 / heartBeatInterval; i++) {
920                 matches = MessageCollectorActor.getAllMatching(notifierActor, RoleChanged.class);
921                 assertNotNull(matches);
922                 if(matches.size() == 3) {
923                     break;
924                 }
925                 Uninterruptibles.sleepUninterruptibly(heartBeatInterval, TimeUnit.MILLISECONDS);
926             }
927
928             assertEquals(3, matches.size());
929
930             // check if the notifier got a role change from null to Follower
931             RoleChanged raftRoleChanged = matches.get(0);
932             assertEquals(persistenceId, raftRoleChanged.getMemberId());
933             assertNull(raftRoleChanged.getOldRole());
934             assertEquals(RaftState.Follower.name(), raftRoleChanged.getNewRole());
935
936             // check if the notifier got a role change from Follower to Candidate
937             raftRoleChanged = matches.get(1);
938             assertEquals(persistenceId, raftRoleChanged.getMemberId());
939             assertEquals(RaftState.Follower.name(), raftRoleChanged.getOldRole());
940             assertEquals(RaftState.Candidate.name(), raftRoleChanged.getNewRole());
941
942             // check if the notifier got a role change from Candidate to Leader
943             raftRoleChanged = matches.get(2);
944             assertEquals(persistenceId, raftRoleChanged.getMemberId());
945             assertEquals(RaftState.Candidate.name(), raftRoleChanged.getOldRole());
946             assertEquals(RaftState.Leader.name(), raftRoleChanged.getNewRole());
947         }};
948     }
949
950     @Test
951     public void testFakeSnapshotsForLeaderWithInRealSnapshots() throws Exception {
952         new JavaTestKit(getSystem()) {
953             {
954                 String persistenceId = factory.generateActorId("leader-");
955                 String follower1Id = factory.generateActorId("follower-");
956
957                 ActorRef followerActor1 =
958                         factory.createActor(Props.create(MessageCollectorActor.class));
959
960                 DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
961                 config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
962                 config.setIsolatedLeaderCheckInterval(new FiniteDuration(1, TimeUnit.DAYS));
963
964                 DataPersistenceProvider dataPersistenceProvider = mock(DataPersistenceProvider.class);
965
966                 Map<String, String> peerAddresses = new HashMap<>();
967                 peerAddresses.put(follower1Id, followerActor1.path().toString());
968
969                 TestActorRef<MockRaftActor> mockActorRef = factory.createTestActor(
970                         MockRaftActor.props(persistenceId, peerAddresses,
971                                 Optional.<ConfigParams>of(config), dataPersistenceProvider), persistenceId);
972
973                 MockRaftActor leaderActor = mockActorRef.underlyingActor();
974
975                 leaderActor.getRaftActorContext().setCommitIndex(4);
976                 leaderActor.getRaftActorContext().setLastApplied(4);
977                 leaderActor.getRaftActorContext().getTermInformation().update(1, persistenceId);
978
979                 leaderActor.waitForInitializeBehaviorComplete();
980
981                 // create 8 entries in the log - 0 to 4 are applied and will get picked up as part of the capture snapshot
982
983                 Leader leader = new Leader(leaderActor.getRaftActorContext());
984                 leaderActor.setCurrentBehavior(leader);
985                 assertEquals(RaftState.Leader, leaderActor.getCurrentBehavior().state());
986
987                 MockRaftActorContext.MockReplicatedLogBuilder logBuilder = new MockRaftActorContext.MockReplicatedLogBuilder();
988                 leaderActor.getRaftActorContext().setReplicatedLog(logBuilder.createEntries(0, 8, 1).build());
989
990                 assertEquals(8, leaderActor.getReplicatedLog().size());
991
992                 leaderActor.onReceiveCommand(new CaptureSnapshot(6, 1, 4, 1, 4, 1));
993
994                 leaderActor.getRaftActorContext().setSnapshotCaptureInitiated(true);
995                 verify(leaderActor.delegate).createSnapshot();
996
997                 assertEquals(8, leaderActor.getReplicatedLog().size());
998
999                 assertEquals(RaftState.Leader, leaderActor.getCurrentBehavior().state());
1000                 //fake snapshot on index 5
1001                 leaderActor.onReceiveCommand(new AppendEntriesReply(follower1Id, 1, true, 5, 1));
1002
1003                 assertEquals(8, leaderActor.getReplicatedLog().size());
1004
1005                 //fake snapshot on index 6
1006                 assertEquals(RaftState.Leader, leaderActor.getCurrentBehavior().state());
1007                 leaderActor.onReceiveCommand(new AppendEntriesReply(follower1Id, 1, true, 6, 1));
1008                 assertEquals(8, leaderActor.getReplicatedLog().size());
1009
1010                 assertEquals(RaftState.Leader, leaderActor.getCurrentBehavior().state());
1011
1012                 assertEquals(8, leaderActor.getReplicatedLog().size());
1013
1014                 ByteString snapshotBytes = fromObject(Arrays.asList(
1015                         new MockRaftActorContext.MockPayload("foo-0"),
1016                         new MockRaftActorContext.MockPayload("foo-1"),
1017                         new MockRaftActorContext.MockPayload("foo-2"),
1018                         new MockRaftActorContext.MockPayload("foo-3"),
1019                         new MockRaftActorContext.MockPayload("foo-4")));
1020                 leaderActor.onReceiveCommand(new CaptureSnapshotReply(snapshotBytes.toByteArray()));
1021                 assertFalse(leaderActor.getRaftActorContext().isSnapshotCaptureInitiated());
1022
1023                 // capture snapshot reply should remove the snapshotted entries only
1024                 assertEquals(3, leaderActor.getReplicatedLog().size());
1025                 assertEquals(7, leaderActor.getReplicatedLog().lastIndex());
1026
1027                 // add another non-replicated entry
1028                 leaderActor.getReplicatedLog().append(
1029                         new ReplicatedLogImplEntry(8, 1, new MockRaftActorContext.MockPayload("foo-8")));
1030
1031                 //fake snapshot on index 7, since lastApplied = 7 , we would keep the last applied
1032                 leaderActor.onReceiveCommand(new AppendEntriesReply(follower1Id, 1, true, 7, 1));
1033                 assertEquals(2, leaderActor.getReplicatedLog().size());
1034                 assertEquals(8, leaderActor.getReplicatedLog().lastIndex());
1035
1036             }
1037         };
1038     }
1039
1040     @Test
1041     public void testFakeSnapshotsForFollowerWithInRealSnapshots() throws Exception {
1042         new JavaTestKit(getSystem()) {
1043             {
1044                 String persistenceId = factory.generateActorId("follower-");
1045                 String leaderId = factory.generateActorId("leader-");
1046
1047
1048                 ActorRef leaderActor1 =
1049                         factory.createActor(Props.create(MessageCollectorActor.class));
1050
1051                 DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
1052                 config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
1053                 config.setIsolatedLeaderCheckInterval(new FiniteDuration(1, TimeUnit.DAYS));
1054
1055                 DataPersistenceProvider dataPersistenceProvider = mock(DataPersistenceProvider.class);
1056
1057                 Map<String, String> peerAddresses = new HashMap<>();
1058                 peerAddresses.put(leaderId, leaderActor1.path().toString());
1059
1060                 TestActorRef<MockRaftActor> mockActorRef = factory.createTestActor(
1061                         MockRaftActor.props(persistenceId, peerAddresses,
1062                                 Optional.<ConfigParams>of(config), dataPersistenceProvider), persistenceId);
1063
1064                 MockRaftActor followerActor = mockActorRef.underlyingActor();
1065                 followerActor.getRaftActorContext().setCommitIndex(4);
1066                 followerActor.getRaftActorContext().setLastApplied(4);
1067                 followerActor.getRaftActorContext().getTermInformation().update(1, persistenceId);
1068
1069                 followerActor.waitForInitializeBehaviorComplete();
1070
1071
1072                 Follower follower = new Follower(followerActor.getRaftActorContext());
1073                 followerActor.setCurrentBehavior(follower);
1074                 assertEquals(RaftState.Follower, followerActor.getCurrentBehavior().state());
1075
1076                 // create 6 entries in the log - 0 to 4 are applied and will get picked up as part of the capture snapshot
1077                 MockRaftActorContext.MockReplicatedLogBuilder logBuilder = new MockRaftActorContext.MockReplicatedLogBuilder();
1078                 followerActor.getRaftActorContext().setReplicatedLog(logBuilder.createEntries(0, 6, 1).build());
1079
1080                 // log has indices 0-5
1081                 assertEquals(6, followerActor.getReplicatedLog().size());
1082
1083                 //snapshot on 4
1084                 followerActor.onReceiveCommand(new CaptureSnapshot(5, 1, 4, 1, 4, 1));
1085
1086                 followerActor.getRaftActorContext().setSnapshotCaptureInitiated(true);
1087                 verify(followerActor.delegate).createSnapshot();
1088
1089                 assertEquals(6, followerActor.getReplicatedLog().size());
1090
1091                 //fake snapshot on index 6
1092                 List<ReplicatedLogEntry> entries =
1093                         Arrays.asList(
1094                                 (ReplicatedLogEntry) new MockRaftActorContext.MockReplicatedLogEntry(1, 6,
1095                                         new MockRaftActorContext.MockPayload("foo-6"))
1096                         );
1097                 followerActor.onReceiveCommand(new AppendEntries(1, leaderId, 5, 1, entries, 5, 5));
1098                 assertEquals(7, followerActor.getReplicatedLog().size());
1099
1100                 //fake snapshot on index 7
1101                 assertEquals(RaftState.Follower, followerActor.getCurrentBehavior().state());
1102
1103                 entries =
1104                         Arrays.asList(
1105                                 (ReplicatedLogEntry) new MockRaftActorContext.MockReplicatedLogEntry(1, 7,
1106                                         new MockRaftActorContext.MockPayload("foo-7"))
1107                         );
1108                 followerActor.onReceiveCommand(new AppendEntries(1, leaderId, 6, 1, entries, 6, 6));
1109                 assertEquals(8, followerActor.getReplicatedLog().size());
1110
1111                 assertEquals(RaftState.Follower, followerActor.getCurrentBehavior().state());
1112
1113
1114                 ByteString snapshotBytes = fromObject(Arrays.asList(
1115                         new MockRaftActorContext.MockPayload("foo-0"),
1116                         new MockRaftActorContext.MockPayload("foo-1"),
1117                         new MockRaftActorContext.MockPayload("foo-2"),
1118                         new MockRaftActorContext.MockPayload("foo-3"),
1119                         new MockRaftActorContext.MockPayload("foo-4")));
1120                 followerActor.onReceiveCommand(new CaptureSnapshotReply(snapshotBytes.toByteArray()));
1121                 assertFalse(followerActor.getRaftActorContext().isSnapshotCaptureInitiated());
1122
1123                 // capture snapshot reply should remove the snapshotted entries only till replicatedToAllIndex
1124                 assertEquals(3, followerActor.getReplicatedLog().size()); //indexes 5,6,7 left in the log
1125                 assertEquals(7, followerActor.getReplicatedLog().lastIndex());
1126
1127                 entries =
1128                         Arrays.asList(
1129                                 (ReplicatedLogEntry) new MockRaftActorContext.MockReplicatedLogEntry(1, 8,
1130                                         new MockRaftActorContext.MockPayload("foo-7"))
1131                         );
1132                 // send an additional entry 8 with leaderCommit = 7
1133                 followerActor.onReceiveCommand(new AppendEntries(1, leaderId, 7, 1, entries, 7, 7));
1134
1135                 // 7 and 8, as lastapplied is 7
1136                 assertEquals(2, followerActor.getReplicatedLog().size());
1137
1138             }
1139         };
1140     }
1141
1142     @Test
1143     public void testFakeSnapshotsForLeaderWithInInitiateSnapshots() throws Exception {
1144         new JavaTestKit(getSystem()) {
1145             {
1146                 String persistenceId = factory.generateActorId("leader-");
1147                 String follower1Id = factory.generateActorId("follower-");
1148                 String follower2Id = factory.generateActorId("follower-");
1149
1150                 ActorRef followerActor1 =
1151                         factory.createActor(Props.create(MessageCollectorActor.class), follower1Id);
1152                 ActorRef followerActor2 =
1153                         factory.createActor(Props.create(MessageCollectorActor.class), follower2Id);
1154
1155                 DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
1156                 config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
1157                 config.setIsolatedLeaderCheckInterval(new FiniteDuration(1, TimeUnit.DAYS));
1158
1159                 DataPersistenceProvider dataPersistenceProvider = mock(DataPersistenceProvider.class);
1160
1161                 Map<String, String> peerAddresses = new HashMap<>();
1162                 peerAddresses.put(follower1Id, followerActor1.path().toString());
1163                 peerAddresses.put(follower2Id, followerActor2.path().toString());
1164
1165                 TestActorRef<MockRaftActor> mockActorRef = factory.createTestActor(
1166                         MockRaftActor.props(persistenceId, peerAddresses,
1167                                 Optional.<ConfigParams>of(config), dataPersistenceProvider), persistenceId);
1168
1169                 MockRaftActor leaderActor = mockActorRef.underlyingActor();
1170                 leaderActor.getRaftActorContext().setCommitIndex(9);
1171                 leaderActor.getRaftActorContext().setLastApplied(9);
1172                 leaderActor.getRaftActorContext().getTermInformation().update(1, persistenceId);
1173
1174                 leaderActor.waitForInitializeBehaviorComplete();
1175
1176                 Leader leader = new Leader(leaderActor.getRaftActorContext());
1177                 leaderActor.setCurrentBehavior(leader);
1178                 assertEquals(RaftState.Leader, leaderActor.getCurrentBehavior().state());
1179
1180                 // create 5 entries in the log
1181                 MockRaftActorContext.MockReplicatedLogBuilder logBuilder = new MockRaftActorContext.MockReplicatedLogBuilder();
1182                 leaderActor.getRaftActorContext().setReplicatedLog(logBuilder.createEntries(5, 10, 1).build());
1183
1184                 //set the snapshot index to 4 , 0 to 4 are snapshotted
1185                 leaderActor.getRaftActorContext().getReplicatedLog().setSnapshotIndex(4);
1186                 //setting replicatedToAllIndex = 9, for the log to clear
1187                 leader.setReplicatedToAllIndex(9);
1188                 assertEquals(5, leaderActor.getReplicatedLog().size());
1189                 assertEquals(RaftState.Leader, leaderActor.getCurrentBehavior().state());
1190
1191                 leaderActor.onReceiveCommand(new AppendEntriesReply(follower1Id, 1, true, 9, 1));
1192                 assertEquals(5, leaderActor.getReplicatedLog().size());
1193                 assertEquals(RaftState.Leader, leaderActor.getCurrentBehavior().state());
1194
1195                 // set the 2nd follower nextIndex to 1 which has been snapshotted
1196                 leaderActor.onReceiveCommand(new AppendEntriesReply(follower2Id, 1, true, 0, 1));
1197                 assertEquals(5, leaderActor.getReplicatedLog().size());
1198                 assertEquals(RaftState.Leader, leaderActor.getCurrentBehavior().state());
1199
1200                 // simulate a real snapshot
1201                 leaderActor.onReceiveCommand(new SendHeartBeat());
1202                 assertEquals(5, leaderActor.getReplicatedLog().size());
1203                 assertEquals(String.format("expected to be Leader but was %s. Current Leader = %s ",
1204                         leaderActor.getCurrentBehavior().state(), leaderActor.getLeaderId())
1205                         , RaftState.Leader, leaderActor.getCurrentBehavior().state());
1206
1207
1208                 //reply from a slow follower does not initiate a fake snapshot
1209                 leaderActor.onReceiveCommand(new AppendEntriesReply(follower2Id, 1, true, 9, 1));
1210                 assertEquals("Fake snapshot should not happen when Initiate is in progress", 5, leaderActor.getReplicatedLog().size());
1211
1212                 ByteString snapshotBytes = fromObject(Arrays.asList(
1213                         new MockRaftActorContext.MockPayload("foo-0"),
1214                         new MockRaftActorContext.MockPayload("foo-1"),
1215                         new MockRaftActorContext.MockPayload("foo-2"),
1216                         new MockRaftActorContext.MockPayload("foo-3"),
1217                         new MockRaftActorContext.MockPayload("foo-4")));
1218                 leaderActor.onReceiveCommand(new CaptureSnapshotReply(snapshotBytes.toByteArray()));
1219                 assertFalse(leaderActor.getRaftActorContext().isSnapshotCaptureInitiated());
1220
1221                 assertEquals("Real snapshot didn't clear the log till replicatedToAllIndex", 0, leaderActor.getReplicatedLog().size());
1222
1223                 //reply from a slow follower after should not raise errors
1224                 leaderActor.onReceiveCommand(new AppendEntriesReply(follower2Id, 1, true, 5, 1));
1225                 assertEquals(0, leaderActor.getReplicatedLog().size());
1226             }
1227         };
1228     }
1229
1230
1231     private static class NonPersistentProvider implements DataPersistenceProvider {
1232         @Override
1233         public boolean isRecoveryApplicable() {
1234             return false;
1235         }
1236
1237         @Override
1238         public <T> void persist(T o, Procedure<T> procedure) {
1239             try {
1240                 procedure.apply(o);
1241             } catch (Exception e) {
1242                 e.printStackTrace();
1243             }
1244         }
1245
1246         @Override
1247         public void saveSnapshot(Object o) {
1248
1249         }
1250
1251         @Override
1252         public void deleteSnapshots(SnapshotSelectionCriteria criteria) {
1253
1254         }
1255
1256         @Override
1257         public void deleteMessages(long sequenceNumber) {
1258
1259         }
1260     }
1261
1262     @Test
1263     public void testRealSnapshotWhenReplicatedToAllIndexMinusOne() throws Exception {
1264         new JavaTestKit(getSystem()) {{
1265             String persistenceId = factory.generateActorId("leader-");
1266             DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
1267             config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
1268             config.setIsolatedLeaderCheckInterval(new FiniteDuration(1, TimeUnit.DAYS));
1269             config.setSnapshotBatchCount(5);
1270
1271             DataPersistenceProvider dataPersistenceProvider = new NonPersistentProvider();
1272
1273             Map<String, String> peerAddresses = new HashMap<>();
1274
1275             TestActorRef<MockRaftActor> mockActorRef = factory.createTestActor(
1276                     MockRaftActor.props(persistenceId, peerAddresses,
1277                             Optional.<ConfigParams>of(config), dataPersistenceProvider), persistenceId);
1278
1279             MockRaftActor leaderActor = mockActorRef.underlyingActor();
1280             leaderActor.getRaftActorContext().setCommitIndex(3);
1281             leaderActor.getRaftActorContext().setLastApplied(3);
1282             leaderActor.getRaftActorContext().getTermInformation().update(1, persistenceId);
1283
1284             leaderActor.waitForInitializeBehaviorComplete();
1285             for(int i=0;i< 4;i++) {
1286                 leaderActor.getReplicatedLog()
1287                         .append(new MockRaftActorContext.MockReplicatedLogEntry(1, i,
1288                                 new MockRaftActorContext.MockPayload("A")));
1289             }
1290
1291             Leader leader = new Leader(leaderActor.getRaftActorContext());
1292             leaderActor.setCurrentBehavior(leader);
1293             assertEquals(RaftState.Leader, leaderActor.getCurrentBehavior().state());
1294
1295             // Persist another entry (this will cause a CaptureSnapshot to be triggered
1296             leaderActor.persistData(mockActorRef, "x", new MockRaftActorContext.MockPayload("duh"));
1297
1298             // Now send a CaptureSnapshotReply
1299             mockActorRef.tell(new CaptureSnapshotReply(fromObject("foo").toByteArray()), mockActorRef);
1300
1301             // Trimming log in this scenario is a no-op
1302             assertEquals(-1, leaderActor.getReplicatedLog().getSnapshotIndex());
1303             assertFalse(leaderActor.getRaftActorContext().isSnapshotCaptureInitiated());
1304             assertEquals(-1, leader.getReplicatedToAllIndex());
1305
1306         }};
1307     }
1308
1309     @Test
1310     public void testRealSnapshotWhenReplicatedToAllIndexNotInReplicatedLog() throws Exception {
1311         new JavaTestKit(getSystem()) {{
1312             String persistenceId = factory.generateActorId("leader-");
1313             DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
1314             config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
1315             config.setIsolatedLeaderCheckInterval(new FiniteDuration(1, TimeUnit.DAYS));
1316             config.setSnapshotBatchCount(5);
1317
1318             DataPersistenceProvider dataPersistenceProvider = new NonPersistentProvider();
1319
1320             Map<String, String> peerAddresses = new HashMap<>();
1321
1322             TestActorRef<MockRaftActor> mockActorRef = factory.createTestActor(
1323                     MockRaftActor.props(persistenceId, peerAddresses,
1324                             Optional.<ConfigParams>of(config), dataPersistenceProvider), persistenceId);
1325
1326             MockRaftActor leaderActor = mockActorRef.underlyingActor();
1327             leaderActor.getRaftActorContext().setCommitIndex(3);
1328             leaderActor.getRaftActorContext().setLastApplied(3);
1329             leaderActor.getRaftActorContext().getTermInformation().update(1, persistenceId);
1330             leaderActor.getReplicatedLog().setSnapshotIndex(3);
1331
1332             leaderActor.waitForInitializeBehaviorComplete();
1333             Leader leader = new Leader(leaderActor.getRaftActorContext());
1334             leaderActor.setCurrentBehavior(leader);
1335             leader.setReplicatedToAllIndex(3);
1336             assertEquals(RaftState.Leader, leaderActor.getCurrentBehavior().state());
1337
1338             // Persist another entry (this will cause a CaptureSnapshot to be triggered
1339             leaderActor.persistData(mockActorRef, "x", new MockRaftActorContext.MockPayload("duh"));
1340
1341             // Now send a CaptureSnapshotReply
1342             mockActorRef.tell(new CaptureSnapshotReply(fromObject("foo").toByteArray()), mockActorRef);
1343
1344             // Trimming log in this scenario is a no-op
1345             assertEquals(3, leaderActor.getReplicatedLog().getSnapshotIndex());
1346             assertFalse(leaderActor.getRaftActorContext().isSnapshotCaptureInitiated());
1347             assertEquals(3, leader.getReplicatedToAllIndex());
1348
1349         }};
1350     }
1351
1352     private ByteString fromObject(Object snapshot) throws Exception {
1353         ByteArrayOutputStream b = null;
1354         ObjectOutputStream o = null;
1355         try {
1356             b = new ByteArrayOutputStream();
1357             o = new ObjectOutputStream(b);
1358             o.writeObject(snapshot);
1359             byte[] snapshotBytes = b.toByteArray();
1360             return ByteString.copyFrom(snapshotBytes);
1361         } finally {
1362             if (o != null) {
1363                 o.flush();
1364                 o.close();
1365             }
1366             if (b != null) {
1367                 b.close();
1368             }
1369         }
1370     }
1371
1372 }

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