e5c8677b0466fa0b282a413ef2291dd0318ce01e
[controller.git] / opendaylight / md-sal / sal-akka-raft / src / test / java / org / opendaylight / controller / cluster / raft / RaftActorTest.java
1 package org.opendaylight.controller.cluster.raft;
2
3 import static org.junit.Assert.assertEquals;
4 import static org.junit.Assert.assertFalse;
5 import static org.junit.Assert.assertNotNull;
6 import static org.junit.Assert.assertNull;
7 import static org.mockito.Matchers.any;
8 import static org.mockito.Matchers.anyObject;
9 import static org.mockito.Matchers.eq;
10 import static org.mockito.Matchers.same;
11 import static org.mockito.Mockito.doReturn;
12 import static org.mockito.Mockito.mock;
13 import static org.mockito.Mockito.times;
14 import static org.mockito.Mockito.verify;
15 import akka.actor.ActorRef;
16 import akka.actor.PoisonPill;
17 import akka.actor.Props;
18 import akka.actor.Terminated;
19 import akka.japi.Procedure;
20 import akka.persistence.SaveSnapshotFailure;
21 import akka.persistence.SaveSnapshotSuccess;
22 import akka.persistence.SnapshotMetadata;
23 import akka.persistence.SnapshotOffer;
24 import akka.testkit.JavaTestKit;
25 import akka.testkit.TestActorRef;
26 import com.google.common.base.Optional;
27 import com.google.common.collect.ImmutableMap;
28 import com.google.common.util.concurrent.Uninterruptibles;
29 import com.google.protobuf.ByteString;
30 import java.io.ByteArrayOutputStream;
31 import java.io.ObjectOutputStream;
32 import java.util.ArrayList;
33 import java.util.Arrays;
34 import java.util.Collections;
35 import java.util.HashMap;
36 import java.util.List;
37 import java.util.Map;
38 import java.util.concurrent.TimeUnit;
39 import org.junit.After;
40 import org.junit.Before;
41 import org.junit.Test;
42 import org.opendaylight.controller.cluster.DataPersistenceProvider;
43 import org.opendaylight.controller.cluster.NonPersistentDataProvider;
44 import org.opendaylight.controller.cluster.notifications.LeaderStateChanged;
45 import org.opendaylight.controller.cluster.notifications.RoleChanged;
46 import org.opendaylight.controller.cluster.raft.RaftActor.UpdateElectionTerm;
47 import org.opendaylight.controller.cluster.raft.base.messages.ApplyJournalEntries;
48 import org.opendaylight.controller.cluster.raft.base.messages.ApplyLogEntries;
49 import org.opendaylight.controller.cluster.raft.base.messages.ApplySnapshot;
50 import org.opendaylight.controller.cluster.raft.base.messages.ApplyState;
51 import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshot;
52 import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshotReply;
53 import org.opendaylight.controller.cluster.raft.base.messages.DeleteEntries;
54 import org.opendaylight.controller.cluster.raft.base.messages.SendHeartBeat;
55 import org.opendaylight.controller.cluster.raft.behaviors.Follower;
56 import org.opendaylight.controller.cluster.raft.behaviors.Leader;
57 import org.opendaylight.controller.cluster.raft.behaviors.RaftActorBehavior;
58 import org.opendaylight.controller.cluster.raft.messages.AppendEntries;
59 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
60 import org.opendaylight.controller.cluster.raft.utils.InMemoryJournal;
61 import org.opendaylight.controller.cluster.raft.utils.InMemorySnapshotStore;
62 import org.opendaylight.controller.cluster.raft.utils.MessageCollectorActor;
63 import org.slf4j.Logger;
64 import org.slf4j.LoggerFactory;
65 import scala.concurrent.duration.FiniteDuration;
66
67 public class RaftActorTest extends AbstractActorTest {
68
69     static final Logger TEST_LOG = LoggerFactory.getLogger(RaftActorTest.class);
70
71     private TestActorFactory factory;
72
73     @Before
74     public void setUp(){
75         factory = new TestActorFactory(getSystem());
76     }
77
78     @After
79     public void tearDown() throws Exception {
80         factory.close();
81         InMemoryJournal.clear();
82         InMemorySnapshotStore.clear();
83     }
84
85     @Test
86     public void testConstruction() {
87         new RaftActorTestKit(getSystem(), "testConstruction").waitUntilLeader();
88     }
89
90     @Test
91     public void testFindLeaderWhenLeaderIsSelf(){
92         RaftActorTestKit kit = new RaftActorTestKit(getSystem(), "testFindLeader");
93         kit.waitUntilLeader();
94     }
95
96     @Test
97     public void testRaftActorRecoveryWithPersistenceEnabled() throws Exception {
98         TEST_LOG.info("testRaftActorRecoveryWithPersistenceEnabled starting");
99
100         new JavaTestKit(getSystem()) {{
101             String persistenceId = factory.generateActorId("follower-");
102
103             DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
104
105             // Set the heartbeat interval high to essentially disable election otherwise the test
106             // may fail if the actor is switched to Leader and the commitIndex is set to the last
107             // log entry.
108             config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
109
110             ImmutableMap<String, String> peerAddresses = ImmutableMap.<String, String>builder().put("member1", "address").build();
111             ActorRef followerActor = factory.createActor(MockRaftActor.props(persistenceId,
112                     peerAddresses, Optional.<ConfigParams>of(config)), persistenceId);
113
114             watch(followerActor);
115
116             List<ReplicatedLogEntry> snapshotUnappliedEntries = new ArrayList<>();
117             ReplicatedLogEntry entry1 = new MockRaftActorContext.MockReplicatedLogEntry(1, 4,
118                     new MockRaftActorContext.MockPayload("E"));
119             snapshotUnappliedEntries.add(entry1);
120
121             int lastAppliedDuringSnapshotCapture = 3;
122             int lastIndexDuringSnapshotCapture = 4;
123
124             // 4 messages as part of snapshot, which are applied to state
125             ByteString snapshotBytes = fromObject(Arrays.asList(
126                     new MockRaftActorContext.MockPayload("A"),
127                     new MockRaftActorContext.MockPayload("B"),
128                     new MockRaftActorContext.MockPayload("C"),
129                     new MockRaftActorContext.MockPayload("D")));
130
131             Snapshot snapshot = Snapshot.create(snapshotBytes.toByteArray(),
132                     snapshotUnappliedEntries, lastIndexDuringSnapshotCapture, 1,
133                     lastAppliedDuringSnapshotCapture, 1);
134             InMemorySnapshotStore.addSnapshot(persistenceId, snapshot);
135
136             // add more entries after snapshot is taken
137             List<ReplicatedLogEntry> entries = new ArrayList<>();
138             ReplicatedLogEntry entry2 = new MockRaftActorContext.MockReplicatedLogEntry(1, 5,
139                     new MockRaftActorContext.MockPayload("F", 2));
140             ReplicatedLogEntry entry3 = new MockRaftActorContext.MockReplicatedLogEntry(1, 6,
141                     new MockRaftActorContext.MockPayload("G", 3));
142             ReplicatedLogEntry entry4 = new MockRaftActorContext.MockReplicatedLogEntry(1, 7,
143                     new MockRaftActorContext.MockPayload("H", 4));
144             entries.add(entry2);
145             entries.add(entry3);
146             entries.add(entry4);
147
148             int lastAppliedToState = 5;
149             int lastIndex = 7;
150
151             InMemoryJournal.addEntry(persistenceId, 5, entry2);
152             // 2 entries are applied to state besides the 4 entries in snapshot
153             InMemoryJournal.addEntry(persistenceId, 6, new ApplyJournalEntries(lastAppliedToState));
154             InMemoryJournal.addEntry(persistenceId, 7, entry3);
155             InMemoryJournal.addEntry(persistenceId, 8, entry4);
156
157             // kill the actor
158             followerActor.tell(PoisonPill.getInstance(), null);
159             expectMsgClass(duration("5 seconds"), Terminated.class);
160
161             unwatch(followerActor);
162
163             //reinstate the actor
164             TestActorRef<MockRaftActor> ref = factory.createTestActor(
165                     MockRaftActor.props(persistenceId, peerAddresses, Optional.<ConfigParams>of(config)));
166
167             MockRaftActor mockRaftActor = ref.underlyingActor();
168
169             mockRaftActor.waitForRecoveryComplete();
170
171             RaftActorContext context = mockRaftActor.getRaftActorContext();
172             assertEquals("Journal log size", snapshotUnappliedEntries.size() + entries.size(),
173                     context.getReplicatedLog().size());
174             assertEquals("Journal data size", 10, context.getReplicatedLog().dataSize());
175             assertEquals("Last index", lastIndex, context.getReplicatedLog().lastIndex());
176             assertEquals("Last applied", lastAppliedToState, context.getLastApplied());
177             assertEquals("Commit index", lastAppliedToState, context.getCommitIndex());
178             assertEquals("Recovered state size", 6, mockRaftActor.getState().size());
179
180             mockRaftActor.waitForInitializeBehaviorComplete();
181
182             assertEquals("getRaftState", RaftState.Follower, mockRaftActor.getRaftState());
183         }};
184
185         TEST_LOG.info("testRaftActorRecoveryWithPersistenceEnabled ending");
186     }
187
188     @Test
189     public void testRaftActorRecoveryWithPersistenceDisabled() throws Exception {
190         new JavaTestKit(getSystem()) {{
191             String persistenceId = factory.generateActorId("follower-");
192
193             DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
194
195             config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
196
197             TestActorRef<MockRaftActor> ref = factory.createTestActor(MockRaftActor.props(persistenceId,
198                     ImmutableMap.<String, String>builder().put("member1", "address").build(),
199                     Optional.<ConfigParams>of(config), new NonPersistentDataProvider()), persistenceId);
200
201             MockRaftActor mockRaftActor = ref.underlyingActor();
202
203             mockRaftActor.waitForRecoveryComplete();
204
205             mockRaftActor.waitForInitializeBehaviorComplete();
206
207             assertEquals("getRaftState", RaftState.Follower, mockRaftActor.getRaftState());
208         }};
209     }
210
211     @Test
212     public void testRaftActorForwardsToRaftActorRecoverySupport() {
213         String persistenceId = factory.generateActorId("leader-");
214
215         DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
216
217         config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
218
219         TestActorRef<MockRaftActor> mockActorRef = factory.createTestActor(MockRaftActor.props(persistenceId,
220                 Collections.<String, String>emptyMap(), Optional.<ConfigParams>of(config)), persistenceId);
221
222         MockRaftActor mockRaftActor = mockActorRef.underlyingActor();
223
224         // Wait for akka's recovery to complete so it doesn't interfere.
225         mockRaftActor.waitForRecoveryComplete();
226
227         RaftActorRecoverySupport mockSupport = mock(RaftActorRecoverySupport.class);
228         mockRaftActor.setRaftActorRecoverySupport(mockSupport );
229
230         Snapshot snapshot = Snapshot.create(new byte[]{1}, Collections.<ReplicatedLogEntry>emptyList(), 3, 1, 3, 1);
231         SnapshotOffer snapshotOffer = new SnapshotOffer(new SnapshotMetadata("test", 6, 12345), snapshot);
232         mockRaftActor.handleRecover(snapshotOffer);
233
234         MockRaftActorContext.MockReplicatedLogEntry logEntry = new MockRaftActorContext.MockReplicatedLogEntry(1,
235                 1, new MockRaftActorContext.MockPayload("1", 5));
236         mockRaftActor.handleRecover(logEntry);
237
238         ApplyJournalEntries applyJournalEntries = new ApplyJournalEntries(2);
239         mockRaftActor.handleRecover(applyJournalEntries);
240
241         ApplyLogEntries applyLogEntries = new ApplyLogEntries(0);
242         mockRaftActor.handleRecover(applyLogEntries);
243
244         DeleteEntries deleteEntries = new DeleteEntries(1);
245         mockRaftActor.handleRecover(deleteEntries);
246
247         org.opendaylight.controller.cluster.raft.RaftActor.DeleteEntries deprecatedDeleteEntries =
248                 new org.opendaylight.controller.cluster.raft.RaftActor.DeleteEntries(1);
249         mockRaftActor.handleRecover(deprecatedDeleteEntries);
250
251         UpdateElectionTerm updateElectionTerm = new UpdateElectionTerm(5, "member2");
252         mockRaftActor.handleRecover(updateElectionTerm);
253
254         verify(mockSupport).handleRecoveryMessage(same(snapshotOffer));
255         verify(mockSupport).handleRecoveryMessage(same(logEntry));
256         verify(mockSupport).handleRecoveryMessage(same(applyJournalEntries));
257         verify(mockSupport).handleRecoveryMessage(same(applyLogEntries));
258         verify(mockSupport).handleRecoveryMessage(same(deleteEntries));
259         verify(mockSupport).handleRecoveryMessage(same(deprecatedDeleteEntries));
260         verify(mockSupport).handleRecoveryMessage(same(updateElectionTerm));
261     }
262
263     @Test
264     public void testRaftActorForwardsToRaftActorSnapshotMessageSupport() {
265         String persistenceId = factory.generateActorId("leader-");
266
267         DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
268
269         config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
270
271         RaftActorSnapshotMessageSupport mockSupport = mock(RaftActorSnapshotMessageSupport.class);
272
273         TestActorRef<MockRaftActor> mockActorRef = factory.createTestActor(MockRaftActor.props(persistenceId,
274                 Collections.<String, String>emptyMap(), Optional.<ConfigParams>of(config), mockSupport), persistenceId);
275
276         MockRaftActor mockRaftActor = mockActorRef.underlyingActor();
277
278         // Wait for akka's recovery to complete so it doesn't interfere.
279         mockRaftActor.waitForRecoveryComplete();
280
281         ApplySnapshot applySnapshot = new ApplySnapshot(mock(Snapshot.class));
282         doReturn(true).when(mockSupport).handleSnapshotMessage(same(applySnapshot));
283         mockRaftActor.handleCommand(applySnapshot);
284
285         CaptureSnapshot captureSnapshot = new CaptureSnapshot(1, 1, 1, 1, 0, 1, null);
286         doReturn(true).when(mockSupport).handleSnapshotMessage(same(captureSnapshot));
287         mockRaftActor.handleCommand(captureSnapshot);
288
289         CaptureSnapshotReply captureSnapshotReply = new CaptureSnapshotReply(new byte[0]);
290         doReturn(true).when(mockSupport).handleSnapshotMessage(same(captureSnapshotReply));
291         mockRaftActor.handleCommand(captureSnapshotReply);
292
293         SaveSnapshotSuccess saveSnapshotSuccess = new SaveSnapshotSuccess(mock(SnapshotMetadata.class));
294         doReturn(true).when(mockSupport).handleSnapshotMessage(same(saveSnapshotSuccess));
295         mockRaftActor.handleCommand(saveSnapshotSuccess);
296
297         SaveSnapshotFailure saveSnapshotFailure = new SaveSnapshotFailure(mock(SnapshotMetadata.class), new Throwable());
298         doReturn(true).when(mockSupport).handleSnapshotMessage(same(saveSnapshotFailure));
299         mockRaftActor.handleCommand(saveSnapshotFailure);
300
301         doReturn(true).when(mockSupport).handleSnapshotMessage(same(RaftActorSnapshotMessageSupport.COMMIT_SNAPSHOT));
302         mockRaftActor.handleCommand(RaftActorSnapshotMessageSupport.COMMIT_SNAPSHOT);
303
304         verify(mockSupport).handleSnapshotMessage(same(applySnapshot));
305         verify(mockSupport).handleSnapshotMessage(same(captureSnapshot));
306         verify(mockSupport).handleSnapshotMessage(same(captureSnapshotReply));
307         verify(mockSupport).handleSnapshotMessage(same(saveSnapshotSuccess));
308         verify(mockSupport).handleSnapshotMessage(same(saveSnapshotFailure));
309         verify(mockSupport).handleSnapshotMessage(same(RaftActorSnapshotMessageSupport.COMMIT_SNAPSHOT));
310     }
311
312     @Test
313     public void testApplyJournalEntriesCallsDataPersistence() throws Exception {
314         new JavaTestKit(getSystem()) {
315             {
316                 String persistenceId = factory.generateActorId("leader-");
317
318                 DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
319
320                 config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
321
322                 DataPersistenceProvider dataPersistenceProvider = mock(DataPersistenceProvider.class);
323
324                 TestActorRef<MockRaftActor> mockActorRef = factory.createTestActor(MockRaftActor.props(persistenceId,
325                         Collections.<String, String>emptyMap(), Optional.<ConfigParams>of(config), dataPersistenceProvider), persistenceId);
326
327                 MockRaftActor mockRaftActor = mockActorRef.underlyingActor();
328
329                 mockRaftActor.waitForInitializeBehaviorComplete();
330
331                 mockRaftActor.waitUntilLeader();
332
333                 mockRaftActor.onReceiveCommand(new ApplyJournalEntries(10));
334
335                 verify(dataPersistenceProvider, times(2)).persist(anyObject(), any(Procedure.class));
336
337             }
338
339         };
340     }
341
342     @Test
343     public void testApplyState() throws Exception {
344
345         new JavaTestKit(getSystem()) {
346             {
347                 String persistenceId = factory.generateActorId("leader-");
348
349                 DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
350
351                 config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
352
353                 DataPersistenceProvider dataPersistenceProvider = mock(DataPersistenceProvider.class);
354
355                 TestActorRef<MockRaftActor> mockActorRef = factory.createTestActor(MockRaftActor.props(persistenceId,
356                         Collections.<String, String>emptyMap(), Optional.<ConfigParams>of(config), dataPersistenceProvider), persistenceId);
357
358                 MockRaftActor mockRaftActor = mockActorRef.underlyingActor();
359
360                 mockRaftActor.waitForInitializeBehaviorComplete();
361
362                 ReplicatedLogEntry entry = new MockRaftActorContext.MockReplicatedLogEntry(1, 5,
363                         new MockRaftActorContext.MockPayload("F"));
364
365                 mockRaftActor.onReceiveCommand(new ApplyState(mockActorRef, "apply-state", entry));
366
367                 verify(mockRaftActor.actorDelegate).applyState(eq(mockActorRef), eq("apply-state"), anyObject());
368
369             }
370         };
371     }
372
373     @Test
374     public void testRaftRoleChangeNotifierWhenRaftActorHasNoPeers() throws Exception {
375         new JavaTestKit(getSystem()) {{
376             TestActorRef<MessageCollectorActor> notifierActor = factory.createTestActor(
377                     Props.create(MessageCollectorActor.class));
378             MessageCollectorActor.waitUntilReady(notifierActor);
379
380             DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
381             long heartBeatInterval = 100;
382             config.setHeartBeatInterval(FiniteDuration.create(heartBeatInterval, TimeUnit.MILLISECONDS));
383             config.setElectionTimeoutFactor(20);
384
385             String persistenceId = factory.generateActorId("notifier-");
386
387             TestActorRef<MockRaftActor> raftActorRef = factory.createTestActor(MockRaftActor.props(persistenceId,
388                     Collections.<String, String>emptyMap(), Optional.<ConfigParams>of(config), notifierActor,
389                     new NonPersistentDataProvider()), persistenceId);
390
391             List<RoleChanged> matches =  MessageCollectorActor.expectMatching(notifierActor, RoleChanged.class, 3);
392
393
394             // check if the notifier got a role change from null to Follower
395             RoleChanged raftRoleChanged = matches.get(0);
396             assertEquals(persistenceId, raftRoleChanged.getMemberId());
397             assertNull(raftRoleChanged.getOldRole());
398             assertEquals(RaftState.Follower.name(), raftRoleChanged.getNewRole());
399
400             // check if the notifier got a role change from Follower to Candidate
401             raftRoleChanged = matches.get(1);
402             assertEquals(persistenceId, raftRoleChanged.getMemberId());
403             assertEquals(RaftState.Follower.name(), raftRoleChanged.getOldRole());
404             assertEquals(RaftState.Candidate.name(), raftRoleChanged.getNewRole());
405
406             // check if the notifier got a role change from Candidate to Leader
407             raftRoleChanged = matches.get(2);
408             assertEquals(persistenceId, raftRoleChanged.getMemberId());
409             assertEquals(RaftState.Candidate.name(), raftRoleChanged.getOldRole());
410             assertEquals(RaftState.Leader.name(), raftRoleChanged.getNewRole());
411
412             LeaderStateChanged leaderStateChange = MessageCollectorActor.expectFirstMatching(
413                     notifierActor, LeaderStateChanged.class);
414
415             assertEquals(raftRoleChanged.getMemberId(), leaderStateChange.getLeaderId());
416
417             notifierActor.underlyingActor().clear();
418
419             MockRaftActor raftActor = raftActorRef.underlyingActor();
420             final String newLeaderId = "new-leader";
421             Follower follower = new Follower(raftActor.getRaftActorContext()) {
422                 @Override
423                 public RaftActorBehavior handleMessage(ActorRef sender, Object message) {
424                     leaderId = newLeaderId;
425                     return this;
426                 }
427             };
428
429             raftActor.changeCurrentBehavior(follower);
430
431             leaderStateChange = MessageCollectorActor.expectFirstMatching(notifierActor, LeaderStateChanged.class);
432             assertEquals(persistenceId, leaderStateChange.getMemberId());
433             assertEquals(null, leaderStateChange.getLeaderId());
434
435             raftRoleChanged = MessageCollectorActor.expectFirstMatching(notifierActor, RoleChanged.class);
436             assertEquals(RaftState.Leader.name(), raftRoleChanged.getOldRole());
437             assertEquals(RaftState.Follower.name(), raftRoleChanged.getNewRole());
438
439             notifierActor.underlyingActor().clear();
440
441             raftActor.handleCommand("any");
442
443             leaderStateChange = MessageCollectorActor.expectFirstMatching(notifierActor, LeaderStateChanged.class);
444             assertEquals(persistenceId, leaderStateChange.getMemberId());
445             assertEquals(newLeaderId, leaderStateChange.getLeaderId());
446         }};
447     }
448
449     @Test
450     public void testRaftRoleChangeNotifierWhenRaftActorHasPeers() throws Exception {
451         new JavaTestKit(getSystem()) {{
452             ActorRef notifierActor = factory.createActor(Props.create(MessageCollectorActor.class));
453             MessageCollectorActor.waitUntilReady(notifierActor);
454
455             DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
456             long heartBeatInterval = 100;
457             config.setHeartBeatInterval(FiniteDuration.create(heartBeatInterval, TimeUnit.MILLISECONDS));
458             config.setElectionTimeoutFactor(1);
459
460             String persistenceId = factory.generateActorId("notifier-");
461
462             factory.createActor(MockRaftActor.props(persistenceId,
463                     ImmutableMap.of("leader", "fake/path"), Optional.<ConfigParams>of(config), notifierActor), persistenceId);
464
465             List<RoleChanged> matches =  null;
466             for(int i = 0; i < 5000 / heartBeatInterval; i++) {
467                 matches = MessageCollectorActor.getAllMatching(notifierActor, RoleChanged.class);
468                 assertNotNull(matches);
469                 if(matches.size() == 3) {
470                     break;
471                 }
472                 Uninterruptibles.sleepUninterruptibly(heartBeatInterval, TimeUnit.MILLISECONDS);
473             }
474
475             assertNotNull(matches);
476             assertEquals(2, matches.size());
477
478             // check if the notifier got a role change from null to Follower
479             RoleChanged raftRoleChanged = matches.get(0);
480             assertEquals(persistenceId, raftRoleChanged.getMemberId());
481             assertNull(raftRoleChanged.getOldRole());
482             assertEquals(RaftState.Follower.name(), raftRoleChanged.getNewRole());
483
484             // check if the notifier got a role change from Follower to Candidate
485             raftRoleChanged = matches.get(1);
486             assertEquals(persistenceId, raftRoleChanged.getMemberId());
487             assertEquals(RaftState.Follower.name(), raftRoleChanged.getOldRole());
488             assertEquals(RaftState.Candidate.name(), raftRoleChanged.getNewRole());
489
490         }};
491     }
492
493     @Test
494     public void testFakeSnapshotsForLeaderWithInRealSnapshots() throws Exception {
495         new JavaTestKit(getSystem()) {
496             {
497                 String persistenceId = factory.generateActorId("leader-");
498                 String follower1Id = factory.generateActorId("follower-");
499
500                 ActorRef followerActor1 =
501                         factory.createActor(Props.create(MessageCollectorActor.class));
502
503                 DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
504                 config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
505                 config.setIsolatedLeaderCheckInterval(new FiniteDuration(1, TimeUnit.DAYS));
506
507                 DataPersistenceProvider dataPersistenceProvider = mock(DataPersistenceProvider.class);
508
509                 Map<String, String> peerAddresses = new HashMap<>();
510                 peerAddresses.put(follower1Id, followerActor1.path().toString());
511
512                 TestActorRef<MockRaftActor> mockActorRef = factory.createTestActor(
513                         MockRaftActor.props(persistenceId, peerAddresses,
514                                 Optional.<ConfigParams>of(config), dataPersistenceProvider), persistenceId);
515
516                 MockRaftActor leaderActor = mockActorRef.underlyingActor();
517
518                 leaderActor.getRaftActorContext().setCommitIndex(4);
519                 leaderActor.getRaftActorContext().setLastApplied(4);
520                 leaderActor.getRaftActorContext().getTermInformation().update(1, persistenceId);
521
522                 leaderActor.waitForInitializeBehaviorComplete();
523
524                 // create 8 entries in the log - 0 to 4 are applied and will get picked up as part of the capture snapshot
525
526                 Leader leader = new Leader(leaderActor.getRaftActorContext());
527                 leaderActor.setCurrentBehavior(leader);
528                 assertEquals(RaftState.Leader, leaderActor.getCurrentBehavior().state());
529
530                 MockRaftActorContext.MockReplicatedLogBuilder logBuilder = new MockRaftActorContext.MockReplicatedLogBuilder();
531                 leaderActor.getRaftActorContext().setReplicatedLog(logBuilder.createEntries(0, 8, 1).build());
532
533                 assertEquals(8, leaderActor.getReplicatedLog().size());
534
535                 leaderActor.getRaftActorContext().getSnapshotManager()
536                         .capture(new MockRaftActorContext.MockReplicatedLogEntry(1, 6,
537                                 new MockRaftActorContext.MockPayload("x")), 4);
538
539                 verify(leaderActor.snapshotCohortDelegate).createSnapshot(any(ActorRef.class));
540
541                 assertEquals(8, leaderActor.getReplicatedLog().size());
542
543                 assertEquals(RaftState.Leader, leaderActor.getCurrentBehavior().state());
544                 //fake snapshot on index 5
545                 leaderActor.onReceiveCommand(new AppendEntriesReply(follower1Id, 1, true, 5, 1));
546
547                 assertEquals(8, leaderActor.getReplicatedLog().size());
548
549                 //fake snapshot on index 6
550                 assertEquals(RaftState.Leader, leaderActor.getCurrentBehavior().state());
551                 leaderActor.onReceiveCommand(new AppendEntriesReply(follower1Id, 1, true, 6, 1));
552                 assertEquals(8, leaderActor.getReplicatedLog().size());
553
554                 assertEquals(RaftState.Leader, leaderActor.getCurrentBehavior().state());
555
556                 assertEquals(8, leaderActor.getReplicatedLog().size());
557
558                 ByteString snapshotBytes = fromObject(Arrays.asList(
559                         new MockRaftActorContext.MockPayload("foo-0"),
560                         new MockRaftActorContext.MockPayload("foo-1"),
561                         new MockRaftActorContext.MockPayload("foo-2"),
562                         new MockRaftActorContext.MockPayload("foo-3"),
563                         new MockRaftActorContext.MockPayload("foo-4")));
564
565                 leaderActor.getRaftActorContext().getSnapshotManager().persist(snapshotBytes.toByteArray(),
566                         leader, Runtime.getRuntime().totalMemory());
567
568                 assertFalse(leaderActor.getRaftActorContext().getSnapshotManager().isCapturing());
569
570                 // The commit is needed to complete the snapshot creation process
571                 leaderActor.getRaftActorContext().getSnapshotManager().commit(-1);
572
573                 // capture snapshot reply should remove the snapshotted entries only
574                 assertEquals(3, leaderActor.getReplicatedLog().size());
575                 assertEquals(7, leaderActor.getReplicatedLog().lastIndex());
576
577                 // add another non-replicated entry
578                 leaderActor.getReplicatedLog().append(
579                         new ReplicatedLogImplEntry(8, 1, new MockRaftActorContext.MockPayload("foo-8")));
580
581                 //fake snapshot on index 7, since lastApplied = 7 , we would keep the last applied
582                 leaderActor.onReceiveCommand(new AppendEntriesReply(follower1Id, 1, true, 7, 1));
583                 assertEquals(2, leaderActor.getReplicatedLog().size());
584                 assertEquals(8, leaderActor.getReplicatedLog().lastIndex());
585
586             }
587         };
588     }
589
590     @Test
591     public void testFakeSnapshotsForFollowerWithInRealSnapshots() throws Exception {
592         new JavaTestKit(getSystem()) {
593             {
594                 String persistenceId = factory.generateActorId("follower-");
595                 String leaderId = factory.generateActorId("leader-");
596
597
598                 ActorRef leaderActor1 =
599                         factory.createActor(Props.create(MessageCollectorActor.class));
600
601                 DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
602                 config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
603                 config.setIsolatedLeaderCheckInterval(new FiniteDuration(1, TimeUnit.DAYS));
604
605                 DataPersistenceProvider dataPersistenceProvider = mock(DataPersistenceProvider.class);
606
607                 Map<String, String> peerAddresses = new HashMap<>();
608                 peerAddresses.put(leaderId, leaderActor1.path().toString());
609
610                 TestActorRef<MockRaftActor> mockActorRef = factory.createTestActor(
611                         MockRaftActor.props(persistenceId, peerAddresses,
612                                 Optional.<ConfigParams>of(config), dataPersistenceProvider), persistenceId);
613
614                 MockRaftActor followerActor = mockActorRef.underlyingActor();
615                 followerActor.getRaftActorContext().setCommitIndex(4);
616                 followerActor.getRaftActorContext().setLastApplied(4);
617                 followerActor.getRaftActorContext().getTermInformation().update(1, persistenceId);
618
619                 followerActor.waitForInitializeBehaviorComplete();
620
621
622                 Follower follower = new Follower(followerActor.getRaftActorContext());
623                 followerActor.setCurrentBehavior(follower);
624                 assertEquals(RaftState.Follower, followerActor.getCurrentBehavior().state());
625
626                 // create 6 entries in the log - 0 to 4 are applied and will get picked up as part of the capture snapshot
627                 MockRaftActorContext.MockReplicatedLogBuilder logBuilder = new MockRaftActorContext.MockReplicatedLogBuilder();
628                 followerActor.getRaftActorContext().setReplicatedLog(logBuilder.createEntries(0, 6, 1).build());
629
630                 // log has indices 0-5
631                 assertEquals(6, followerActor.getReplicatedLog().size());
632
633                 //snapshot on 4
634                 followerActor.getRaftActorContext().getSnapshotManager().capture(
635                         new MockRaftActorContext.MockReplicatedLogEntry(1, 5,
636                                 new MockRaftActorContext.MockPayload("D")), 4);
637
638                 verify(followerActor.snapshotCohortDelegate).createSnapshot(any(ActorRef.class));
639
640                 assertEquals(6, followerActor.getReplicatedLog().size());
641
642                 //fake snapshot on index 6
643                 List<ReplicatedLogEntry> entries =
644                         Arrays.asList(
645                                 (ReplicatedLogEntry) new MockRaftActorContext.MockReplicatedLogEntry(1, 6,
646                                         new MockRaftActorContext.MockPayload("foo-6"))
647                         );
648                 followerActor.onReceiveCommand(new AppendEntries(1, leaderId, 5, 1, entries, 5, 5));
649                 assertEquals(7, followerActor.getReplicatedLog().size());
650
651                 //fake snapshot on index 7
652                 assertEquals(RaftState.Follower, followerActor.getCurrentBehavior().state());
653
654                 entries =
655                         Arrays.asList(
656                                 (ReplicatedLogEntry) new MockRaftActorContext.MockReplicatedLogEntry(1, 7,
657                                         new MockRaftActorContext.MockPayload("foo-7"))
658                         );
659                 followerActor.onReceiveCommand(new AppendEntries(1, leaderId, 6, 1, entries, 6, 6));
660                 assertEquals(8, followerActor.getReplicatedLog().size());
661
662                 assertEquals(RaftState.Follower, followerActor.getCurrentBehavior().state());
663
664
665                 ByteString snapshotBytes = fromObject(Arrays.asList(
666                         new MockRaftActorContext.MockPayload("foo-0"),
667                         new MockRaftActorContext.MockPayload("foo-1"),
668                         new MockRaftActorContext.MockPayload("foo-2"),
669                         new MockRaftActorContext.MockPayload("foo-3"),
670                         new MockRaftActorContext.MockPayload("foo-4")));
671                 followerActor.onReceiveCommand(new CaptureSnapshotReply(snapshotBytes.toByteArray()));
672                 assertFalse(followerActor.getRaftActorContext().getSnapshotManager().isCapturing());
673
674                 // The commit is needed to complete the snapshot creation process
675                 followerActor.getRaftActorContext().getSnapshotManager().commit(-1);
676
677                 // capture snapshot reply should remove the snapshotted entries only till replicatedToAllIndex
678                 assertEquals(3, followerActor.getReplicatedLog().size()); //indexes 5,6,7 left in the log
679                 assertEquals(7, followerActor.getReplicatedLog().lastIndex());
680
681                 entries =
682                         Arrays.asList(
683                                 (ReplicatedLogEntry) new MockRaftActorContext.MockReplicatedLogEntry(1, 8,
684                                         new MockRaftActorContext.MockPayload("foo-7"))
685                         );
686                 // send an additional entry 8 with leaderCommit = 7
687                 followerActor.onReceiveCommand(new AppendEntries(1, leaderId, 7, 1, entries, 7, 7));
688
689                 // 7 and 8, as lastapplied is 7
690                 assertEquals(2, followerActor.getReplicatedLog().size());
691
692             }
693         };
694     }
695
696     @Test
697     public void testFakeSnapshotsForLeaderWithInInitiateSnapshots() throws Exception {
698         new JavaTestKit(getSystem()) {
699             {
700                 String persistenceId = factory.generateActorId("leader-");
701                 String follower1Id = factory.generateActorId("follower-");
702                 String follower2Id = factory.generateActorId("follower-");
703
704                 ActorRef followerActor1 =
705                         factory.createActor(Props.create(MessageCollectorActor.class), follower1Id);
706                 ActorRef followerActor2 =
707                         factory.createActor(Props.create(MessageCollectorActor.class), follower2Id);
708
709                 DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
710                 config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
711                 config.setIsolatedLeaderCheckInterval(new FiniteDuration(1, TimeUnit.DAYS));
712
713                 DataPersistenceProvider dataPersistenceProvider = mock(DataPersistenceProvider.class);
714
715                 Map<String, String> peerAddresses = new HashMap<>();
716                 peerAddresses.put(follower1Id, followerActor1.path().toString());
717                 peerAddresses.put(follower2Id, followerActor2.path().toString());
718
719                 TestActorRef<MockRaftActor> mockActorRef = factory.createTestActor(
720                         MockRaftActor.props(persistenceId, peerAddresses,
721                                 Optional.<ConfigParams>of(config), dataPersistenceProvider), persistenceId);
722
723                 MockRaftActor leaderActor = mockActorRef.underlyingActor();
724                 leaderActor.getRaftActorContext().setCommitIndex(9);
725                 leaderActor.getRaftActorContext().setLastApplied(9);
726                 leaderActor.getRaftActorContext().getTermInformation().update(1, persistenceId);
727
728                 leaderActor.waitForInitializeBehaviorComplete();
729
730                 Leader leader = new Leader(leaderActor.getRaftActorContext());
731                 leaderActor.setCurrentBehavior(leader);
732                 assertEquals(RaftState.Leader, leaderActor.getCurrentBehavior().state());
733
734                 // create 5 entries in the log
735                 MockRaftActorContext.MockReplicatedLogBuilder logBuilder = new MockRaftActorContext.MockReplicatedLogBuilder();
736                 leaderActor.getRaftActorContext().setReplicatedLog(logBuilder.createEntries(5, 10, 1).build());
737
738                 //set the snapshot index to 4 , 0 to 4 are snapshotted
739                 leaderActor.getRaftActorContext().getReplicatedLog().setSnapshotIndex(4);
740                 //setting replicatedToAllIndex = 9, for the log to clear
741                 leader.setReplicatedToAllIndex(9);
742                 assertEquals(5, leaderActor.getReplicatedLog().size());
743                 assertEquals(RaftState.Leader, leaderActor.getCurrentBehavior().state());
744
745                 leaderActor.onReceiveCommand(new AppendEntriesReply(follower1Id, 1, true, 9, 1));
746                 assertEquals(5, leaderActor.getReplicatedLog().size());
747                 assertEquals(RaftState.Leader, leaderActor.getCurrentBehavior().state());
748
749                 // set the 2nd follower nextIndex to 1 which has been snapshotted
750                 leaderActor.onReceiveCommand(new AppendEntriesReply(follower2Id, 1, true, 0, 1));
751                 assertEquals(5, leaderActor.getReplicatedLog().size());
752                 assertEquals(RaftState.Leader, leaderActor.getCurrentBehavior().state());
753
754                 // simulate a real snapshot
755                 leaderActor.onReceiveCommand(new SendHeartBeat());
756                 assertEquals(5, leaderActor.getReplicatedLog().size());
757                 assertEquals(String.format("expected to be Leader but was %s. Current Leader = %s ",
758                         leaderActor.getCurrentBehavior().state(), leaderActor.getLeaderId())
759                         , RaftState.Leader, leaderActor.getCurrentBehavior().state());
760
761
762                 //reply from a slow follower does not initiate a fake snapshot
763                 leaderActor.onReceiveCommand(new AppendEntriesReply(follower2Id, 1, true, 9, 1));
764                 assertEquals("Fake snapshot should not happen when Initiate is in progress", 5, leaderActor.getReplicatedLog().size());
765
766                 ByteString snapshotBytes = fromObject(Arrays.asList(
767                         new MockRaftActorContext.MockPayload("foo-0"),
768                         new MockRaftActorContext.MockPayload("foo-1"),
769                         new MockRaftActorContext.MockPayload("foo-2"),
770                         new MockRaftActorContext.MockPayload("foo-3"),
771                         new MockRaftActorContext.MockPayload("foo-4")));
772                 leaderActor.onReceiveCommand(new CaptureSnapshotReply(snapshotBytes.toByteArray()));
773                 assertFalse(leaderActor.getRaftActorContext().getSnapshotManager().isCapturing());
774
775                 assertEquals("Real snapshot didn't clear the log till replicatedToAllIndex", 0, leaderActor.getReplicatedLog().size());
776
777                 //reply from a slow follower after should not raise errors
778                 leaderActor.onReceiveCommand(new AppendEntriesReply(follower2Id, 1, true, 5, 1));
779                 assertEquals(0, leaderActor.getReplicatedLog().size());
780             }
781         };
782     }
783
784     @Test
785     public void testRealSnapshotWhenReplicatedToAllIndexMinusOne() throws Exception {
786         new JavaTestKit(getSystem()) {{
787             String persistenceId = factory.generateActorId("leader-");
788             DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
789             config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
790             config.setIsolatedLeaderCheckInterval(new FiniteDuration(1, TimeUnit.DAYS));
791             config.setSnapshotBatchCount(5);
792
793             DataPersistenceProvider dataPersistenceProvider = new NonPersistentDataProvider();
794
795             Map<String, String> peerAddresses = new HashMap<>();
796
797             TestActorRef<MockRaftActor> mockActorRef = factory.createTestActor(
798                     MockRaftActor.props(persistenceId, peerAddresses,
799                             Optional.<ConfigParams>of(config), dataPersistenceProvider), persistenceId);
800
801             MockRaftActor leaderActor = mockActorRef.underlyingActor();
802             leaderActor.getRaftActorContext().setCommitIndex(3);
803             leaderActor.getRaftActorContext().setLastApplied(3);
804             leaderActor.getRaftActorContext().getTermInformation().update(1, persistenceId);
805
806             leaderActor.waitForInitializeBehaviorComplete();
807             for(int i=0;i< 4;i++) {
808                 leaderActor.getReplicatedLog()
809                         .append(new MockRaftActorContext.MockReplicatedLogEntry(1, i,
810                                 new MockRaftActorContext.MockPayload("A")));
811             }
812
813             Leader leader = new Leader(leaderActor.getRaftActorContext());
814             leaderActor.setCurrentBehavior(leader);
815             assertEquals(RaftState.Leader, leaderActor.getCurrentBehavior().state());
816
817             // Persist another entry (this will cause a CaptureSnapshot to be triggered
818             leaderActor.persistData(mockActorRef, "x", new MockRaftActorContext.MockPayload("duh"));
819
820             // Now send a CaptureSnapshotReply
821             mockActorRef.tell(new CaptureSnapshotReply(fromObject("foo").toByteArray()), mockActorRef);
822
823             // Trimming log in this scenario is a no-op
824             assertEquals(-1, leaderActor.getReplicatedLog().getSnapshotIndex());
825             assertFalse(leaderActor.getRaftActorContext().getSnapshotManager().isCapturing());
826             assertEquals(-1, leader.getReplicatedToAllIndex());
827
828         }};
829     }
830
831     @Test
832     public void testRealSnapshotWhenReplicatedToAllIndexNotInReplicatedLog() throws Exception {
833         new JavaTestKit(getSystem()) {{
834             String persistenceId = factory.generateActorId("leader-");
835             DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
836             config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
837             config.setIsolatedLeaderCheckInterval(new FiniteDuration(1, TimeUnit.DAYS));
838             config.setSnapshotBatchCount(5);
839
840             DataPersistenceProvider dataPersistenceProvider = new NonPersistentDataProvider();
841
842             Map<String, String> peerAddresses = new HashMap<>();
843
844             TestActorRef<MockRaftActor> mockActorRef = factory.createTestActor(
845                     MockRaftActor.props(persistenceId, peerAddresses,
846                             Optional.<ConfigParams>of(config), dataPersistenceProvider), persistenceId);
847
848             MockRaftActor leaderActor = mockActorRef.underlyingActor();
849             leaderActor.getRaftActorContext().setCommitIndex(3);
850             leaderActor.getRaftActorContext().setLastApplied(3);
851             leaderActor.getRaftActorContext().getTermInformation().update(1, persistenceId);
852             leaderActor.getReplicatedLog().setSnapshotIndex(3);
853
854             leaderActor.waitForInitializeBehaviorComplete();
855             Leader leader = new Leader(leaderActor.getRaftActorContext());
856             leaderActor.setCurrentBehavior(leader);
857             leader.setReplicatedToAllIndex(3);
858             assertEquals(RaftState.Leader, leaderActor.getCurrentBehavior().state());
859
860             // Persist another entry (this will cause a CaptureSnapshot to be triggered
861             leaderActor.persistData(mockActorRef, "x", new MockRaftActorContext.MockPayload("duh"));
862
863             // Now send a CaptureSnapshotReply
864             mockActorRef.tell(new CaptureSnapshotReply(fromObject("foo").toByteArray()), mockActorRef);
865
866             // Trimming log in this scenario is a no-op
867             assertEquals(3, leaderActor.getReplicatedLog().getSnapshotIndex());
868             assertFalse(leaderActor.getRaftActorContext().getSnapshotManager().isCapturing());
869             assertEquals(3, leader.getReplicatedToAllIndex());
870
871         }};
872     }
873
874     public static ByteString fromObject(Object snapshot) throws Exception {
875         ByteArrayOutputStream b = null;
876         ObjectOutputStream o = null;
877         try {
878             b = new ByteArrayOutputStream();
879             o = new ObjectOutputStream(b);
880             o.writeObject(snapshot);
881             byte[] snapshotBytes = b.toByteArray();
882             return ByteString.copyFrom(snapshotBytes);
883         } finally {
884             if (o != null) {
885                 o.flush();
886                 o.close();
887             }
888             if (b != null) {
889                 b.close();
890             }
891         }
892     }
893
894 }

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