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.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;
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;
56 * Abstract base for an integration test that tests end-to-end RaftActor and behavior functionality.
58 * @author Thomas Pantelis
60 public abstract class AbstractRaftActorIntegrationTest extends AbstractActorTest {
62 private static final class MockIdentifier extends AbstractStringIdentifier<MockIdentifier> {
63 private static final long serialVersionUID = 1L;
65 protected MockIdentifier(String string) {
70 public static class SetPeerAddress {
71 private final String peerId;
72 private final String peerAddress;
74 public SetPeerAddress(String peerId, String peerAddress) {
76 this.peerAddress = peerAddress;
79 public String getPeerId() {
83 public String getPeerAddress() {
88 public static class TestRaftActor extends MockRaftActor {
90 private final TestActorRef<MessageCollectorActor> collectorActor;
91 private final Map<Class<?>, Predicate<?>> dropMessages = new ConcurrentHashMap<>();
93 private TestRaftActor(Builder builder) {
95 this.collectorActor = builder.collectorActor;
98 public void startDropMessages(Class<?> msgClass) {
99 dropMessages.put(msgClass, msg -> true);
102 <T> void startDropMessages(Class<T> msgClass, Predicate<T> filter) {
103 dropMessages.put(msgClass, filter);
106 public void stopDropMessages(Class<?> msgClass) {
107 dropMessages.remove(msgClass);
110 void setMockTotalMemory(final long mockTotalMemory) {
111 getRaftActorContext().setTotalMemoryRetriever(mockTotalMemory > 0 ? () -> mockTotalMemory : null);
114 @SuppressWarnings({ "rawtypes", "unchecked", "checkstyle:IllegalCatch" })
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);
123 if (message instanceof ServerConfigurationPayload) {
124 super.persistData(collectorActor, new MockIdentifier("serverConfig"), (Payload) message, false);
128 if (message instanceof SetPeerAddress) {
129 setPeerAddress(((SetPeerAddress) message).getPeerId().toString(),
130 ((SetPeerAddress) message).getPeerAddress());
135 Predicate drop = dropMessages.get(message.getClass());
136 if (drop == null || !drop.test(message)) {
137 super.handleCommand(message);
140 if (!(message instanceof SendHeartBeat)) {
142 collectorActor.tell(message, ActorRef.noSender());
143 } catch (Exception e) {
144 LOG.error("MessageCollectorActor error", e);
151 @SuppressWarnings("checkstyle:IllegalCatch")
152 public void createSnapshot(ActorRef actorRef) {
154 actorRef.tell(new CaptureSnapshotReply(RaftActorTest.fromObject(getState()).toByteArray()), actorRef);
155 } catch (Exception e) {
156 Throwables.propagate(e);
160 public ActorRef collectorActor() {
161 return collectorActor;
164 public static Builder newBuilder() {
165 return new Builder();
168 public static class Builder extends AbstractBuilder<Builder, TestRaftActor> {
169 private TestActorRef<MessageCollectorActor> collectorActor;
171 public Builder collectorActor(TestActorRef<MessageCollectorActor> newCollectorActor) {
172 this.collectorActor = newCollectorActor;
177 super(TestRaftActor.class);
182 protected static final int SNAPSHOT_CHUNK_SIZE = 100;
184 protected final Logger testLog = LoggerFactory.getLogger(getClass());
186 protected final TestActorFactory factory = new TestActorFactory(getSystem());
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;
195 protected String follower1Id = factory.generateActorId("follower");
196 protected TestActorRef<TestRaftActor> follower1Actor;
197 protected ActorRef follower1CollectorActor;
198 protected RaftActorBehavior follower1;
199 protected RaftActorContext follower1Context;
201 protected String follower2Id = factory.generateActorId("follower");
202 protected TestActorRef<TestRaftActor> follower2Actor;
203 protected ActorRef follower2CollectorActor;
204 protected RaftActorBehavior follower2;
205 protected RaftActorContext follower2Context;
207 protected ImmutableMap<String, String> peerAddresses;
209 protected long initialTerm = 5;
210 protected long currentTerm;
212 protected int snapshotBatchCount = 4;
214 protected List<MockPayload> expSnapshotState = new ArrayList<>();
217 public void tearDown() {
218 InMemoryJournal.clear();
219 InMemorySnapshotStore.clear();
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);
234 protected DefaultConfigParamsImpl newFollowerConfigParams() {
235 DefaultConfigParamsImpl configParams = new DefaultConfigParamsImpl();
236 configParams.setHeartBeatInterval(new FiniteDuration(500, TimeUnit.MILLISECONDS));
237 configParams.setElectionTimeoutFactor(1000);
241 protected void waitUntilLeader(ActorRef actorRef) {
242 RaftActorTestKit.waitUntilLeader(actorRef);
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));
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);
256 InvalidActorNameException lastEx = null;
257 for (int i = 0; i < 10; i++) {
259 return factory.createTestActor(builder.props().withDispatcher(Dispatchers.DefaultDispatcherId()), id);
260 } catch (InvalidActorNameException e) {
262 Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
266 assertNotNull(lastEx);
270 protected void killActor(TestActorRef<TestRaftActor> actor) {
271 JavaTestKit testkit = new JavaTestKit(getSystem());
272 testkit.watch(actor);
274 actor.tell(PoisonPill.getInstance(), null);
275 testkit.expectMsgClass(JavaTestKit.duration("5 seconds"), Terminated.class);
277 testkit.unwatch(actor);
280 protected void verifyApplyJournalEntries(ActorRef actor, final long expIndex) {
281 MessageCollectorActor.expectFirstMatching(actor, ApplyJournalEntries.class,
282 msg -> msg.getToIndex() == expIndex);
285 @SuppressWarnings("unchecked")
286 protected void verifySnapshot(String prefix, Snapshot snapshot, long lastAppliedTerm,
287 long lastAppliedIndex, long lastTerm, long lastIndex)
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());
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));
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());
312 protected MockPayload sendPayloadData(ActorRef actor, String data) {
313 return sendPayloadData(actor, data, 0);
316 protected MockPayload sendPayloadData(ActorRef actor, String data, int size) {
319 payload = new MockPayload(data, size);
321 payload = new MockPayload(data);
324 actor.tell(payload, ActorRef.noSender());
328 protected void verifyApplyState(ApplyState applyState, ActorRef expClientActor,
329 String expId, long expTerm, long expIndex, Payload payload) {
330 assertEquals("ApplyState getClientActor", expClientActor, applyState.getClientActor());
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);
338 protected void verifyReplicatedLogEntry(ReplicatedLogEntry replicatedLogEntry, long expTerm, long expIndex,
340 assertEquals("ReplicatedLogEntry getTerm", expTerm, replicatedLogEntry.getTerm());
341 assertEquals("ReplicatedLogEntry getIndex", expIndex, replicatedLogEntry.getIndex());
342 assertEquals("ReplicatedLogEntry getData", payload, replicatedLogEntry.getData());
345 protected String testActorPath(String id) {
346 return factory.createTestActorPath(id);
349 protected void verifyLeadersTrimmedLog(long lastIndex) {
350 verifyTrimmedLog("Leader", leaderActor, lastIndex, lastIndex - 1);
353 protected void verifyLeadersTrimmedLog(long lastIndex, long replicatedToAllIndex) {
354 verifyTrimmedLog("Leader", leaderActor, lastIndex, replicatedToAllIndex);
357 protected void verifyFollowersTrimmedLog(int num, TestActorRef<TestRaftActor> actorRef, long lastIndex) {
358 verifyTrimmedLog("Follower " + num, actorRef, lastIndex, lastIndex - 1);
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());
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) {
384 OnDemandRaftState raftState = (OnDemandRaftState)Await.result(ask(raftActor,
385 GetOnDemandRaftState.INSTANCE, timeout), timeout.duration());
386 verifier.accept(raftState);
388 } catch (AssertionError e) {
390 Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
391 } catch (Exception e) {
392 lastError = new AssertionError("OnDemandRaftState failed", e);
393 Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);