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

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