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