48b555faff286c0393cb2c6ec39030c651751822
[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 testRaftActorOnRecoverySnapshot() throws Exception {
965         TEST_LOG.info("testRaftActorOnRecoverySnapshot");
966
967         new JavaTestKit(getSystem()) {{
968                 String persistenceId = factory.generateActorId("follower-");
969
970                 DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
971
972                 // Set the heartbeat interval high to essentially disable election otherwise the test
973                 // may fail if the actor is switched to Leader
974                 config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
975
976                 ImmutableMap<String, String> peerAddresses = ImmutableMap.<String, String>builder().put("member1", "address").build();
977
978                 // Create mock ReplicatedLogEntry
979                 ReplicatedLogEntry replLogEntry = new MockRaftActorContext.MockReplicatedLogEntry(1,1,
980                         new MockRaftActorContext.MockPayload("F", 1));
981
982                 InMemoryJournal.addEntry(persistenceId, 1, replLogEntry);
983
984                 TestActorRef<MockRaftActor> ref = factory.createTestActor(
985                         MockRaftActor.props(persistenceId, peerAddresses, config));
986
987                 MockRaftActor mockRaftActor = ref.underlyingActor();
988
989                 mockRaftActor.waitForRecoveryComplete();
990
991                 mockRaftActor.waitForInitializeBehaviorComplete();
992
993                 verify(mockRaftActor.snapshotCohortDelegate, timeout(5000)).createSnapshot(any(ActorRef.class));
994             }};
995     }
996
997     @Test
998     public void testSwitchBehavior(){
999         String persistenceId = factory.generateActorId("leader-");
1000         DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
1001         config.setCustomRaftPolicyImplementationClass("org.opendaylight.controller.cluster.raft.policy.DisableElectionsRaftPolicy");
1002         config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
1003         config.setIsolatedLeaderCheckInterval(new FiniteDuration(1, TimeUnit.DAYS));
1004         config.setSnapshotBatchCount(5);
1005
1006         DataPersistenceProvider dataPersistenceProvider = new NonPersistentDataProvider();
1007
1008         Map<String, String> peerAddresses = ImmutableMap.<String, String>builder().build();
1009
1010         TestActorRef<MockRaftActor> mockActorRef = factory.createTestActor(
1011                 MockRaftActor.props(persistenceId, peerAddresses, config, dataPersistenceProvider), persistenceId);
1012
1013         MockRaftActor leaderActor = mockActorRef.underlyingActor();
1014
1015         leaderActor.waitForRecoveryComplete();
1016
1017         leaderActor.handleCommand(new SwitchBehavior(RaftState.Follower, 100));
1018
1019         assertEquals(100, leaderActor.getRaftActorContext().getTermInformation().getCurrentTerm());
1020         assertEquals(RaftState.Follower, leaderActor.getCurrentBehavior().state());
1021
1022         leaderActor.handleCommand(new SwitchBehavior(RaftState.Leader, 110));
1023
1024         assertEquals(110, leaderActor.getRaftActorContext().getTermInformation().getCurrentTerm());
1025         assertEquals(RaftState.Leader, leaderActor.getCurrentBehavior().state());
1026
1027         leaderActor.handleCommand(new SwitchBehavior(RaftState.Candidate, 125));
1028
1029         assertEquals(110, leaderActor.getRaftActorContext().getTermInformation().getCurrentTerm());
1030         assertEquals(RaftState.Leader, leaderActor.getCurrentBehavior().state());
1031
1032         leaderActor.handleCommand(new SwitchBehavior(RaftState.IsolatedLeader, 125));
1033
1034         assertEquals(110, leaderActor.getRaftActorContext().getTermInformation().getCurrentTerm());
1035         assertEquals(RaftState.Leader, leaderActor.getCurrentBehavior().state());
1036     }
1037
1038     public static ByteString fromObject(Object snapshot) throws Exception {
1039         ByteArrayOutputStream b = null;
1040         ObjectOutputStream o = null;
1041         try {
1042             b = new ByteArrayOutputStream();
1043             o = new ObjectOutputStream(b);
1044             o.writeObject(snapshot);
1045             byte[] snapshotBytes = b.toByteArray();
1046             return ByteString.copyFrom(snapshotBytes);
1047         } finally {
1048             if (o != null) {
1049                 o.flush();
1050                 o.close();
1051             }
1052             if (b != null) {
1053                 b.close();
1054             }
1055         }
1056     }
1057
1058     @Test
1059     public void testUpdateConfigParam() throws Exception {
1060         DefaultConfigParamsImpl emptyConfig = new DefaultConfigParamsImpl();
1061         String persistenceId = factory.generateActorId("follower-");
1062         ImmutableMap<String, String> peerAddresses =
1063             ImmutableMap.<String, String>builder().put("member1", "address").build();
1064         DataPersistenceProvider dataPersistenceProvider = mock(DataPersistenceProvider.class);
1065
1066         TestActorRef<MockRaftActor> actorRef = factory.createTestActor(
1067                 MockRaftActor.props(persistenceId, peerAddresses, emptyConfig, dataPersistenceProvider), persistenceId);
1068         MockRaftActor mockRaftActor = actorRef.underlyingActor();
1069         mockRaftActor.waitForInitializeBehaviorComplete();
1070
1071         RaftActorBehavior behavior = mockRaftActor.getCurrentBehavior();
1072         mockRaftActor.updateConfigParams(emptyConfig);
1073         assertSame("Same Behavior", behavior, mockRaftActor.getCurrentBehavior());
1074         assertEquals("Behavior State", RaftState.Follower,
1075             mockRaftActor.getCurrentBehavior().state());
1076
1077         DefaultConfigParamsImpl disableConfig = new DefaultConfigParamsImpl();
1078         disableConfig.setCustomRaftPolicyImplementationClass(
1079             "org.opendaylight.controller.cluster.raft.policy.DisableElectionsRaftPolicy");
1080         mockRaftActor.updateConfigParams(disableConfig);
1081         assertNotSame("Different Behavior", behavior, mockRaftActor.getCurrentBehavior());
1082         assertEquals("Behavior State", RaftState.Follower,
1083             mockRaftActor.getCurrentBehavior().state());
1084
1085         behavior = mockRaftActor.getCurrentBehavior();
1086         mockRaftActor.updateConfigParams(disableConfig);
1087         assertSame("Same Behavior", behavior, mockRaftActor.getCurrentBehavior());
1088         assertEquals("Behavior State", RaftState.Follower,
1089             mockRaftActor.getCurrentBehavior().state());
1090
1091         DefaultConfigParamsImpl defaultConfig = new DefaultConfigParamsImpl();
1092         defaultConfig.setCustomRaftPolicyImplementationClass(
1093             "org.opendaylight.controller.cluster.raft.policy.DefaultRaftPolicy");
1094         mockRaftActor.updateConfigParams(defaultConfig);
1095         assertNotSame("Different Behavior", behavior, mockRaftActor.getCurrentBehavior());
1096         assertEquals("Behavior State", RaftState.Follower,
1097             mockRaftActor.getCurrentBehavior().state());
1098
1099         behavior = mockRaftActor.getCurrentBehavior();
1100         mockRaftActor.updateConfigParams(defaultConfig);
1101         assertSame("Same Behavior", behavior, mockRaftActor.getCurrentBehavior());
1102         assertEquals("Behavior State", RaftState.Follower,
1103             mockRaftActor.getCurrentBehavior().state());
1104     }
1105
1106     @Test
1107     public void testGetSnapshot() throws Exception {
1108         TEST_LOG.info("testGetSnapshot starting");
1109
1110         JavaTestKit kit = new JavaTestKit(getSystem());
1111
1112         String persistenceId = factory.generateActorId("test-actor-");
1113         DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
1114         config.setCustomRaftPolicyImplementationClass(DisableElectionsRaftPolicy.class.getName());
1115
1116         long term = 3;
1117         long seqN = 1;
1118         InMemoryJournal.addEntry(persistenceId, seqN++, new UpdateElectionTerm(term, "member-1"));
1119         InMemoryJournal.addEntry(persistenceId, seqN++, new MockRaftActorContext.MockReplicatedLogEntry(term, 0,
1120                 new MockRaftActorContext.MockPayload("A")));
1121         InMemoryJournal.addEntry(persistenceId, seqN++, new MockRaftActorContext.MockReplicatedLogEntry(term, 1,
1122                 new MockRaftActorContext.MockPayload("B")));
1123         InMemoryJournal.addEntry(persistenceId, seqN++, new ApplyJournalEntries(1));
1124         InMemoryJournal.addEntry(persistenceId, seqN++, new MockRaftActorContext.MockReplicatedLogEntry(term, 2,
1125                 new MockRaftActorContext.MockPayload("C")));
1126
1127         TestActorRef<MockRaftActor> raftActorRef = factory.createTestActor(MockRaftActor.props(persistenceId,
1128                 ImmutableMap.<String, String>builder().put("member1", "address").build(), config).
1129                     withDispatcher(Dispatchers.DefaultDispatcherId()), persistenceId);
1130         MockRaftActor mockRaftActor = raftActorRef.underlyingActor();
1131
1132         mockRaftActor.waitForRecoveryComplete();
1133
1134         // Wait for snapshot after recovery
1135         verify(mockRaftActor.snapshotCohortDelegate, timeout(5000)).createSnapshot(any(ActorRef.class));
1136
1137         mockRaftActor.snapshotCohortDelegate = mock(RaftActorSnapshotCohort.class);
1138
1139         raftActorRef.tell(GetSnapshot.INSTANCE, kit.getRef());
1140
1141         ArgumentCaptor<ActorRef> replyActor = ArgumentCaptor.forClass(ActorRef.class);
1142         verify(mockRaftActor.snapshotCohortDelegate, timeout(5000)).createSnapshot(replyActor.capture());
1143
1144         byte[] stateSnapshot = new byte[]{1,2,3};
1145         replyActor.getValue().tell(new CaptureSnapshotReply(stateSnapshot), ActorRef.noSender());
1146
1147         GetSnapshotReply reply = kit.expectMsgClass(GetSnapshotReply.class);
1148
1149         assertEquals("getId", persistenceId, reply.getId());
1150         Snapshot replySnapshot = SerializationUtils.deserialize(reply.getSnapshot());
1151         assertEquals("getElectionTerm", term, replySnapshot.getElectionTerm());
1152         assertEquals("getElectionVotedFor", "member-1", replySnapshot.getElectionVotedFor());
1153         assertEquals("getLastAppliedIndex", 1L, replySnapshot.getLastAppliedIndex());
1154         assertEquals("getLastAppliedTerm", term, replySnapshot.getLastAppliedTerm());
1155         assertEquals("getLastIndex", 2L, replySnapshot.getLastIndex());
1156         assertEquals("getLastTerm", term, replySnapshot.getLastTerm());
1157         assertArrayEquals("getState", stateSnapshot, replySnapshot.getState());
1158         assertEquals("getUnAppliedEntries size", 1, replySnapshot.getUnAppliedEntries().size());
1159         assertEquals("UnApplied entry index ", 2L, replySnapshot.getUnAppliedEntries().get(0).getIndex());
1160
1161         // Test with timeout
1162
1163         mockRaftActor.getSnapshotMessageSupport().setSnapshotReplyActorTimeout(Duration.create(200, TimeUnit.MILLISECONDS));
1164         reset(mockRaftActor.snapshotCohortDelegate);
1165
1166         raftActorRef.tell(GetSnapshot.INSTANCE, kit.getRef());
1167         Failure failure = kit.expectMsgClass(akka.actor.Status.Failure.class);
1168         assertEquals("Failure cause type", TimeoutException.class, failure.cause().getClass());
1169
1170         mockRaftActor.getSnapshotMessageSupport().setSnapshotReplyActorTimeout(Duration.create(30, TimeUnit.SECONDS));
1171
1172         // Test with persistence disabled.
1173
1174         mockRaftActor.setPersistence(false);
1175         reset(mockRaftActor.snapshotCohortDelegate);
1176
1177         raftActorRef.tell(GetSnapshot.INSTANCE, kit.getRef());
1178         reply = kit.expectMsgClass(GetSnapshotReply.class);
1179         verify(mockRaftActor.snapshotCohortDelegate, never()).createSnapshot(any(ActorRef.class));
1180
1181         assertEquals("getId", persistenceId, reply.getId());
1182         replySnapshot = SerializationUtils.deserialize(reply.getSnapshot());
1183         assertEquals("getElectionTerm", term, replySnapshot.getElectionTerm());
1184         assertEquals("getElectionVotedFor", "member-1", replySnapshot.getElectionVotedFor());
1185         assertEquals("getLastAppliedIndex", -1L, replySnapshot.getLastAppliedIndex());
1186         assertEquals("getLastAppliedTerm", -1L, replySnapshot.getLastAppliedTerm());
1187         assertEquals("getLastIndex", -1L, replySnapshot.getLastIndex());
1188         assertEquals("getLastTerm", -1L, replySnapshot.getLastTerm());
1189         assertEquals("getState length", 0, replySnapshot.getState().length);
1190         assertEquals("getUnAppliedEntries size", 0, replySnapshot.getUnAppliedEntries().size());
1191
1192         TEST_LOG.info("testGetSnapshot ending");
1193     }
1194
1195     @Test
1196     public void testRestoreFromSnapshot() throws Exception {
1197         TEST_LOG.info("testRestoreFromSnapshot starting");
1198
1199         String persistenceId = factory.generateActorId("test-actor-");
1200         DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
1201         config.setCustomRaftPolicyImplementationClass(DisableElectionsRaftPolicy.class.getName());
1202
1203         List<ReplicatedLogEntry> snapshotUnappliedEntries = new ArrayList<>();
1204         snapshotUnappliedEntries.add(new MockRaftActorContext.MockReplicatedLogEntry(1, 4,
1205                 new MockRaftActorContext.MockPayload("E")));
1206
1207         int snapshotLastApplied = 3;
1208         int snapshotLastIndex = 4;
1209
1210         List<MockPayload> state = Arrays.asList(
1211                 new MockRaftActorContext.MockPayload("A"),
1212                 new MockRaftActorContext.MockPayload("B"),
1213                 new MockRaftActorContext.MockPayload("C"),
1214                 new MockRaftActorContext.MockPayload("D"));
1215         ByteString stateBytes = fromObject(state);
1216
1217         Snapshot snapshot = Snapshot.create(stateBytes.toByteArray(), snapshotUnappliedEntries,
1218                 snapshotLastIndex, 1, snapshotLastApplied, 1, 1, "member-1");
1219
1220         InMemorySnapshotStore.addSnapshotSavedLatch(persistenceId);
1221
1222         TestActorRef<MockRaftActor> raftActorRef = factory.createTestActor(MockRaftActor.builder().id(persistenceId).
1223                 config(config).restoreFromSnapshot(SerializationUtils.serialize(snapshot)).props().
1224                     withDispatcher(Dispatchers.DefaultDispatcherId()), persistenceId);
1225         MockRaftActor mockRaftActor = raftActorRef.underlyingActor();
1226
1227         mockRaftActor.waitForRecoveryComplete();
1228
1229         Snapshot savedSnapshot = InMemorySnapshotStore.waitForSavedSnapshot(persistenceId, Snapshot.class);
1230         assertEquals("getElectionTerm", snapshot.getElectionTerm(), savedSnapshot.getElectionTerm());
1231         assertEquals("getElectionVotedFor", snapshot.getElectionVotedFor(), savedSnapshot.getElectionVotedFor());
1232         assertEquals("getLastAppliedIndex", snapshot.getLastAppliedIndex(), savedSnapshot.getLastAppliedIndex());
1233         assertEquals("getLastAppliedTerm", snapshot.getLastAppliedTerm(), savedSnapshot.getLastAppliedTerm());
1234         assertEquals("getLastIndex", snapshot.getLastIndex(), savedSnapshot.getLastIndex());
1235         assertEquals("getLastTerm", snapshot.getLastTerm(), savedSnapshot.getLastTerm());
1236         assertArrayEquals("getState", snapshot.getState(), savedSnapshot.getState());
1237         assertEquals("getUnAppliedEntries", snapshot.getUnAppliedEntries(), savedSnapshot.getUnAppliedEntries());
1238
1239         verify(mockRaftActor.snapshotCohortDelegate, timeout(5000)).applySnapshot(any(byte[].class));
1240
1241         RaftActorContext context = mockRaftActor.getRaftActorContext();
1242         assertEquals("Journal log size", 1, context.getReplicatedLog().size());
1243         assertEquals("Last index", snapshotLastIndex, context.getReplicatedLog().lastIndex());
1244         assertEquals("Last applied", snapshotLastApplied, context.getLastApplied());
1245         assertEquals("Commit index", snapshotLastApplied, context.getCommitIndex());
1246         assertEquals("Recovered state", state, mockRaftActor.getState());
1247         assertEquals("Current term", 1L, context.getTermInformation().getCurrentTerm());
1248         assertEquals("Voted for", "member-1", context.getTermInformation().getVotedFor());
1249
1250         // Test with data persistence disabled
1251
1252         snapshot = Snapshot.create(new byte[0], Collections.<ReplicatedLogEntry>emptyList(),
1253                 -1, -1, -1, -1, 5, "member-1");
1254
1255         persistenceId = factory.generateActorId("test-actor-");
1256
1257         raftActorRef = factory.createTestActor(MockRaftActor.builder().id(persistenceId).
1258                 config(config).restoreFromSnapshot(SerializationUtils.serialize(snapshot)).
1259                 persistent(Optional.of(Boolean.FALSE)).props().
1260                     withDispatcher(Dispatchers.DefaultDispatcherId()), persistenceId);
1261         mockRaftActor = raftActorRef.underlyingActor();
1262
1263         mockRaftActor.waitForRecoveryComplete();
1264         assertEquals("snapshot committed", true,
1265                 Uninterruptibles.awaitUninterruptibly(mockRaftActor.snapshotCommitted, 5, TimeUnit.SECONDS));
1266
1267         context = mockRaftActor.getRaftActorContext();
1268         assertEquals("Current term", 5L, context.getTermInformation().getCurrentTerm());
1269         assertEquals("Voted for", "member-1", context.getTermInformation().getVotedFor());
1270
1271         TEST_LOG.info("testRestoreFromSnapshot ending");
1272     }
1273
1274     @Test
1275     public void testRestoreFromSnapshotWithRecoveredData() throws Exception {
1276         TEST_LOG.info("testRestoreFromSnapshotWithRecoveredData starting");
1277
1278         String persistenceId = factory.generateActorId("test-actor-");
1279         DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
1280         config.setCustomRaftPolicyImplementationClass(DisableElectionsRaftPolicy.class.getName());
1281
1282         List<MockPayload> state = Arrays.asList(new MockRaftActorContext.MockPayload("A"));
1283         Snapshot snapshot = Snapshot.create(fromObject(state).toByteArray(), Arrays.<ReplicatedLogEntry>asList(),
1284                 5, 2, 5, 2, 2, "member-1");
1285
1286         InMemoryJournal.addEntry(persistenceId, 1, new MockRaftActorContext.MockReplicatedLogEntry(1, 0,
1287                 new MockRaftActorContext.MockPayload("B")));
1288
1289         TestActorRef<MockRaftActor> raftActorRef = factory.createTestActor(MockRaftActor.builder().id(persistenceId).
1290                 config(config).restoreFromSnapshot(SerializationUtils.serialize(snapshot)).props().
1291                     withDispatcher(Dispatchers.DefaultDispatcherId()), persistenceId);
1292         MockRaftActor mockRaftActor = raftActorRef.underlyingActor();
1293
1294         mockRaftActor.waitForRecoveryComplete();
1295
1296         Uninterruptibles.sleepUninterruptibly(500, TimeUnit.MILLISECONDS);
1297         verify(mockRaftActor.snapshotCohortDelegate, never()).applySnapshot(any(byte[].class));
1298
1299         RaftActorContext context = mockRaftActor.getRaftActorContext();
1300         assertEquals("Journal log size", 1, context.getReplicatedLog().size());
1301         assertEquals("Last index", 0, context.getReplicatedLog().lastIndex());
1302         assertEquals("Last applied", -1, context.getLastApplied());
1303         assertEquals("Commit index", -1, context.getCommitIndex());
1304         assertEquals("Current term", 0, context.getTermInformation().getCurrentTerm());
1305         assertEquals("Voted for", null, context.getTermInformation().getVotedFor());
1306
1307         TEST_LOG.info("testRestoreFromSnapshotWithRecoveredData ending");
1308     }
1309
1310     @Test
1311     public void testNonVotingOnRecovery() throws Exception {
1312         TEST_LOG.info("testNonVotingOnRecovery starting");
1313
1314         DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
1315         config.setElectionTimeoutFactor(1);
1316         config.setHeartBeatInterval(FiniteDuration.create(1, TimeUnit.MILLISECONDS));
1317
1318         String persistenceId = factory.generateActorId("test-actor-");
1319         InMemoryJournal.addEntry(persistenceId, 1,  new MockRaftActorContext.MockReplicatedLogEntry(1, 0,
1320                 new ServerConfigurationPayload(Arrays.asList(new ServerInfo(persistenceId, false)))));
1321
1322         TestActorRef<MockRaftActor> raftActorRef = factory.createTestActor(MockRaftActor.builder().id(persistenceId).
1323                 config(config).props().withDispatcher(Dispatchers.DefaultDispatcherId()), persistenceId);
1324         MockRaftActor mockRaftActor = raftActorRef.underlyingActor();
1325
1326         mockRaftActor.waitForInitializeBehaviorComplete();
1327
1328         // Sleep a bit and verify it didn't get an election timeout and schedule an election.
1329
1330         Uninterruptibles.sleepUninterruptibly(400, TimeUnit.MILLISECONDS);
1331         assertEquals("getRaftState", RaftState.Follower, mockRaftActor.getRaftState());
1332
1333         TEST_LOG.info("testNonVotingOnRecovery ending");
1334     }
1335
1336     @Test
1337     public void testLeaderTransitioning() throws Exception {
1338         TEST_LOG.info("testLeaderTransitioning starting");
1339
1340         TestActorRef<MessageCollectorActor> notifierActor = factory.createTestActor(
1341                 Props.create(MessageCollectorActor.class));
1342
1343         DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
1344         config.setCustomRaftPolicyImplementationClass(DisableElectionsRaftPolicy.class.getName());
1345
1346         String persistenceId = factory.generateActorId("test-actor-");
1347
1348         TestActorRef<MockRaftActor> raftActorRef = factory.createTestActor(MockRaftActor.builder().id(persistenceId).
1349                 config(config).roleChangeNotifier(notifierActor).props().withDispatcher(Dispatchers.DefaultDispatcherId()), persistenceId);
1350         MockRaftActor mockRaftActor = raftActorRef.underlyingActor();
1351
1352         mockRaftActor.waitForInitializeBehaviorComplete();
1353
1354         raftActorRef.tell(new AppendEntries(1L, "leader", 0L, 1L, Collections.<ReplicatedLogEntry>emptyList(),
1355                 0L, -1L, (short)1), ActorRef.noSender());
1356         LeaderStateChanged leaderStateChange = MessageCollectorActor.expectFirstMatching(
1357                 notifierActor, LeaderStateChanged.class);
1358         assertEquals("getLeaderId", "leader", leaderStateChange.getLeaderId());
1359
1360         MessageCollectorActor.clearMessages(notifierActor);
1361
1362         raftActorRef.tell(LeaderTransitioning.INSTANCE, ActorRef.noSender());
1363
1364         leaderStateChange = MessageCollectorActor.expectFirstMatching(notifierActor, LeaderStateChanged.class);
1365         assertEquals("getMemberId", persistenceId, leaderStateChange.getMemberId());
1366         assertEquals("getLeaderId", null, leaderStateChange.getLeaderId());
1367
1368         TEST_LOG.info("testLeaderTransitioning ending");
1369     }
1370 }

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