Bug 2890: Chunk AppendEntries when single payload size exceeds threshold
[controller.git] / opendaylight / md-sal / sal-akka-raft / src / test / java / org / opendaylight / controller / cluster / raft / AbstractRaftActorIntegrationTest.java
1 /*
2  * Copyright (c) 2015 Brocade Communications Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.controller.cluster.raft;
9
10 import static akka.pattern.Patterns.ask;
11 import static org.junit.Assert.assertEquals;
12 import static org.junit.Assert.assertNotNull;
13
14 import akka.actor.ActorRef;
15 import akka.actor.InvalidActorNameException;
16 import akka.actor.PoisonPill;
17 import akka.actor.Terminated;
18 import akka.dispatch.Dispatchers;
19 import akka.dispatch.Mailboxes;
20 import akka.testkit.JavaTestKit;
21 import akka.testkit.TestActorRef;
22 import akka.util.Timeout;
23 import com.google.common.base.Stopwatch;
24 import com.google.common.collect.ImmutableMap;
25 import com.google.common.util.concurrent.Uninterruptibles;
26 import java.io.OutputStream;
27 import java.util.ArrayList;
28 import java.util.Collections;
29 import java.util.List;
30 import java.util.Map;
31 import java.util.Optional;
32 import java.util.concurrent.ConcurrentHashMap;
33 import java.util.concurrent.TimeUnit;
34 import java.util.function.Consumer;
35 import java.util.function.Predicate;
36 import org.apache.commons.lang3.SerializationUtils;
37 import org.junit.After;
38 import org.opendaylight.controller.cluster.raft.MockRaftActor.MockSnapshotState;
39 import org.opendaylight.controller.cluster.raft.MockRaftActorContext.MockPayload;
40 import org.opendaylight.controller.cluster.raft.base.messages.ApplyState;
41 import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshotReply;
42 import org.opendaylight.controller.cluster.raft.base.messages.SendHeartBeat;
43 import org.opendaylight.controller.cluster.raft.behaviors.RaftActorBehavior;
44 import org.opendaylight.controller.cluster.raft.client.messages.GetOnDemandRaftState;
45 import org.opendaylight.controller.cluster.raft.client.messages.OnDemandRaftState;
46 import org.opendaylight.controller.cluster.raft.persisted.ApplyJournalEntries;
47 import org.opendaylight.controller.cluster.raft.persisted.ServerConfigurationPayload;
48 import org.opendaylight.controller.cluster.raft.persisted.Snapshot;
49 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
50 import org.opendaylight.controller.cluster.raft.utils.InMemoryJournal;
51 import org.opendaylight.controller.cluster.raft.utils.InMemorySnapshotStore;
52 import org.opendaylight.controller.cluster.raft.utils.MessageCollectorActor;
53 import org.opendaylight.yangtools.concepts.Identifier;
54 import org.opendaylight.yangtools.util.AbstractStringIdentifier;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
57 import scala.concurrent.Await;
58 import scala.concurrent.duration.FiniteDuration;
59
60 /**
61  * Abstract base for an integration test that tests end-to-end RaftActor and behavior functionality.
62  *
63  * @author Thomas Pantelis
64  */
65 public abstract class AbstractRaftActorIntegrationTest extends AbstractActorTest {
66
67     private static final class MockIdentifier extends AbstractStringIdentifier<MockIdentifier> {
68         private static final long serialVersionUID = 1L;
69
70         protected MockIdentifier(String string) {
71             super(string);
72         }
73     }
74
75     public static class SetPeerAddress {
76         private final String peerId;
77         private final String peerAddress;
78
79         public SetPeerAddress(String peerId, String peerAddress) {
80             this.peerId = peerId;
81             this.peerAddress = peerAddress;
82         }
83
84         public String getPeerId() {
85             return peerId;
86         }
87
88         public String getPeerAddress() {
89             return peerAddress;
90         }
91     }
92
93     public static class TestRaftActor extends MockRaftActor {
94
95         private final TestActorRef<MessageCollectorActor> collectorActor;
96         private final Map<Class<?>, Predicate<?>> dropMessages = new ConcurrentHashMap<>();
97
98         private TestRaftActor(Builder builder) {
99             super(builder);
100             this.collectorActor = builder.collectorActor;
101         }
102
103         public void startDropMessages(Class<?> msgClass) {
104             dropMessages.put(msgClass, msg -> true);
105         }
106
107         <T> void startDropMessages(Class<T> msgClass, Predicate<T> filter) {
108             dropMessages.put(msgClass, filter);
109         }
110
111         public void stopDropMessages(Class<?> msgClass) {
112             dropMessages.remove(msgClass);
113         }
114
115         void setMockTotalMemory(final long mockTotalMemory) {
116             getRaftActorContext().setTotalMemoryRetriever(mockTotalMemory > 0 ? () -> mockTotalMemory : null);
117         }
118
119         @SuppressWarnings({ "rawtypes", "unchecked", "checkstyle:IllegalCatch" })
120         @Override
121         public void handleCommand(Object message) {
122             if (message instanceof MockPayload) {
123                 MockPayload payload = (MockPayload) message;
124                 super.persistData(collectorActor, new MockIdentifier(payload.toString()), payload, false);
125                 return;
126             }
127
128             if (message instanceof ServerConfigurationPayload) {
129                 super.persistData(collectorActor, new MockIdentifier("serverConfig"), (Payload) message, false);
130                 return;
131             }
132
133             if (message instanceof SetPeerAddress) {
134                 setPeerAddress(((SetPeerAddress) message).getPeerId().toString(),
135                         ((SetPeerAddress) message).getPeerAddress());
136                 return;
137             }
138
139             try {
140                 Predicate drop = dropMessages.get(message.getClass());
141                 if (drop == null || !drop.test(message)) {
142                     super.handleCommand(message);
143                 }
144             } finally {
145                 if (!(message instanceof SendHeartBeat)) {
146                     try {
147                         collectorActor.tell(message, ActorRef.noSender());
148                     } catch (Exception e) {
149                         LOG.error("MessageCollectorActor error", e);
150                     }
151                 }
152             }
153         }
154
155         @Override
156         @SuppressWarnings("checkstyle:IllegalCatch")
157         public void createSnapshot(ActorRef actorRef, Optional<OutputStream> installSnapshotStream) {
158             MockSnapshotState snapshotState = new MockSnapshotState(new ArrayList<>(getState()));
159             if (installSnapshotStream.isPresent()) {
160                 SerializationUtils.serialize(snapshotState, installSnapshotStream.get());
161             }
162
163             actorRef.tell(new CaptureSnapshotReply(snapshotState, installSnapshotStream), actorRef);
164         }
165
166         public ActorRef collectorActor() {
167             return collectorActor;
168         }
169
170         public static Builder newBuilder() {
171             return new Builder();
172         }
173
174         public static class Builder extends AbstractBuilder<Builder, TestRaftActor> {
175             private TestActorRef<MessageCollectorActor> collectorActor;
176
177             public Builder collectorActor(TestActorRef<MessageCollectorActor> newCollectorActor) {
178                 this.collectorActor = newCollectorActor;
179                 return this;
180             }
181
182             private Builder() {
183                 super(TestRaftActor.class);
184             }
185         }
186     }
187
188     protected static final int SNAPSHOT_CHUNK_SIZE = 100;
189
190     protected final Logger testLog = LoggerFactory.getLogger(getClass());
191
192     protected final TestActorFactory factory = new TestActorFactory(getSystem());
193
194     protected String leaderId = factory.generateActorId("leader");
195     protected DefaultConfigParamsImpl leaderConfigParams;
196     protected TestActorRef<TestRaftActor> leaderActor;
197     protected ActorRef leaderCollectorActor;
198     protected RaftActorContext leaderContext;
199     protected RaftActorBehavior leader;
200
201     protected String follower1Id = factory.generateActorId("follower");
202     protected TestActorRef<TestRaftActor> follower1Actor;
203     protected ActorRef follower1CollectorActor;
204     protected RaftActorBehavior follower1;
205     protected RaftActorContext follower1Context;
206
207     protected String follower2Id = factory.generateActorId("follower");
208     protected TestActorRef<TestRaftActor> follower2Actor;
209     protected ActorRef follower2CollectorActor;
210     protected  RaftActorBehavior follower2;
211     protected RaftActorContext follower2Context;
212
213     protected ImmutableMap<String, String> peerAddresses;
214
215     protected long initialTerm = 5;
216     protected long currentTerm;
217
218     protected int snapshotBatchCount = 4;
219     protected int snapshotChunkSize = SNAPSHOT_CHUNK_SIZE;
220
221     protected List<MockPayload> expSnapshotState = new ArrayList<>();
222
223     @After
224     public void tearDown() {
225         InMemoryJournal.clear();
226         InMemorySnapshotStore.clear();
227         factory.close();
228     }
229
230     protected DefaultConfigParamsImpl newLeaderConfigParams() {
231         DefaultConfigParamsImpl configParams = new DefaultConfigParamsImpl();
232         configParams.setHeartBeatInterval(new FiniteDuration(100, TimeUnit.MILLISECONDS));
233         configParams.setElectionTimeoutFactor(4);
234         configParams.setSnapshotBatchCount(snapshotBatchCount);
235         configParams.setSnapshotDataThresholdPercentage(70);
236         configParams.setIsolatedLeaderCheckInterval(new FiniteDuration(1, TimeUnit.DAYS));
237         configParams.setSnapshotChunkSize(snapshotChunkSize);
238         return configParams;
239     }
240
241     protected DefaultConfigParamsImpl newFollowerConfigParams() {
242         DefaultConfigParamsImpl configParams = new DefaultConfigParamsImpl();
243         configParams.setHeartBeatInterval(new FiniteDuration(500, TimeUnit.MILLISECONDS));
244         configParams.setElectionTimeoutFactor(1000);
245         return configParams;
246     }
247
248     protected void waitUntilLeader(ActorRef actorRef) {
249         RaftActorTestKit.waitUntilLeader(actorRef);
250     }
251
252     protected TestActorRef<TestRaftActor> newTestRaftActor(String id, Map<String, String> newPeerAddresses,
253             ConfigParams configParams) {
254         return newTestRaftActor(id, TestRaftActor.newBuilder().peerAddresses(newPeerAddresses != null
255                 ? newPeerAddresses : Collections.<String, String>emptyMap()).config(configParams));
256     }
257
258     protected TestActorRef<TestRaftActor> newTestRaftActor(String id, TestRaftActor.Builder builder) {
259         builder.collectorActor(factory.<MessageCollectorActor>createTestActor(
260                 MessageCollectorActor.props().withDispatcher(Dispatchers.DefaultDispatcherId()),
261                         factory.generateActorId(id + "-collector"))).id(id);
262
263         InvalidActorNameException lastEx = null;
264         for (int i = 0; i < 10; i++) {
265             try {
266                 return factory.createTestActor(builder.props().withDispatcher(Dispatchers.DefaultDispatcherId())
267                         .withMailbox(Mailboxes.DefaultMailboxId()), id);
268             } catch (InvalidActorNameException e) {
269                 lastEx = e;
270                 Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
271             }
272         }
273
274         assertNotNull(lastEx);
275         throw lastEx;
276     }
277
278     protected void killActor(TestActorRef<TestRaftActor> actor) {
279         JavaTestKit testkit = new JavaTestKit(getSystem());
280         testkit.watch(actor);
281
282         actor.tell(PoisonPill.getInstance(), null);
283         testkit.expectMsgClass(JavaTestKit.duration("5 seconds"), Terminated.class);
284
285         testkit.unwatch(actor);
286     }
287
288     protected void verifyApplyJournalEntries(ActorRef actor, final long expIndex) {
289         MessageCollectorActor.expectFirstMatching(actor, ApplyJournalEntries.class,
290             msg -> msg.getToIndex() == expIndex);
291     }
292
293     protected void verifySnapshot(String prefix, Snapshot snapshot, long lastAppliedTerm,
294             long lastAppliedIndex, long lastTerm, long lastIndex)
295                     throws Exception {
296         assertEquals(prefix + " Snapshot getLastAppliedTerm", lastAppliedTerm, snapshot.getLastAppliedTerm());
297         assertEquals(prefix + " Snapshot getLastAppliedIndex", lastAppliedIndex, snapshot.getLastAppliedIndex());
298         assertEquals(prefix + " Snapshot getLastTerm", lastTerm, snapshot.getLastTerm());
299         assertEquals(prefix + " Snapshot getLastIndex", lastIndex, snapshot.getLastIndex());
300
301         List<Object> actualState = ((MockSnapshotState)snapshot.getState()).getState();
302         assertEquals(String.format("%s Snapshot getState size. Expected %s: . Actual: %s", prefix, expSnapshotState,
303                 actualState), expSnapshotState.size(), actualState.size());
304         for (int i = 0; i < expSnapshotState.size(); i++) {
305             assertEquals(prefix + " Snapshot state " + i, expSnapshotState.get(i), actualState.get(i));
306         }
307     }
308
309     protected void verifyPersistedJournal(String persistenceId, List<? extends ReplicatedLogEntry> expJournal) {
310         List<ReplicatedLogEntry> journal = InMemoryJournal.get(persistenceId, ReplicatedLogEntry.class);
311         assertEquals("Journal ReplicatedLogEntry count", expJournal.size(), journal.size());
312         for (int i = 0; i < expJournal.size(); i++) {
313             ReplicatedLogEntry expected = expJournal.get(i);
314             ReplicatedLogEntry actual = journal.get(i);
315             verifyReplicatedLogEntry(expected, actual.getTerm(), actual.getIndex(), actual.getData());
316         }
317     }
318
319     protected MockPayload sendPayloadData(ActorRef actor, String data) {
320         return sendPayloadData(actor, data, 0);
321     }
322
323     protected MockPayload sendPayloadData(ActorRef actor, String data, int size) {
324         MockPayload payload;
325         if (size > 0) {
326             payload = new MockPayload(data, size);
327         } else {
328             payload = new MockPayload(data);
329         }
330
331         actor.tell(payload, ActorRef.noSender());
332         return payload;
333     }
334
335     protected void verifyApplyState(ApplyState applyState, ActorRef expClientActor,
336             String expId, long expTerm, long expIndex, Payload payload) {
337         assertEquals("ApplyState getClientActor", expClientActor, applyState.getClientActor());
338
339         final Identifier id = expId == null ? null : new MockIdentifier(expId);
340         assertEquals("ApplyState getIdentifier", id, applyState.getIdentifier());
341         ReplicatedLogEntry replicatedLogEntry = applyState.getReplicatedLogEntry();
342         verifyReplicatedLogEntry(replicatedLogEntry, expTerm, expIndex, payload);
343     }
344
345     protected void verifyReplicatedLogEntry(ReplicatedLogEntry replicatedLogEntry, long expTerm, long expIndex,
346             Payload payload) {
347         assertEquals("ReplicatedLogEntry getTerm", expTerm, replicatedLogEntry.getTerm());
348         assertEquals("ReplicatedLogEntry getIndex", expIndex, replicatedLogEntry.getIndex());
349         assertEquals("ReplicatedLogEntry getData", payload, replicatedLogEntry.getData());
350     }
351
352     protected String testActorPath(String id) {
353         return factory.createTestActorPath(id);
354     }
355
356     protected void verifyLeadersTrimmedLog(long lastIndex) {
357         verifyTrimmedLog("Leader", leaderActor, lastIndex, lastIndex - 1);
358     }
359
360     protected void verifyLeadersTrimmedLog(long lastIndex, long replicatedToAllIndex) {
361         verifyTrimmedLog("Leader", leaderActor, lastIndex, replicatedToAllIndex);
362     }
363
364     protected void verifyFollowersTrimmedLog(int num, TestActorRef<TestRaftActor> actorRef, long lastIndex) {
365         verifyTrimmedLog("Follower " + num, actorRef, lastIndex, lastIndex - 1);
366     }
367
368     protected void verifyTrimmedLog(String name, TestActorRef<TestRaftActor> actorRef, long lastIndex,
369             long replicatedToAllIndex) {
370         TestRaftActor actor = actorRef.underlyingActor();
371         RaftActorContext context = actor.getRaftActorContext();
372         long snapshotIndex = lastIndex - 1;
373         assertEquals(name + " snapshot term", snapshotIndex < 0 ? -1 : currentTerm,
374                 context.getReplicatedLog().getSnapshotTerm());
375         assertEquals(name + " snapshot index", snapshotIndex, context.getReplicatedLog().getSnapshotIndex());
376         assertEquals(name + " journal log size", 1, context.getReplicatedLog().size());
377         assertEquals(name + " journal last index", lastIndex, context.getReplicatedLog().lastIndex());
378         assertEquals(name + " commit index", lastIndex, context.getCommitIndex());
379         assertEquals(name + " last applied", lastIndex, context.getLastApplied());
380         assertEquals(name + " replicatedToAllIndex", replicatedToAllIndex,
381                 actor.getCurrentBehavior().getReplicatedToAllIndex());
382     }
383
384     @SuppressWarnings("checkstyle:IllegalCatch")
385     static void verifyRaftState(ActorRef raftActor, Consumer<OnDemandRaftState> verifier) {
386         Timeout timeout = new Timeout(500, TimeUnit.MILLISECONDS);
387         AssertionError lastError = null;
388         Stopwatch sw = Stopwatch.createStarted();
389         while (sw.elapsed(TimeUnit.SECONDS) <= 5) {
390             try {
391                 OnDemandRaftState raftState = (OnDemandRaftState)Await.result(ask(raftActor,
392                         GetOnDemandRaftState.INSTANCE, timeout), timeout.duration());
393                 verifier.accept(raftState);
394                 return;
395             } catch (AssertionError e) {
396                 lastError = e;
397                 Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
398             } catch (Exception e) {
399                 lastError = new AssertionError("OnDemandRaftState failed", e);
400                 Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
401             }
402         }
403
404         throw lastError;
405     }
406 }