2 * Copyright (c) 2015 Brocade Communications Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.controller.cluster.raft;
10 import static akka.pattern.Patterns.ask;
11 import static org.junit.Assert.assertEquals;
12 import static org.junit.Assert.assertNotNull;
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;
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;
61 * Abstract base for an integration test that tests end-to-end RaftActor and behavior functionality.
63 * @author Thomas Pantelis
65 public abstract class AbstractRaftActorIntegrationTest extends AbstractActorTest {
67 private static final class MockIdentifier extends AbstractStringIdentifier<MockIdentifier> {
68 private static final long serialVersionUID = 1L;
70 protected MockIdentifier(String string) {
75 public static class SetPeerAddress {
76 private final String peerId;
77 private final String peerAddress;
79 public SetPeerAddress(String peerId, String peerAddress) {
81 this.peerAddress = peerAddress;
84 public String getPeerId() {
88 public String getPeerAddress() {
93 public static class TestRaftActor extends MockRaftActor {
95 private final TestActorRef<MessageCollectorActor> collectorActor;
96 private final Map<Class<?>, Predicate<?>> dropMessages = new ConcurrentHashMap<>();
98 private TestRaftActor(Builder builder) {
100 this.collectorActor = builder.collectorActor;
103 public void startDropMessages(Class<?> msgClass) {
104 dropMessages.put(msgClass, msg -> true);
107 <T> void startDropMessages(Class<T> msgClass, Predicate<T> filter) {
108 dropMessages.put(msgClass, filter);
111 public void stopDropMessages(Class<?> msgClass) {
112 dropMessages.remove(msgClass);
115 void setMockTotalMemory(final long mockTotalMemory) {
116 getRaftActorContext().setTotalMemoryRetriever(mockTotalMemory > 0 ? () -> mockTotalMemory : null);
119 @SuppressWarnings({ "rawtypes", "unchecked", "checkstyle:IllegalCatch" })
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);
128 if (message instanceof ServerConfigurationPayload) {
129 super.persistData(collectorActor, new MockIdentifier("serverConfig"), (Payload) message, false);
133 if (message instanceof SetPeerAddress) {
134 setPeerAddress(((SetPeerAddress) message).getPeerId().toString(),
135 ((SetPeerAddress) message).getPeerAddress());
140 Predicate drop = dropMessages.get(message.getClass());
141 if (drop == null || !drop.test(message)) {
142 super.handleCommand(message);
145 if (!(message instanceof SendHeartBeat)) {
147 collectorActor.tell(message, ActorRef.noSender());
148 } catch (Exception e) {
149 LOG.error("MessageCollectorActor error", e);
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());
163 actorRef.tell(new CaptureSnapshotReply(snapshotState, installSnapshotStream), actorRef);
166 public ActorRef collectorActor() {
167 return collectorActor;
170 public static Builder newBuilder() {
171 return new Builder();
174 public static class Builder extends AbstractBuilder<Builder, TestRaftActor> {
175 private TestActorRef<MessageCollectorActor> collectorActor;
177 public Builder collectorActor(TestActorRef<MessageCollectorActor> newCollectorActor) {
178 this.collectorActor = newCollectorActor;
183 super(TestRaftActor.class);
188 protected static final int SNAPSHOT_CHUNK_SIZE = 100;
190 protected final Logger testLog = LoggerFactory.getLogger(getClass());
192 protected final TestActorFactory factory = new TestActorFactory(getSystem());
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;
201 protected String follower1Id = factory.generateActorId("follower");
202 protected TestActorRef<TestRaftActor> follower1Actor;
203 protected ActorRef follower1CollectorActor;
204 protected RaftActorBehavior follower1;
205 protected RaftActorContext follower1Context;
207 protected String follower2Id = factory.generateActorId("follower");
208 protected TestActorRef<TestRaftActor> follower2Actor;
209 protected ActorRef follower2CollectorActor;
210 protected RaftActorBehavior follower2;
211 protected RaftActorContext follower2Context;
213 protected ImmutableMap<String, String> peerAddresses;
215 protected long initialTerm = 5;
216 protected long currentTerm;
218 protected int snapshotBatchCount = 4;
219 protected int snapshotChunkSize = SNAPSHOT_CHUNK_SIZE;
221 protected List<MockPayload> expSnapshotState = new ArrayList<>();
224 public void tearDown() {
225 InMemoryJournal.clear();
226 InMemorySnapshotStore.clear();
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);
241 protected DefaultConfigParamsImpl newFollowerConfigParams() {
242 DefaultConfigParamsImpl configParams = new DefaultConfigParamsImpl();
243 configParams.setHeartBeatInterval(new FiniteDuration(500, TimeUnit.MILLISECONDS));
244 configParams.setElectionTimeoutFactor(1000);
248 protected void waitUntilLeader(ActorRef actorRef) {
249 RaftActorTestKit.waitUntilLeader(actorRef);
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));
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);
263 InvalidActorNameException lastEx = null;
264 for (int i = 0; i < 10; i++) {
266 return factory.createTestActor(builder.props().withDispatcher(Dispatchers.DefaultDispatcherId())
267 .withMailbox(Mailboxes.DefaultMailboxId()), id);
268 } catch (InvalidActorNameException e) {
270 Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
274 assertNotNull(lastEx);
278 protected void killActor(TestActorRef<TestRaftActor> actor) {
279 JavaTestKit testkit = new JavaTestKit(getSystem());
280 testkit.watch(actor);
282 actor.tell(PoisonPill.getInstance(), null);
283 testkit.expectMsgClass(JavaTestKit.duration("5 seconds"), Terminated.class);
285 testkit.unwatch(actor);
288 protected void verifyApplyJournalEntries(ActorRef actor, final long expIndex) {
289 MessageCollectorActor.expectFirstMatching(actor, ApplyJournalEntries.class,
290 msg -> msg.getToIndex() == expIndex);
293 protected void verifySnapshot(String prefix, Snapshot snapshot, long lastAppliedTerm,
294 long lastAppliedIndex, long lastTerm, long lastIndex)
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());
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));
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());
319 protected MockPayload sendPayloadData(ActorRef actor, String data) {
320 return sendPayloadData(actor, data, 0);
323 protected MockPayload sendPayloadData(ActorRef actor, String data, int size) {
326 payload = new MockPayload(data, size);
328 payload = new MockPayload(data);
331 actor.tell(payload, ActorRef.noSender());
335 protected void verifyApplyState(ApplyState applyState, ActorRef expClientActor,
336 String expId, long expTerm, long expIndex, Payload payload) {
337 assertEquals("ApplyState getClientActor", expClientActor, applyState.getClientActor());
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);
345 protected void verifyReplicatedLogEntry(ReplicatedLogEntry replicatedLogEntry, long expTerm, long expIndex,
347 assertEquals("ReplicatedLogEntry getTerm", expTerm, replicatedLogEntry.getTerm());
348 assertEquals("ReplicatedLogEntry getIndex", expIndex, replicatedLogEntry.getIndex());
349 assertEquals("ReplicatedLogEntry getData", payload, replicatedLogEntry.getData());
352 protected String testActorPath(String id) {
353 return factory.createTestActorPath(id);
356 protected void verifyLeadersTrimmedLog(long lastIndex) {
357 verifyTrimmedLog("Leader", leaderActor, lastIndex, lastIndex - 1);
360 protected void verifyLeadersTrimmedLog(long lastIndex, long replicatedToAllIndex) {
361 verifyTrimmedLog("Leader", leaderActor, lastIndex, replicatedToAllIndex);
364 protected void verifyFollowersTrimmedLog(int num, TestActorRef<TestRaftActor> actorRef, long lastIndex) {
365 verifyTrimmedLog("Follower " + num, actorRef, lastIndex, lastIndex - 1);
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());
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) {
391 OnDemandRaftState raftState = (OnDemandRaftState)Await.result(ask(raftActor,
392 GetOnDemandRaftState.INSTANCE, timeout), timeout.duration());
393 verifier.accept(raftState);
395 } catch (AssertionError e) {
397 Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
398 } catch (Exception e) {
399 lastError = new AssertionError("OnDemandRaftState failed", e);
400 Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);