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

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