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

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