7654648840bd26cdb1e838b21317c32eb0efc6f7
[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.ApplySnapshot;
67 import org.opendaylight.controller.cluster.raft.base.messages.ApplyState;
68 import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshot;
69 import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshotReply;
70 import org.opendaylight.controller.cluster.raft.base.messages.LeaderTransitioning;
71 import org.opendaylight.controller.cluster.raft.base.messages.SendHeartBeat;
72 import org.opendaylight.controller.cluster.raft.base.messages.SwitchBehavior;
73 import org.opendaylight.controller.cluster.raft.behaviors.Follower;
74 import org.opendaylight.controller.cluster.raft.behaviors.Leader;
75 import org.opendaylight.controller.cluster.raft.behaviors.RaftActorBehavior;
76 import org.opendaylight.controller.cluster.raft.client.messages.GetSnapshot;
77 import org.opendaylight.controller.cluster.raft.client.messages.GetSnapshotReply;
78 import org.opendaylight.controller.cluster.raft.messages.AppendEntries;
79 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
80 import org.opendaylight.controller.cluster.raft.persisted.ApplyJournalEntries;
81 import org.opendaylight.controller.cluster.raft.persisted.DeleteEntries;
82 import org.opendaylight.controller.cluster.raft.persisted.ServerConfigurationPayload;
83 import org.opendaylight.controller.cluster.raft.persisted.ServerInfo;
84 import org.opendaylight.controller.cluster.raft.persisted.UpdateElectionTerm;
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         UpdateElectionTerm updateElectionTerm = new UpdateElectionTerm(5, "member2");
316         mockRaftActor.handleRecover(updateElectionTerm);
317
318         verify(mockSupport).handleRecoveryMessage(same(snapshotOffer), any(PersistentDataProvider.class));
319         verify(mockSupport).handleRecoveryMessage(same(logEntry), any(PersistentDataProvider.class));
320         verify(mockSupport).handleRecoveryMessage(same(applyJournalEntries), any(PersistentDataProvider.class));
321         verify(mockSupport).handleRecoveryMessage(same(deleteEntries), any(PersistentDataProvider.class));
322         verify(mockSupport).handleRecoveryMessage(same(updateElectionTerm), any(PersistentDataProvider.class));
323     }
324
325     @Test
326     public void testRaftActorForwardsToRaftActorSnapshotMessageSupport() {
327         String persistenceId = factory.generateActorId("leader-");
328
329         DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
330
331         config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
332
333         RaftActorSnapshotMessageSupport mockSupport = mock(RaftActorSnapshotMessageSupport.class);
334
335         TestActorRef<MockRaftActor> mockActorRef = factory.createTestActor(MockRaftActor.builder().id(persistenceId).
336                 config(config).snapshotMessageSupport(mockSupport).props());
337
338         MockRaftActor mockRaftActor = mockActorRef.underlyingActor();
339
340         // Wait for akka's recovery to complete so it doesn't interfere.
341         mockRaftActor.waitForRecoveryComplete();
342
343         ApplySnapshot applySnapshot = new ApplySnapshot(mock(Snapshot.class));
344         doReturn(true).when(mockSupport).handleSnapshotMessage(same(applySnapshot), any(ActorRef.class));
345         mockRaftActor.handleCommand(applySnapshot);
346
347         CaptureSnapshot captureSnapshot = new CaptureSnapshot(1, 1, 1, 1, 0, 1, null);
348         doReturn(true).when(mockSupport).handleSnapshotMessage(same(captureSnapshot), any(ActorRef.class));
349         mockRaftActor.handleCommand(captureSnapshot);
350
351         CaptureSnapshotReply captureSnapshotReply = new CaptureSnapshotReply(new byte[0]);
352         doReturn(true).when(mockSupport).handleSnapshotMessage(same(captureSnapshotReply), any(ActorRef.class));
353         mockRaftActor.handleCommand(captureSnapshotReply);
354
355         SaveSnapshotSuccess saveSnapshotSuccess = new SaveSnapshotSuccess(new SnapshotMetadata("", 0L, 0L));
356         doReturn(true).when(mockSupport).handleSnapshotMessage(same(saveSnapshotSuccess), any(ActorRef.class));
357         mockRaftActor.handleCommand(saveSnapshotSuccess);
358
359         SaveSnapshotFailure saveSnapshotFailure = new SaveSnapshotFailure(new SnapshotMetadata("", 0L, 0L), new Throwable());
360         doReturn(true).when(mockSupport).handleSnapshotMessage(same(saveSnapshotFailure), any(ActorRef.class));
361         mockRaftActor.handleCommand(saveSnapshotFailure);
362
363         doReturn(true).when(mockSupport).handleSnapshotMessage(same(RaftActorSnapshotMessageSupport.COMMIT_SNAPSHOT),
364                 any(ActorRef.class));
365         mockRaftActor.handleCommand(RaftActorSnapshotMessageSupport.COMMIT_SNAPSHOT);
366
367         doReturn(true).when(mockSupport).handleSnapshotMessage(same(GetSnapshot.INSTANCE), any(ActorRef.class));
368         mockRaftActor.handleCommand(GetSnapshot.INSTANCE);
369
370         verify(mockSupport).handleSnapshotMessage(same(applySnapshot), any(ActorRef.class));
371         verify(mockSupport).handleSnapshotMessage(same(captureSnapshot), any(ActorRef.class));
372         verify(mockSupport).handleSnapshotMessage(same(captureSnapshotReply), any(ActorRef.class));
373         verify(mockSupport).handleSnapshotMessage(same(saveSnapshotSuccess), any(ActorRef.class));
374         verify(mockSupport).handleSnapshotMessage(same(saveSnapshotFailure), any(ActorRef.class));
375         verify(mockSupport).handleSnapshotMessage(same(RaftActorSnapshotMessageSupport.COMMIT_SNAPSHOT),
376                 any(ActorRef.class));
377         verify(mockSupport).handleSnapshotMessage(same(GetSnapshot.INSTANCE), any(ActorRef.class));
378     }
379
380     @Test
381     public void testApplyJournalEntriesCallsDataPersistence() throws Exception {
382         new JavaTestKit(getSystem()) {
383             {
384                 String persistenceId = factory.generateActorId("leader-");
385
386                 DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
387
388                 config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
389
390                 DataPersistenceProvider dataPersistenceProvider = mock(DataPersistenceProvider.class);
391
392                 TestActorRef<MockRaftActor> mockActorRef = factory.createTestActor(MockRaftActor.props(persistenceId,
393                         Collections.<String, String>emptyMap(), config, dataPersistenceProvider), persistenceId);
394
395                 MockRaftActor mockRaftActor = mockActorRef.underlyingActor();
396
397                 mockRaftActor.waitForInitializeBehaviorComplete();
398
399                 mockRaftActor.waitUntilLeader();
400
401                 mockRaftActor.onReceiveCommand(new ApplyJournalEntries(10));
402
403                 verify(dataPersistenceProvider).persist(any(ApplyJournalEntries.class), any(Procedure.class));
404
405             }
406
407         };
408     }
409
410     @Test
411     public void testApplyState() throws Exception {
412
413         new JavaTestKit(getSystem()) {
414             {
415                 String persistenceId = factory.generateActorId("leader-");
416
417                 DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
418
419                 config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
420
421                 DataPersistenceProvider dataPersistenceProvider = mock(DataPersistenceProvider.class);
422
423                 TestActorRef<MockRaftActor> mockActorRef = factory.createTestActor(MockRaftActor.props(persistenceId,
424                         Collections.<String, String>emptyMap(), config, dataPersistenceProvider), persistenceId);
425
426                 MockRaftActor mockRaftActor = mockActorRef.underlyingActor();
427
428                 mockRaftActor.waitForInitializeBehaviorComplete();
429
430                 ReplicatedLogEntry entry = new MockRaftActorContext.MockReplicatedLogEntry(1, 5,
431                         new MockRaftActorContext.MockPayload("F"));
432
433                 final Identifier id = new MockIdentifier("apply-state");
434                 mockRaftActor.onReceiveCommand(new ApplyState(mockActorRef, id, entry));
435
436                 verify(mockRaftActor.actorDelegate).applyState(eq(mockActorRef), eq(id), anyObject());
437
438             }
439         };
440     }
441
442     @Test
443     public void testRaftRoleChangeNotifierWhenRaftActorHasNoPeers() throws Exception {
444         new JavaTestKit(getSystem()) {{
445             TestActorRef<MessageCollectorActor> notifierActor = factory.createTestActor(
446                     Props.create(MessageCollectorActor.class));
447             MessageCollectorActor.waitUntilReady(notifierActor);
448
449             DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
450             long heartBeatInterval = 100;
451             config.setHeartBeatInterval(FiniteDuration.create(heartBeatInterval, TimeUnit.MILLISECONDS));
452             config.setElectionTimeoutFactor(20);
453
454             String persistenceId = factory.generateActorId("notifier-");
455
456             TestActorRef<MockRaftActor> raftActorRef = factory.createTestActor(MockRaftActor.builder().id(persistenceId).
457                     config(config).roleChangeNotifier(notifierActor).dataPersistenceProvider(
458                             new NonPersistentDataProvider()).props().withDispatcher(Dispatchers.DefaultDispatcherId()),
459                             persistenceId);
460
461             List<RoleChanged> matches =  MessageCollectorActor.expectMatching(notifierActor, RoleChanged.class, 3);
462
463
464             // check if the notifier got a role change from null to Follower
465             RoleChanged raftRoleChanged = matches.get(0);
466             assertEquals(persistenceId, raftRoleChanged.getMemberId());
467             assertNull(raftRoleChanged.getOldRole());
468             assertEquals(RaftState.Follower.name(), raftRoleChanged.getNewRole());
469
470             // check if the notifier got a role change from Follower to Candidate
471             raftRoleChanged = matches.get(1);
472             assertEquals(persistenceId, raftRoleChanged.getMemberId());
473             assertEquals(RaftState.Follower.name(), raftRoleChanged.getOldRole());
474             assertEquals(RaftState.Candidate.name(), raftRoleChanged.getNewRole());
475
476             // check if the notifier got a role change from Candidate to Leader
477             raftRoleChanged = matches.get(2);
478             assertEquals(persistenceId, raftRoleChanged.getMemberId());
479             assertEquals(RaftState.Candidate.name(), raftRoleChanged.getOldRole());
480             assertEquals(RaftState.Leader.name(), raftRoleChanged.getNewRole());
481
482             LeaderStateChanged leaderStateChange = MessageCollectorActor.expectFirstMatching(
483                     notifierActor, LeaderStateChanged.class);
484
485             assertEquals(raftRoleChanged.getMemberId(), leaderStateChange.getLeaderId());
486             assertEquals(MockRaftActor.PAYLOAD_VERSION, leaderStateChange.getLeaderPayloadVersion());
487
488             notifierActor.underlyingActor().clear();
489
490             MockRaftActor raftActor = raftActorRef.underlyingActor();
491             final String newLeaderId = "new-leader";
492             final short newLeaderVersion = 6;
493             Follower follower = new Follower(raftActor.getRaftActorContext()) {
494                 @Override
495                 public RaftActorBehavior handleMessage(ActorRef sender, Object message) {
496                     setLeaderId(newLeaderId);
497                     setLeaderPayloadVersion(newLeaderVersion);
498                     return this;
499                 }
500             };
501
502             raftActor.newBehavior(follower);
503
504             leaderStateChange = MessageCollectorActor.expectFirstMatching(notifierActor, LeaderStateChanged.class);
505             assertEquals(persistenceId, leaderStateChange.getMemberId());
506             assertEquals(null, leaderStateChange.getLeaderId());
507
508             raftRoleChanged = MessageCollectorActor.expectFirstMatching(notifierActor, RoleChanged.class);
509             assertEquals(RaftState.Leader.name(), raftRoleChanged.getOldRole());
510             assertEquals(RaftState.Follower.name(), raftRoleChanged.getNewRole());
511
512             notifierActor.underlyingActor().clear();
513
514             raftActor.handleCommand("any");
515
516             leaderStateChange = MessageCollectorActor.expectFirstMatching(notifierActor, LeaderStateChanged.class);
517             assertEquals(persistenceId, leaderStateChange.getMemberId());
518             assertEquals(newLeaderId, leaderStateChange.getLeaderId());
519             assertEquals(newLeaderVersion, leaderStateChange.getLeaderPayloadVersion());
520
521             notifierActor.underlyingActor().clear();
522
523             raftActor.handleCommand("any");
524
525             Uninterruptibles.sleepUninterruptibly(505, TimeUnit.MILLISECONDS);
526             leaderStateChange = MessageCollectorActor.getFirstMatching(notifierActor, LeaderStateChanged.class);
527             assertNull(leaderStateChange);
528         }};
529     }
530
531     @Test
532     public void testRaftRoleChangeNotifierWhenRaftActorHasPeers() throws Exception {
533         new JavaTestKit(getSystem()) {{
534             ActorRef notifierActor = factory.createActor(Props.create(MessageCollectorActor.class));
535             MessageCollectorActor.waitUntilReady(notifierActor);
536
537             DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
538             long heartBeatInterval = 100;
539             config.setHeartBeatInterval(FiniteDuration.create(heartBeatInterval, TimeUnit.MILLISECONDS));
540             config.setElectionTimeoutFactor(1);
541
542             String persistenceId = factory.generateActorId("notifier-");
543
544             factory.createActor(MockRaftActor.builder().id(persistenceId).
545                     peerAddresses(ImmutableMap.of("leader", "fake/path")).
546                     config(config).roleChangeNotifier(notifierActor).props());
547
548             List<RoleChanged> matches =  null;
549             for(int i = 0; i < 5000 / heartBeatInterval; i++) {
550                 matches = MessageCollectorActor.getAllMatching(notifierActor, RoleChanged.class);
551                 assertNotNull(matches);
552                 if(matches.size() == 3) {
553                     break;
554                 }
555                 Uninterruptibles.sleepUninterruptibly(heartBeatInterval, TimeUnit.MILLISECONDS);
556             }
557
558             assertNotNull(matches);
559             assertEquals(2, matches.size());
560
561             // check if the notifier got a role change from null to Follower
562             RoleChanged raftRoleChanged = matches.get(0);
563             assertEquals(persistenceId, raftRoleChanged.getMemberId());
564             assertNull(raftRoleChanged.getOldRole());
565             assertEquals(RaftState.Follower.name(), raftRoleChanged.getNewRole());
566
567             // check if the notifier got a role change from Follower to Candidate
568             raftRoleChanged = matches.get(1);
569             assertEquals(persistenceId, raftRoleChanged.getMemberId());
570             assertEquals(RaftState.Follower.name(), raftRoleChanged.getOldRole());
571             assertEquals(RaftState.Candidate.name(), raftRoleChanged.getNewRole());
572
573         }};
574     }
575
576     @Test
577     public void testFakeSnapshotsForLeaderWithInRealSnapshots() throws Exception {
578         new JavaTestKit(getSystem()) {
579             {
580                 String persistenceId = factory.generateActorId("leader-");
581                 String follower1Id = factory.generateActorId("follower-");
582
583                 ActorRef followerActor1 =
584                         factory.createActor(Props.create(MessageCollectorActor.class));
585
586                 DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
587                 config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
588                 config.setIsolatedLeaderCheckInterval(new FiniteDuration(1, TimeUnit.DAYS));
589
590                 DataPersistenceProvider dataPersistenceProvider = mock(DataPersistenceProvider.class);
591
592                 Map<String, String> peerAddresses = new HashMap<>();
593                 peerAddresses.put(follower1Id, followerActor1.path().toString());
594
595                 TestActorRef<MockRaftActor> mockActorRef = factory.createTestActor(
596                         MockRaftActor.props(persistenceId, peerAddresses, config, dataPersistenceProvider), persistenceId);
597
598                 MockRaftActor leaderActor = mockActorRef.underlyingActor();
599
600                 leaderActor.getRaftActorContext().setCommitIndex(4);
601                 leaderActor.getRaftActorContext().setLastApplied(4);
602                 leaderActor.getRaftActorContext().getTermInformation().update(1, persistenceId);
603
604                 leaderActor.waitForInitializeBehaviorComplete();
605
606                 // create 8 entries in the log - 0 to 4 are applied and will get picked up as part of the capture snapshot
607
608                 Leader leader = new Leader(leaderActor.getRaftActorContext());
609                 leaderActor.setCurrentBehavior(leader);
610                 assertEquals(RaftState.Leader, leaderActor.getCurrentBehavior().state());
611
612                 MockRaftActorContext.MockReplicatedLogBuilder logBuilder = new MockRaftActorContext.MockReplicatedLogBuilder();
613                 leaderActor.getRaftActorContext().setReplicatedLog(logBuilder.createEntries(0, 8, 1).build());
614
615                 assertEquals(8, leaderActor.getReplicatedLog().size());
616
617                 leaderActor.getRaftActorContext().getSnapshotManager()
618                         .capture(new MockRaftActorContext.MockReplicatedLogEntry(1, 6,
619                                 new MockRaftActorContext.MockPayload("x")), 4);
620
621                 verify(leaderActor.snapshotCohortDelegate).createSnapshot(any(ActorRef.class));
622
623                 assertEquals(8, leaderActor.getReplicatedLog().size());
624
625                 assertEquals(RaftState.Leader, leaderActor.getCurrentBehavior().state());
626                 //fake snapshot on index 5
627                 leaderActor.onReceiveCommand(new AppendEntriesReply(follower1Id, 1, true, 5, 1, (short)0));
628
629                 assertEquals(8, leaderActor.getReplicatedLog().size());
630
631                 //fake snapshot on index 6
632                 assertEquals(RaftState.Leader, leaderActor.getCurrentBehavior().state());
633                 leaderActor.onReceiveCommand(new AppendEntriesReply(follower1Id, 1, true, 6, 1, (short)0));
634                 assertEquals(8, leaderActor.getReplicatedLog().size());
635
636                 assertEquals(RaftState.Leader, leaderActor.getCurrentBehavior().state());
637
638                 assertEquals(8, leaderActor.getReplicatedLog().size());
639
640                 ByteString snapshotBytes = fromObject(Arrays.asList(
641                         new MockRaftActorContext.MockPayload("foo-0"),
642                         new MockRaftActorContext.MockPayload("foo-1"),
643                         new MockRaftActorContext.MockPayload("foo-2"),
644                         new MockRaftActorContext.MockPayload("foo-3"),
645                         new MockRaftActorContext.MockPayload("foo-4")));
646
647                 leaderActor.getRaftActorContext().getSnapshotManager().persist(snapshotBytes.toByteArray(),
648                         Runtime.getRuntime().totalMemory());
649
650                 assertTrue(leaderActor.getRaftActorContext().getSnapshotManager().isCapturing());
651
652                 // The commit is needed to complete the snapshot creation process
653                 leaderActor.getRaftActorContext().getSnapshotManager().commit(-1, -1);
654
655                 // capture snapshot reply should remove the snapshotted entries only
656                 assertEquals(3, leaderActor.getReplicatedLog().size());
657                 assertEquals(7, leaderActor.getReplicatedLog().lastIndex());
658
659                 // add another non-replicated entry
660                 leaderActor.getReplicatedLog().append(
661                         new ReplicatedLogImplEntry(8, 1, new MockRaftActorContext.MockPayload("foo-8")));
662
663                 //fake snapshot on index 7, since lastApplied = 7 , we would keep the last applied
664                 leaderActor.onReceiveCommand(new AppendEntriesReply(follower1Id, 1, true, 7, 1, (short)0));
665                 assertEquals(2, leaderActor.getReplicatedLog().size());
666                 assertEquals(8, leaderActor.getReplicatedLog().lastIndex());
667
668             }
669         };
670     }
671
672     @Test
673     public void testFakeSnapshotsForFollowerWithInRealSnapshots() throws Exception {
674         new JavaTestKit(getSystem()) {
675             {
676                 String persistenceId = factory.generateActorId("follower-");
677                 String leaderId = factory.generateActorId("leader-");
678
679
680                 ActorRef leaderActor1 =
681                         factory.createActor(Props.create(MessageCollectorActor.class));
682
683                 DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
684                 config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
685                 config.setIsolatedLeaderCheckInterval(new FiniteDuration(1, TimeUnit.DAYS));
686
687                 DataPersistenceProvider dataPersistenceProvider = mock(DataPersistenceProvider.class);
688
689                 Map<String, String> peerAddresses = new HashMap<>();
690                 peerAddresses.put(leaderId, leaderActor1.path().toString());
691
692                 TestActorRef<MockRaftActor> mockActorRef = factory.createTestActor(
693                         MockRaftActor.props(persistenceId, peerAddresses, config, dataPersistenceProvider), persistenceId);
694
695                 MockRaftActor followerActor = mockActorRef.underlyingActor();
696                 followerActor.getRaftActorContext().setCommitIndex(4);
697                 followerActor.getRaftActorContext().setLastApplied(4);
698                 followerActor.getRaftActorContext().getTermInformation().update(1, persistenceId);
699
700                 followerActor.waitForInitializeBehaviorComplete();
701
702
703                 Follower follower = new Follower(followerActor.getRaftActorContext());
704                 followerActor.setCurrentBehavior(follower);
705                 assertEquals(RaftState.Follower, followerActor.getCurrentBehavior().state());
706
707                 // create 6 entries in the log - 0 to 4 are applied and will get picked up as part of the capture snapshot
708                 MockRaftActorContext.MockReplicatedLogBuilder logBuilder = new MockRaftActorContext.MockReplicatedLogBuilder();
709                 followerActor.getRaftActorContext().setReplicatedLog(logBuilder.createEntries(0, 6, 1).build());
710
711                 // log has indices 0-5
712                 assertEquals(6, followerActor.getReplicatedLog().size());
713
714                 //snapshot on 4
715                 followerActor.getRaftActorContext().getSnapshotManager().capture(
716                         new MockRaftActorContext.MockReplicatedLogEntry(1, 5,
717                                 new MockRaftActorContext.MockPayload("D")), 4);
718
719                 verify(followerActor.snapshotCohortDelegate).createSnapshot(any(ActorRef.class));
720
721                 assertEquals(6, followerActor.getReplicatedLog().size());
722
723                 //fake snapshot on index 6
724                 List<ReplicatedLogEntry> entries =
725                         Arrays.asList(
726                                 (ReplicatedLogEntry) new MockRaftActorContext.MockReplicatedLogEntry(1, 6,
727                                         new MockRaftActorContext.MockPayload("foo-6"))
728                         );
729                 followerActor.onReceiveCommand(new AppendEntries(1, leaderId, 5, 1, entries, 5, 5, (short)0));
730                 assertEquals(7, followerActor.getReplicatedLog().size());
731
732                 //fake snapshot on index 7
733                 assertEquals(RaftState.Follower, followerActor.getCurrentBehavior().state());
734
735                 entries =
736                         Arrays.asList(
737                                 (ReplicatedLogEntry) new MockRaftActorContext.MockReplicatedLogEntry(1, 7,
738                                         new MockRaftActorContext.MockPayload("foo-7"))
739                         );
740                 followerActor.onReceiveCommand(new AppendEntries(1, leaderId, 6, 1, entries, 6, 6, (short) 0));
741                 assertEquals(8, followerActor.getReplicatedLog().size());
742
743                 assertEquals(RaftState.Follower, followerActor.getCurrentBehavior().state());
744
745
746                 ByteString snapshotBytes = fromObject(Arrays.asList(
747                         new MockRaftActorContext.MockPayload("foo-0"),
748                         new MockRaftActorContext.MockPayload("foo-1"),
749                         new MockRaftActorContext.MockPayload("foo-2"),
750                         new MockRaftActorContext.MockPayload("foo-3"),
751                         new MockRaftActorContext.MockPayload("foo-4")));
752                 followerActor.onReceiveCommand(new CaptureSnapshotReply(snapshotBytes.toByteArray()));
753                 assertTrue(followerActor.getRaftActorContext().getSnapshotManager().isCapturing());
754
755                 // The commit is needed to complete the snapshot creation process
756                 followerActor.getRaftActorContext().getSnapshotManager().commit(-1, -1);
757
758                 // capture snapshot reply should remove the snapshotted entries only till replicatedToAllIndex
759                 assertEquals(3, followerActor.getReplicatedLog().size()); //indexes 5,6,7 left in the log
760                 assertEquals(7, followerActor.getReplicatedLog().lastIndex());
761
762                 entries =
763                         Arrays.asList(
764                                 (ReplicatedLogEntry) new MockRaftActorContext.MockReplicatedLogEntry(1, 8,
765                                         new MockRaftActorContext.MockPayload("foo-7"))
766                         );
767                 // send an additional entry 8 with leaderCommit = 7
768                 followerActor.onReceiveCommand(new AppendEntries(1, leaderId, 7, 1, entries, 7, 7, (short) 0));
769
770                 // 7 and 8, as lastapplied is 7
771                 assertEquals(2, followerActor.getReplicatedLog().size());
772
773             }
774         };
775     }
776
777     @Test
778     public void testFakeSnapshotsForLeaderWithInInitiateSnapshots() throws Exception {
779         new JavaTestKit(getSystem()) {
780             {
781                 String persistenceId = factory.generateActorId("leader-");
782                 String follower1Id = factory.generateActorId("follower-");
783                 String follower2Id = factory.generateActorId("follower-");
784
785                 ActorRef followerActor1 =
786                         factory.createActor(Props.create(MessageCollectorActor.class), follower1Id);
787                 ActorRef followerActor2 =
788                         factory.createActor(Props.create(MessageCollectorActor.class), follower2Id);
789
790                 DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
791                 config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
792                 config.setIsolatedLeaderCheckInterval(new FiniteDuration(1, TimeUnit.DAYS));
793
794                 DataPersistenceProvider dataPersistenceProvider = mock(DataPersistenceProvider.class);
795
796                 Map<String, String> peerAddresses = new HashMap<>();
797                 peerAddresses.put(follower1Id, followerActor1.path().toString());
798                 peerAddresses.put(follower2Id, followerActor2.path().toString());
799
800                 TestActorRef<MockRaftActor> mockActorRef = factory.createTestActor(
801                         MockRaftActor.props(persistenceId, peerAddresses, config, dataPersistenceProvider), persistenceId);
802
803                 MockRaftActor leaderActor = mockActorRef.underlyingActor();
804                 leaderActor.getRaftActorContext().setCommitIndex(9);
805                 leaderActor.getRaftActorContext().setLastApplied(9);
806                 leaderActor.getRaftActorContext().getTermInformation().update(1, persistenceId);
807
808                 leaderActor.waitForInitializeBehaviorComplete();
809
810                 Leader leader = new Leader(leaderActor.getRaftActorContext());
811                 leaderActor.setCurrentBehavior(leader);
812                 assertEquals(RaftState.Leader, leaderActor.getCurrentBehavior().state());
813
814                 // create 5 entries in the log
815                 MockRaftActorContext.MockReplicatedLogBuilder logBuilder = new MockRaftActorContext.MockReplicatedLogBuilder();
816                 leaderActor.getRaftActorContext().setReplicatedLog(logBuilder.createEntries(5, 10, 1).build());
817
818                 //set the snapshot index to 4 , 0 to 4 are snapshotted
819                 leaderActor.getRaftActorContext().getReplicatedLog().setSnapshotIndex(4);
820                 //setting replicatedToAllIndex = 9, for the log to clear
821                 leader.setReplicatedToAllIndex(9);
822                 assertEquals(5, leaderActor.getReplicatedLog().size());
823                 assertEquals(RaftState.Leader, leaderActor.getCurrentBehavior().state());
824
825                 leaderActor.onReceiveCommand(new AppendEntriesReply(follower1Id, 1, true, 9, 1, (short) 0));
826                 assertEquals(5, leaderActor.getReplicatedLog().size());
827                 assertEquals(RaftState.Leader, leaderActor.getCurrentBehavior().state());
828
829                 // set the 2nd follower nextIndex to 1 which has been snapshotted
830                 leaderActor.onReceiveCommand(new AppendEntriesReply(follower2Id, 1, true, 0, 1, (short)0));
831                 assertEquals(5, leaderActor.getReplicatedLog().size());
832                 assertEquals(RaftState.Leader, leaderActor.getCurrentBehavior().state());
833
834                 // simulate a real snapshot
835                 leaderActor.onReceiveCommand(SendHeartBeat.INSTANCE);
836                 assertEquals(5, leaderActor.getReplicatedLog().size());
837                 assertEquals(String.format("expected to be Leader but was %s. Current Leader = %s ",
838                         leaderActor.getCurrentBehavior().state(), leaderActor.getLeaderId())
839                         , RaftState.Leader, leaderActor.getCurrentBehavior().state());
840
841
842                 //reply from a slow follower does not initiate a fake snapshot
843                 leaderActor.onReceiveCommand(new AppendEntriesReply(follower2Id, 1, true, 9, 1, (short)0));
844                 assertEquals("Fake snapshot should not happen when Initiate is in progress", 5, leaderActor.getReplicatedLog().size());
845
846                 ByteString snapshotBytes = fromObject(Arrays.asList(
847                         new MockRaftActorContext.MockPayload("foo-0"),
848                         new MockRaftActorContext.MockPayload("foo-1"),
849                         new MockRaftActorContext.MockPayload("foo-2"),
850                         new MockRaftActorContext.MockPayload("foo-3"),
851                         new MockRaftActorContext.MockPayload("foo-4")));
852                 leaderActor.onReceiveCommand(new CaptureSnapshotReply(snapshotBytes.toByteArray()));
853                 assertTrue(leaderActor.getRaftActorContext().getSnapshotManager().isCapturing());
854
855                 assertEquals("Real snapshot didn't clear the log till replicatedToAllIndex", 0, leaderActor.getReplicatedLog().size());
856
857                 //reply from a slow follower after should not raise errors
858                 leaderActor.onReceiveCommand(new AppendEntriesReply(follower2Id, 1, true, 5, 1, (short) 0));
859                 assertEquals(0, leaderActor.getReplicatedLog().size());
860             }
861         };
862     }
863
864     @Test
865     public void testRealSnapshotWhenReplicatedToAllIndexMinusOne() throws Exception {
866         new JavaTestKit(getSystem()) {{
867             String persistenceId = factory.generateActorId("leader-");
868             DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
869             config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
870             config.setIsolatedLeaderCheckInterval(new FiniteDuration(1, TimeUnit.DAYS));
871             config.setSnapshotBatchCount(5);
872
873             DataPersistenceProvider dataPersistenceProvider = new NonPersistentDataProvider();
874
875             Map<String, String> peerAddresses = ImmutableMap.<String, String>builder().put("member1", "address").build();
876
877             TestActorRef<MockRaftActor> mockActorRef = factory.createTestActor(
878                     MockRaftActor.props(persistenceId, peerAddresses, config, dataPersistenceProvider), persistenceId);
879
880             MockRaftActor leaderActor = mockActorRef.underlyingActor();
881             leaderActor.getRaftActorContext().setCommitIndex(3);
882             leaderActor.getRaftActorContext().setLastApplied(3);
883             leaderActor.getRaftActorContext().getTermInformation().update(1, persistenceId);
884
885             leaderActor.waitForInitializeBehaviorComplete();
886             for(int i=0;i< 4;i++) {
887                 leaderActor.getReplicatedLog()
888                         .append(new MockRaftActorContext.MockReplicatedLogEntry(1, i,
889                                 new MockRaftActorContext.MockPayload("A")));
890             }
891
892             Leader leader = new Leader(leaderActor.getRaftActorContext());
893             leaderActor.setCurrentBehavior(leader);
894             assertEquals(RaftState.Leader, leaderActor.getCurrentBehavior().state());
895
896             // Simulate an install snaphost to a follower.
897             leaderActor.getRaftActorContext().getSnapshotManager().captureToInstall(
898                     leaderActor.getReplicatedLog().last(), -1, "member1");
899
900             // Now send a CaptureSnapshotReply
901             mockActorRef.tell(new CaptureSnapshotReply(fromObject("foo").toByteArray()), mockActorRef);
902
903             // Trimming log in this scenario is a no-op
904             assertEquals(-1, leaderActor.getReplicatedLog().getSnapshotIndex());
905             assertTrue(leaderActor.getRaftActorContext().getSnapshotManager().isCapturing());
906             assertEquals(-1, leader.getReplicatedToAllIndex());
907
908         }};
909     }
910
911     @Test
912     public void testRealSnapshotWhenReplicatedToAllIndexNotInReplicatedLog() throws Exception {
913         new JavaTestKit(getSystem()) {{
914             String persistenceId = factory.generateActorId("leader-");
915             DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
916             config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
917             config.setIsolatedLeaderCheckInterval(new FiniteDuration(1, TimeUnit.DAYS));
918             config.setSnapshotBatchCount(5);
919
920             DataPersistenceProvider dataPersistenceProvider = new NonPersistentDataProvider();
921
922             Map<String, String> peerAddresses = ImmutableMap.<String, String>builder().put("member1", "address").build();
923
924             TestActorRef<MockRaftActor> mockActorRef = factory.createTestActor(
925                     MockRaftActor.props(persistenceId, peerAddresses, config, dataPersistenceProvider), persistenceId);
926
927             MockRaftActor leaderActor = mockActorRef.underlyingActor();
928             leaderActor.getRaftActorContext().setCommitIndex(3);
929             leaderActor.getRaftActorContext().setLastApplied(3);
930             leaderActor.getRaftActorContext().getTermInformation().update(1, persistenceId);
931             leaderActor.getReplicatedLog().setSnapshotIndex(3);
932
933             leaderActor.waitForInitializeBehaviorComplete();
934             Leader leader = new Leader(leaderActor.getRaftActorContext());
935             leaderActor.setCurrentBehavior(leader);
936             leader.setReplicatedToAllIndex(3);
937             assertEquals(RaftState.Leader, leaderActor.getCurrentBehavior().state());
938
939             // Persist another entry (this will cause a CaptureSnapshot to be triggered
940             leaderActor.persistData(mockActorRef, new MockIdentifier("x"),
941                 new MockRaftActorContext.MockPayload("duh"));
942
943             // Now send a CaptureSnapshotReply
944             mockActorRef.tell(new CaptureSnapshotReply(fromObject("foo").toByteArray()), mockActorRef);
945
946             // Trimming log in this scenario is a no-op
947             assertEquals(3, leaderActor.getReplicatedLog().getSnapshotIndex());
948             assertTrue(leaderActor.getRaftActorContext().getSnapshotManager().isCapturing());
949             assertEquals(3, leader.getReplicatedToAllIndex());
950
951         }};
952     }
953
954     @Test
955     public void testSwitchBehavior(){
956         String persistenceId = factory.generateActorId("leader-");
957         DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
958         config.setCustomRaftPolicyImplementationClass("org.opendaylight.controller.cluster.raft.policy.DisableElectionsRaftPolicy");
959         config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
960         config.setIsolatedLeaderCheckInterval(new FiniteDuration(1, TimeUnit.DAYS));
961         config.setSnapshotBatchCount(5);
962
963         DataPersistenceProvider dataPersistenceProvider = new NonPersistentDataProvider();
964
965         Map<String, String> peerAddresses = ImmutableMap.<String, String>builder().build();
966
967         TestActorRef<MockRaftActor> mockActorRef = factory.createTestActor(
968                 MockRaftActor.props(persistenceId, peerAddresses, config, dataPersistenceProvider), persistenceId);
969
970         MockRaftActor leaderActor = mockActorRef.underlyingActor();
971
972         leaderActor.waitForRecoveryComplete();
973
974         leaderActor.handleCommand(new SwitchBehavior(RaftState.Follower, 100));
975
976         assertEquals(100, leaderActor.getRaftActorContext().getTermInformation().getCurrentTerm());
977         assertEquals(RaftState.Follower, leaderActor.getCurrentBehavior().state());
978
979         leaderActor.handleCommand(new SwitchBehavior(RaftState.Leader, 110));
980
981         assertEquals(110, leaderActor.getRaftActorContext().getTermInformation().getCurrentTerm());
982         assertEquals(RaftState.Leader, leaderActor.getCurrentBehavior().state());
983
984         leaderActor.handleCommand(new SwitchBehavior(RaftState.Candidate, 125));
985
986         assertEquals(110, leaderActor.getRaftActorContext().getTermInformation().getCurrentTerm());
987         assertEquals(RaftState.Leader, leaderActor.getCurrentBehavior().state());
988
989         leaderActor.handleCommand(new SwitchBehavior(RaftState.IsolatedLeader, 125));
990
991         assertEquals(110, leaderActor.getRaftActorContext().getTermInformation().getCurrentTerm());
992         assertEquals(RaftState.Leader, leaderActor.getCurrentBehavior().state());
993     }
994
995     public static ByteString fromObject(Object snapshot) throws Exception {
996         ByteArrayOutputStream b = null;
997         ObjectOutputStream o = null;
998         try {
999             b = new ByteArrayOutputStream();
1000             o = new ObjectOutputStream(b);
1001             o.writeObject(snapshot);
1002             byte[] snapshotBytes = b.toByteArray();
1003             return ByteString.copyFrom(snapshotBytes);
1004         } finally {
1005             if (o != null) {
1006                 o.flush();
1007                 o.close();
1008             }
1009             if (b != null) {
1010                 b.close();
1011             }
1012         }
1013     }
1014
1015     @Test
1016     public void testUpdateConfigParam() throws Exception {
1017         DefaultConfigParamsImpl emptyConfig = new DefaultConfigParamsImpl();
1018         String persistenceId = factory.generateActorId("follower-");
1019         ImmutableMap<String, String> peerAddresses =
1020             ImmutableMap.<String, String>builder().put("member1", "address").build();
1021         DataPersistenceProvider dataPersistenceProvider = mock(DataPersistenceProvider.class);
1022
1023         TestActorRef<MockRaftActor> actorRef = factory.createTestActor(
1024                 MockRaftActor.props(persistenceId, peerAddresses, emptyConfig, dataPersistenceProvider), persistenceId);
1025         MockRaftActor mockRaftActor = actorRef.underlyingActor();
1026         mockRaftActor.waitForInitializeBehaviorComplete();
1027
1028         RaftActorBehavior behavior = mockRaftActor.getCurrentBehavior();
1029         mockRaftActor.updateConfigParams(emptyConfig);
1030         assertSame("Same Behavior", behavior, mockRaftActor.getCurrentBehavior());
1031         assertEquals("Behavior State", RaftState.Follower,
1032             mockRaftActor.getCurrentBehavior().state());
1033
1034         DefaultConfigParamsImpl disableConfig = new DefaultConfigParamsImpl();
1035         disableConfig.setCustomRaftPolicyImplementationClass(
1036             "org.opendaylight.controller.cluster.raft.policy.DisableElectionsRaftPolicy");
1037         mockRaftActor.updateConfigParams(disableConfig);
1038         assertNotSame("Different Behavior", behavior, mockRaftActor.getCurrentBehavior());
1039         assertEquals("Behavior State", RaftState.Follower,
1040             mockRaftActor.getCurrentBehavior().state());
1041
1042         behavior = mockRaftActor.getCurrentBehavior();
1043         mockRaftActor.updateConfigParams(disableConfig);
1044         assertSame("Same Behavior", behavior, mockRaftActor.getCurrentBehavior());
1045         assertEquals("Behavior State", RaftState.Follower,
1046             mockRaftActor.getCurrentBehavior().state());
1047
1048         DefaultConfigParamsImpl defaultConfig = new DefaultConfigParamsImpl();
1049         defaultConfig.setCustomRaftPolicyImplementationClass(
1050             "org.opendaylight.controller.cluster.raft.policy.DefaultRaftPolicy");
1051         mockRaftActor.updateConfigParams(defaultConfig);
1052         assertNotSame("Different Behavior", behavior, mockRaftActor.getCurrentBehavior());
1053         assertEquals("Behavior State", RaftState.Follower,
1054             mockRaftActor.getCurrentBehavior().state());
1055
1056         behavior = mockRaftActor.getCurrentBehavior();
1057         mockRaftActor.updateConfigParams(defaultConfig);
1058         assertSame("Same Behavior", behavior, mockRaftActor.getCurrentBehavior());
1059         assertEquals("Behavior State", RaftState.Follower,
1060             mockRaftActor.getCurrentBehavior().state());
1061     }
1062
1063     @Test
1064     public void testGetSnapshot() throws Exception {
1065         TEST_LOG.info("testGetSnapshot starting");
1066
1067         JavaTestKit kit = new JavaTestKit(getSystem());
1068
1069         String persistenceId = factory.generateActorId("test-actor-");
1070         DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
1071         config.setCustomRaftPolicyImplementationClass(DisableElectionsRaftPolicy.class.getName());
1072
1073         long term = 3;
1074         long seqN = 1;
1075         InMemoryJournal.addEntry(persistenceId, seqN++, new UpdateElectionTerm(term, "member-1"));
1076         InMemoryJournal.addEntry(persistenceId, seqN++, new MockRaftActorContext.MockReplicatedLogEntry(term, 0,
1077                 new MockRaftActorContext.MockPayload("A")));
1078         InMemoryJournal.addEntry(persistenceId, seqN++, new MockRaftActorContext.MockReplicatedLogEntry(term, 1,
1079                 new MockRaftActorContext.MockPayload("B")));
1080         InMemoryJournal.addEntry(persistenceId, seqN++, new ApplyJournalEntries(1));
1081         InMemoryJournal.addEntry(persistenceId, seqN++, new MockRaftActorContext.MockReplicatedLogEntry(term, 2,
1082                 new MockRaftActorContext.MockPayload("C")));
1083
1084         TestActorRef<MockRaftActor> raftActorRef = factory.createTestActor(MockRaftActor.props(persistenceId,
1085                 ImmutableMap.<String, String>builder().put("member1", "address").build(), config).
1086                     withDispatcher(Dispatchers.DefaultDispatcherId()), persistenceId);
1087         MockRaftActor mockRaftActor = raftActorRef.underlyingActor();
1088
1089         mockRaftActor.waitForRecoveryComplete();
1090
1091         mockRaftActor.snapshotCohortDelegate = mock(RaftActorSnapshotCohort.class);
1092
1093         raftActorRef.tell(GetSnapshot.INSTANCE, kit.getRef());
1094
1095         ArgumentCaptor<ActorRef> replyActor = ArgumentCaptor.forClass(ActorRef.class);
1096         verify(mockRaftActor.snapshotCohortDelegate, timeout(5000)).createSnapshot(replyActor.capture());
1097
1098         byte[] stateSnapshot = new byte[]{1,2,3};
1099         replyActor.getValue().tell(new CaptureSnapshotReply(stateSnapshot), ActorRef.noSender());
1100
1101         GetSnapshotReply reply = kit.expectMsgClass(GetSnapshotReply.class);
1102
1103         assertEquals("getId", persistenceId, reply.getId());
1104         Snapshot replySnapshot = SerializationUtils.deserialize(reply.getSnapshot());
1105         assertEquals("getElectionTerm", term, replySnapshot.getElectionTerm());
1106         assertEquals("getElectionVotedFor", "member-1", replySnapshot.getElectionVotedFor());
1107         assertEquals("getLastAppliedIndex", 1L, replySnapshot.getLastAppliedIndex());
1108         assertEquals("getLastAppliedTerm", term, replySnapshot.getLastAppliedTerm());
1109         assertEquals("getLastIndex", 2L, replySnapshot.getLastIndex());
1110         assertEquals("getLastTerm", term, replySnapshot.getLastTerm());
1111         assertArrayEquals("getState", stateSnapshot, replySnapshot.getState());
1112         assertEquals("getUnAppliedEntries size", 1, replySnapshot.getUnAppliedEntries().size());
1113         assertEquals("UnApplied entry index ", 2L, replySnapshot.getUnAppliedEntries().get(0).getIndex());
1114
1115         // Test with timeout
1116
1117         mockRaftActor.getSnapshotMessageSupport().setSnapshotReplyActorTimeout(Duration.create(200, TimeUnit.MILLISECONDS));
1118         reset(mockRaftActor.snapshotCohortDelegate);
1119
1120         raftActorRef.tell(GetSnapshot.INSTANCE, kit.getRef());
1121         Failure failure = kit.expectMsgClass(akka.actor.Status.Failure.class);
1122         assertEquals("Failure cause type", TimeoutException.class, failure.cause().getClass());
1123
1124         mockRaftActor.getSnapshotMessageSupport().setSnapshotReplyActorTimeout(Duration.create(30, TimeUnit.SECONDS));
1125
1126         // Test with persistence disabled.
1127
1128         mockRaftActor.setPersistence(false);
1129         reset(mockRaftActor.snapshotCohortDelegate);
1130
1131         raftActorRef.tell(GetSnapshot.INSTANCE, kit.getRef());
1132         reply = kit.expectMsgClass(GetSnapshotReply.class);
1133         verify(mockRaftActor.snapshotCohortDelegate, never()).createSnapshot(any(ActorRef.class));
1134
1135         assertEquals("getId", persistenceId, reply.getId());
1136         replySnapshot = SerializationUtils.deserialize(reply.getSnapshot());
1137         assertEquals("getElectionTerm", term, replySnapshot.getElectionTerm());
1138         assertEquals("getElectionVotedFor", "member-1", replySnapshot.getElectionVotedFor());
1139         assertEquals("getLastAppliedIndex", -1L, replySnapshot.getLastAppliedIndex());
1140         assertEquals("getLastAppliedTerm", -1L, replySnapshot.getLastAppliedTerm());
1141         assertEquals("getLastIndex", -1L, replySnapshot.getLastIndex());
1142         assertEquals("getLastTerm", -1L, replySnapshot.getLastTerm());
1143         assertEquals("getState length", 0, replySnapshot.getState().length);
1144         assertEquals("getUnAppliedEntries size", 0, replySnapshot.getUnAppliedEntries().size());
1145
1146         TEST_LOG.info("testGetSnapshot ending");
1147     }
1148
1149     @Test
1150     public void testRestoreFromSnapshot() throws Exception {
1151         TEST_LOG.info("testRestoreFromSnapshot starting");
1152
1153         String persistenceId = factory.generateActorId("test-actor-");
1154         DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
1155         config.setCustomRaftPolicyImplementationClass(DisableElectionsRaftPolicy.class.getName());
1156
1157         List<ReplicatedLogEntry> snapshotUnappliedEntries = new ArrayList<>();
1158         snapshotUnappliedEntries.add(new MockRaftActorContext.MockReplicatedLogEntry(1, 4,
1159                 new MockRaftActorContext.MockPayload("E")));
1160
1161         int snapshotLastApplied = 3;
1162         int snapshotLastIndex = 4;
1163
1164         List<MockPayload> state = Arrays.asList(
1165                 new MockRaftActorContext.MockPayload("A"),
1166                 new MockRaftActorContext.MockPayload("B"),
1167                 new MockRaftActorContext.MockPayload("C"),
1168                 new MockRaftActorContext.MockPayload("D"));
1169         ByteString stateBytes = fromObject(state);
1170
1171         Snapshot snapshot = Snapshot.create(stateBytes.toByteArray(), snapshotUnappliedEntries,
1172                 snapshotLastIndex, 1, snapshotLastApplied, 1, 1, "member-1");
1173
1174         InMemorySnapshotStore.addSnapshotSavedLatch(persistenceId);
1175
1176         TestActorRef<MockRaftActor> raftActorRef = factory.createTestActor(MockRaftActor.builder().id(persistenceId).
1177                 config(config).restoreFromSnapshot(SerializationUtils.serialize(snapshot)).props().
1178                     withDispatcher(Dispatchers.DefaultDispatcherId()), persistenceId);
1179         MockRaftActor mockRaftActor = raftActorRef.underlyingActor();
1180
1181         mockRaftActor.waitForRecoveryComplete();
1182
1183         Snapshot savedSnapshot = InMemorySnapshotStore.waitForSavedSnapshot(persistenceId, Snapshot.class);
1184         assertEquals("getElectionTerm", snapshot.getElectionTerm(), savedSnapshot.getElectionTerm());
1185         assertEquals("getElectionVotedFor", snapshot.getElectionVotedFor(), savedSnapshot.getElectionVotedFor());
1186         assertEquals("getLastAppliedIndex", snapshot.getLastAppliedIndex(), savedSnapshot.getLastAppliedIndex());
1187         assertEquals("getLastAppliedTerm", snapshot.getLastAppliedTerm(), savedSnapshot.getLastAppliedTerm());
1188         assertEquals("getLastIndex", snapshot.getLastIndex(), savedSnapshot.getLastIndex());
1189         assertEquals("getLastTerm", snapshot.getLastTerm(), savedSnapshot.getLastTerm());
1190         assertArrayEquals("getState", snapshot.getState(), savedSnapshot.getState());
1191         assertEquals("getUnAppliedEntries", snapshot.getUnAppliedEntries(), savedSnapshot.getUnAppliedEntries());
1192
1193         verify(mockRaftActor.snapshotCohortDelegate, timeout(5000)).applySnapshot(any(byte[].class));
1194
1195         RaftActorContext context = mockRaftActor.getRaftActorContext();
1196         assertEquals("Journal log size", 1, context.getReplicatedLog().size());
1197         assertEquals("Last index", snapshotLastIndex, context.getReplicatedLog().lastIndex());
1198         assertEquals("Last applied", snapshotLastApplied, context.getLastApplied());
1199         assertEquals("Commit index", snapshotLastApplied, context.getCommitIndex());
1200         assertEquals("Recovered state", state, mockRaftActor.getState());
1201         assertEquals("Current term", 1L, context.getTermInformation().getCurrentTerm());
1202         assertEquals("Voted for", "member-1", context.getTermInformation().getVotedFor());
1203
1204         // Test with data persistence disabled
1205
1206         snapshot = Snapshot.create(new byte[0], Collections.<ReplicatedLogEntry>emptyList(),
1207                 -1, -1, -1, -1, 5, "member-1");
1208
1209         persistenceId = factory.generateActorId("test-actor-");
1210
1211         raftActorRef = factory.createTestActor(MockRaftActor.builder().id(persistenceId).
1212                 config(config).restoreFromSnapshot(SerializationUtils.serialize(snapshot)).
1213                 persistent(Optional.of(Boolean.FALSE)).props().
1214                     withDispatcher(Dispatchers.DefaultDispatcherId()), persistenceId);
1215         mockRaftActor = raftActorRef.underlyingActor();
1216
1217         mockRaftActor.waitForRecoveryComplete();
1218         assertEquals("snapshot committed", true,
1219                 Uninterruptibles.awaitUninterruptibly(mockRaftActor.snapshotCommitted, 5, TimeUnit.SECONDS));
1220
1221         context = mockRaftActor.getRaftActorContext();
1222         assertEquals("Current term", 5L, context.getTermInformation().getCurrentTerm());
1223         assertEquals("Voted for", "member-1", context.getTermInformation().getVotedFor());
1224
1225         TEST_LOG.info("testRestoreFromSnapshot ending");
1226     }
1227
1228     @Test
1229     public void testRestoreFromSnapshotWithRecoveredData() throws Exception {
1230         TEST_LOG.info("testRestoreFromSnapshotWithRecoveredData starting");
1231
1232         String persistenceId = factory.generateActorId("test-actor-");
1233         DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
1234         config.setCustomRaftPolicyImplementationClass(DisableElectionsRaftPolicy.class.getName());
1235
1236         List<MockPayload> state = Arrays.asList(new MockRaftActorContext.MockPayload("A"));
1237         Snapshot snapshot = Snapshot.create(fromObject(state).toByteArray(), Arrays.<ReplicatedLogEntry>asList(),
1238                 5, 2, 5, 2, 2, "member-1");
1239
1240         InMemoryJournal.addEntry(persistenceId, 1, new MockRaftActorContext.MockReplicatedLogEntry(1, 0,
1241                 new MockRaftActorContext.MockPayload("B")));
1242
1243         TestActorRef<MockRaftActor> raftActorRef = factory.createTestActor(MockRaftActor.builder().id(persistenceId).
1244                 config(config).restoreFromSnapshot(SerializationUtils.serialize(snapshot)).props().
1245                     withDispatcher(Dispatchers.DefaultDispatcherId()), persistenceId);
1246         MockRaftActor mockRaftActor = raftActorRef.underlyingActor();
1247
1248         mockRaftActor.waitForRecoveryComplete();
1249
1250         Uninterruptibles.sleepUninterruptibly(500, TimeUnit.MILLISECONDS);
1251         verify(mockRaftActor.snapshotCohortDelegate, never()).applySnapshot(any(byte[].class));
1252
1253         RaftActorContext context = mockRaftActor.getRaftActorContext();
1254         assertEquals("Journal log size", 1, context.getReplicatedLog().size());
1255         assertEquals("Last index", 0, context.getReplicatedLog().lastIndex());
1256         assertEquals("Last applied", -1, context.getLastApplied());
1257         assertEquals("Commit index", -1, context.getCommitIndex());
1258         assertEquals("Current term", 0, context.getTermInformation().getCurrentTerm());
1259         assertEquals("Voted for", null, context.getTermInformation().getVotedFor());
1260
1261         TEST_LOG.info("testRestoreFromSnapshotWithRecoveredData ending");
1262     }
1263
1264     @Test
1265     public void testNonVotingOnRecovery() throws Exception {
1266         TEST_LOG.info("testNonVotingOnRecovery starting");
1267
1268         DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
1269         config.setElectionTimeoutFactor(1);
1270         config.setHeartBeatInterval(FiniteDuration.create(1, TimeUnit.MILLISECONDS));
1271
1272         String persistenceId = factory.generateActorId("test-actor-");
1273         InMemoryJournal.addEntry(persistenceId, 1,  new MockRaftActorContext.MockReplicatedLogEntry(1, 0,
1274                 new ServerConfigurationPayload(Arrays.asList(new ServerInfo(persistenceId, false)))));
1275
1276         TestActorRef<MockRaftActor> raftActorRef = factory.createTestActor(MockRaftActor.builder().id(persistenceId).
1277                 config(config).props().withDispatcher(Dispatchers.DefaultDispatcherId()), persistenceId);
1278         MockRaftActor mockRaftActor = raftActorRef.underlyingActor();
1279
1280         mockRaftActor.waitForInitializeBehaviorComplete();
1281
1282         // Sleep a bit and verify it didn't get an election timeout and schedule an election.
1283
1284         Uninterruptibles.sleepUninterruptibly(400, TimeUnit.MILLISECONDS);
1285         assertEquals("getRaftState", RaftState.Follower, mockRaftActor.getRaftState());
1286
1287         TEST_LOG.info("testNonVotingOnRecovery ending");
1288     }
1289
1290     @Test
1291     public void testLeaderTransitioning() throws Exception {
1292         TEST_LOG.info("testLeaderTransitioning starting");
1293
1294         TestActorRef<MessageCollectorActor> notifierActor = factory.createTestActor(
1295                 Props.create(MessageCollectorActor.class));
1296
1297         DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
1298         config.setCustomRaftPolicyImplementationClass(DisableElectionsRaftPolicy.class.getName());
1299
1300         String persistenceId = factory.generateActorId("test-actor-");
1301
1302         TestActorRef<MockRaftActor> raftActorRef = factory.createTestActor(MockRaftActor.builder().id(persistenceId).
1303                 config(config).roleChangeNotifier(notifierActor).props().withDispatcher(Dispatchers.DefaultDispatcherId()), persistenceId);
1304         MockRaftActor mockRaftActor = raftActorRef.underlyingActor();
1305
1306         mockRaftActor.waitForInitializeBehaviorComplete();
1307
1308         raftActorRef.tell(new AppendEntries(1L, "leader", 0L, 1L, Collections.<ReplicatedLogEntry>emptyList(),
1309                 0L, -1L, (short)1), ActorRef.noSender());
1310         LeaderStateChanged leaderStateChange = MessageCollectorActor.expectFirstMatching(
1311                 notifierActor, LeaderStateChanged.class);
1312         assertEquals("getLeaderId", "leader", leaderStateChange.getLeaderId());
1313
1314         MessageCollectorActor.clearMessages(notifierActor);
1315
1316         raftActorRef.tell(LeaderTransitioning.INSTANCE, ActorRef.noSender());
1317
1318         leaderStateChange = MessageCollectorActor.expectFirstMatching(notifierActor, LeaderStateChanged.class);
1319         assertEquals("getMemberId", persistenceId, leaderStateChange.getMemberId());
1320         assertEquals("getLeaderId", null, leaderStateChange.getLeaderId());
1321
1322         TEST_LOG.info("testLeaderTransitioning ending");
1323     }
1324 }

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