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

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