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;
13 import akka.actor.ActorRef;
14 import akka.actor.InvalidActorNameException;
15 import akka.actor.PoisonPill;
16 import akka.actor.Terminated;
17 import akka.dispatch.Dispatchers;
18 import akka.testkit.JavaTestKit;
19 import akka.testkit.TestActorRef;
20 import akka.util.Timeout;
21 import com.google.common.base.Stopwatch;
22 import com.google.common.collect.ImmutableMap;
23 import com.google.common.util.concurrent.Uninterruptibles;
24 import java.util.ArrayList;
25 import java.util.Collections;
26 import java.util.List;
28 import java.util.concurrent.ConcurrentHashMap;
29 import java.util.concurrent.TimeUnit;
30 import java.util.function.Consumer;
31 import java.util.function.Predicate;
32 import org.junit.After;
33 import org.opendaylight.controller.cluster.raft.MockRaftActorContext.MockPayload;
34 import org.opendaylight.controller.cluster.raft.base.messages.ApplyState;
35 import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshotReply;
36 import org.opendaylight.controller.cluster.raft.base.messages.SendHeartBeat;
37 import org.opendaylight.controller.cluster.raft.behaviors.RaftActorBehavior;
38 import org.opendaylight.controller.cluster.raft.client.messages.GetOnDemandRaftState;
39 import org.opendaylight.controller.cluster.raft.client.messages.OnDemandRaftState;
40 import org.opendaylight.controller.cluster.raft.persisted.ApplyJournalEntries;
41 import org.opendaylight.controller.cluster.raft.persisted.ServerConfigurationPayload;
42 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
43 import org.opendaylight.controller.cluster.raft.utils.InMemoryJournal;
44 import org.opendaylight.controller.cluster.raft.utils.InMemorySnapshotStore;
45 import org.opendaylight.controller.cluster.raft.utils.MessageCollectorActor;
46 import org.opendaylight.yangtools.concepts.Identifier;
47 import org.opendaylight.yangtools.util.AbstractStringIdentifier;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50 import scala.concurrent.Await;
51 import scala.concurrent.duration.FiniteDuration;
54 * Abstract base for an integration test that tests end-to-end RaftActor and behavior functionality.
56 * @author Thomas Pantelis
58 public abstract class AbstractRaftActorIntegrationTest extends AbstractActorTest {
60 private static final class MockIdentifier extends AbstractStringIdentifier<MockIdentifier> {
61 private static final long serialVersionUID = 1L;
63 protected MockIdentifier(String string) {
68 public static class SetPeerAddress {
69 private final String peerId;
70 private final String peerAddress;
72 public SetPeerAddress(String peerId, String peerAddress) {
74 this.peerAddress = peerAddress;
77 public String getPeerId() {
81 public String getPeerAddress() {
86 public static class TestRaftActor extends MockRaftActor {
88 private final TestActorRef<MessageCollectorActor> collectorActor;
89 private final Map<Class<?>, Predicate<?>> dropMessages = new ConcurrentHashMap<>();
91 private TestRaftActor(Builder builder) {
93 this.collectorActor = builder.collectorActor;
96 public void startDropMessages(Class<?> msgClass) {
97 dropMessages.put(msgClass, msg -> true);
100 <T> void startDropMessages(Class<T> msgClass, Predicate<T> filter) {
101 dropMessages.put(msgClass, filter);
104 public void stopDropMessages(Class<?> msgClass) {
105 dropMessages.remove(msgClass);
108 void setMockTotalMemory(final long mockTotalMemory) {
109 getRaftActorContext().setTotalMemoryRetriever(mockTotalMemory > 0 ? () -> mockTotalMemory : null);
112 @SuppressWarnings({ "rawtypes", "unchecked" })
114 public void handleCommand(Object message) {
115 if(message instanceof MockPayload) {
116 MockPayload payload = (MockPayload)message;
117 super.persistData(collectorActor, new MockIdentifier(payload.toString()), payload);
121 if(message instanceof ServerConfigurationPayload) {
122 super.persistData(collectorActor, new MockIdentifier("serverConfig"), (Payload)message);
126 if(message instanceof SetPeerAddress) {
127 setPeerAddress(((SetPeerAddress) message).getPeerId().toString(),
128 ((SetPeerAddress) message).getPeerAddress());
133 Predicate drop = dropMessages.get(message.getClass());
134 if(drop == null || !drop.test(message)) {
135 super.handleCommand(message);
138 if(!(message instanceof SendHeartBeat)) {
140 collectorActor.tell(message, ActorRef.noSender());
141 } catch (Exception e) {
142 LOG.error("MessageCollectorActor error", e);
149 public void createSnapshot(ActorRef actorRef) {
151 actorRef.tell(new CaptureSnapshotReply(RaftActorTest.fromObject(getState()).toByteArray()), actorRef);
152 } catch (Exception e) {
157 public ActorRef collectorActor() {
158 return collectorActor;
161 public static Builder newBuilder() {
162 return new Builder();
165 public static class Builder extends AbstractBuilder<Builder, TestRaftActor> {
166 private TestActorRef<MessageCollectorActor> collectorActor;
168 public Builder collectorActor(TestActorRef<MessageCollectorActor> collectorActor) {
169 this.collectorActor = collectorActor;
174 super(TestRaftActor.class);
179 protected static final int SNAPSHOT_CHUNK_SIZE = 100;
181 protected final Logger testLog = LoggerFactory.getLogger(getClass());
183 protected final TestActorFactory factory = new TestActorFactory(getSystem());
185 protected String leaderId = factory.generateActorId("leader");
186 protected DefaultConfigParamsImpl leaderConfigParams;
187 protected TestActorRef<TestRaftActor> leaderActor;
188 protected ActorRef leaderCollectorActor;
189 protected RaftActorContext leaderContext;
190 protected RaftActorBehavior leader;
192 protected String follower1Id = factory.generateActorId("follower");
193 protected TestActorRef<TestRaftActor> follower1Actor;
194 protected ActorRef follower1CollectorActor;
195 protected RaftActorBehavior follower1;
196 protected RaftActorContext follower1Context;
198 protected String follower2Id = factory.generateActorId("follower");
199 protected TestActorRef<TestRaftActor> follower2Actor;
200 protected ActorRef follower2CollectorActor;
201 protected RaftActorBehavior follower2;
202 protected RaftActorContext follower2Context;
204 protected ImmutableMap<String, String> peerAddresses;
206 protected long initialTerm = 5;
207 protected long currentTerm;
209 protected int snapshotBatchCount = 4;
211 protected List<MockPayload> expSnapshotState = new ArrayList<>();
214 public void tearDown() {
215 InMemoryJournal.clear();
216 InMemorySnapshotStore.clear();
220 protected DefaultConfigParamsImpl newLeaderConfigParams() {
221 DefaultConfigParamsImpl configParams = new DefaultConfigParamsImpl();
222 configParams.setHeartBeatInterval(new FiniteDuration(100, TimeUnit.MILLISECONDS));
223 configParams.setElectionTimeoutFactor(4);
224 configParams.setSnapshotBatchCount(snapshotBatchCount);
225 configParams.setSnapshotDataThresholdPercentage(70);
226 configParams.setIsolatedLeaderCheckInterval(new FiniteDuration(1, TimeUnit.DAYS));
227 configParams.setSnapshotChunkSize(SNAPSHOT_CHUNK_SIZE);
231 protected DefaultConfigParamsImpl newFollowerConfigParams() {
232 DefaultConfigParamsImpl configParams = new DefaultConfigParamsImpl();
233 configParams.setHeartBeatInterval(new FiniteDuration(500, TimeUnit.MILLISECONDS));
234 configParams.setElectionTimeoutFactor(1000);
238 protected void waitUntilLeader(ActorRef actorRef) {
239 RaftActorTestKit.waitUntilLeader(actorRef);
242 protected TestActorRef<TestRaftActor> newTestRaftActor(String id, Map<String, String> peerAddresses,
243 ConfigParams configParams) {
244 return newTestRaftActor(id, TestRaftActor.newBuilder().peerAddresses(peerAddresses != null ? peerAddresses :
245 Collections.<String, String>emptyMap()).config(configParams));
248 protected TestActorRef<TestRaftActor> newTestRaftActor(String id, TestRaftActor.Builder builder) {
249 builder.collectorActor(factory.<MessageCollectorActor>createTestActor(
250 MessageCollectorActor.props().withDispatcher(Dispatchers.DefaultDispatcherId()),
251 factory.generateActorId(id + "-collector"))).id(id);
253 InvalidActorNameException lastEx = null;
254 for(int i = 0; i < 10; i++) {
256 return factory.createTestActor(builder.props().withDispatcher(Dispatchers.DefaultDispatcherId()), id);
257 } catch (InvalidActorNameException e) {
259 Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
263 assertNotNull(lastEx);
267 protected void killActor(TestActorRef<TestRaftActor> leaderActor) {
268 JavaTestKit testkit = new JavaTestKit(getSystem());
269 testkit.watch(leaderActor);
271 leaderActor.tell(PoisonPill.getInstance(), null);
272 testkit.expectMsgClass(JavaTestKit.duration("5 seconds"), Terminated.class);
274 testkit.unwatch(leaderActor);
277 protected void verifyApplyJournalEntries(ActorRef actor, final long expIndex) {
278 MessageCollectorActor.expectFirstMatching(actor, ApplyJournalEntries.class, msg -> msg.getToIndex() == expIndex);
281 @SuppressWarnings("unchecked")
282 protected void verifySnapshot(String prefix, Snapshot snapshot, long lastAppliedTerm,
283 long lastAppliedIndex, long lastTerm, long lastIndex)
285 assertEquals(prefix + " Snapshot getLastAppliedTerm", lastAppliedTerm, snapshot.getLastAppliedTerm());
286 assertEquals(prefix + " Snapshot getLastAppliedIndex", lastAppliedIndex, snapshot.getLastAppliedIndex());
287 assertEquals(prefix + " Snapshot getLastTerm", lastTerm, snapshot.getLastTerm());
288 assertEquals(prefix + " Snapshot getLastIndex", lastIndex, snapshot.getLastIndex());
290 List<Object> actualState = (List<Object>)MockRaftActor.toObject(snapshot.getState());
291 assertEquals(String.format("%s Snapshot getState size. Expected %s: . Actual: %s", prefix, expSnapshotState,
292 actualState), expSnapshotState.size(), actualState.size());
293 for(int i = 0; i < expSnapshotState.size(); i++) {
294 assertEquals(prefix + " Snapshot state " + i, expSnapshotState.get(i), actualState.get(i));
298 protected void verifyPersistedJournal(String persistenceId, List<? extends ReplicatedLogEntry> expJournal) {
299 List<ReplicatedLogEntry> journal = InMemoryJournal.get(persistenceId, ReplicatedLogEntry.class);
300 assertEquals("Journal ReplicatedLogEntry count", expJournal.size(), journal.size());
301 for(int i = 0; i < expJournal.size(); i++) {
302 ReplicatedLogEntry expected = expJournal.get(i);
303 ReplicatedLogEntry actual = journal.get(i);
304 verifyReplicatedLogEntry(expected, actual.getTerm(), actual.getIndex(), actual.getData());
308 protected MockPayload sendPayloadData(ActorRef leaderActor, String data) {
309 return sendPayloadData(leaderActor, data, 0);
312 protected MockPayload sendPayloadData(ActorRef leaderActor, String data, int size) {
315 payload = new MockPayload(data, size);
317 payload = new MockPayload(data);
320 leaderActor.tell(payload, ActorRef.noSender());
324 protected void verifyApplyState(ApplyState applyState, ActorRef expClientActor,
325 String expId, long expTerm, long expIndex, Payload payload) {
326 assertEquals("ApplyState getClientActor", expClientActor, applyState.getClientActor());
328 final Identifier id = expId == null ? null : new MockIdentifier(expId);
329 assertEquals("ApplyState getIdentifier", id, applyState.getIdentifier());
330 ReplicatedLogEntry replicatedLogEntry = applyState.getReplicatedLogEntry();
331 verifyReplicatedLogEntry(replicatedLogEntry, expTerm, expIndex, payload);
334 protected void verifyReplicatedLogEntry(ReplicatedLogEntry replicatedLogEntry, long expTerm, long expIndex,
336 assertEquals("ReplicatedLogEntry getTerm", expTerm, replicatedLogEntry.getTerm());
337 assertEquals("ReplicatedLogEntry getIndex", expIndex, replicatedLogEntry.getIndex());
338 assertEquals("ReplicatedLogEntry getData", payload, replicatedLogEntry.getData());
341 protected String testActorPath(String id){
342 return factory.createTestActorPath(id);
345 protected void verifyLeadersTrimmedLog(long lastIndex) {
346 verifyTrimmedLog("Leader", leaderActor, lastIndex, lastIndex - 1);
349 protected void verifyLeadersTrimmedLog(long lastIndex, long replicatedToAllIndex) {
350 verifyTrimmedLog("Leader", leaderActor, lastIndex, replicatedToAllIndex);
353 protected void verifyFollowersTrimmedLog(int num, TestActorRef<TestRaftActor> actorRef, long lastIndex) {
354 verifyTrimmedLog("Follower " + num, actorRef, lastIndex, lastIndex - 1);
357 protected void verifyTrimmedLog(String name, TestActorRef<TestRaftActor> actorRef, long lastIndex,
358 long replicatedToAllIndex) {
359 TestRaftActor actor = actorRef.underlyingActor();
360 RaftActorContext context = actor.getRaftActorContext();
361 long snapshotIndex = lastIndex - 1;
362 assertEquals(name + " snapshot term", snapshotIndex < 0 ? -1 : currentTerm,
363 context.getReplicatedLog().getSnapshotTerm());
364 assertEquals(name + " snapshot index", snapshotIndex, context.getReplicatedLog().getSnapshotIndex());
365 assertEquals(name + " journal log size", 1, context.getReplicatedLog().size());
366 assertEquals(name + " journal last index", lastIndex, context.getReplicatedLog().lastIndex());
367 assertEquals(name + " commit index", lastIndex, context.getCommitIndex());
368 assertEquals(name + " last applied", lastIndex, context.getLastApplied());
369 assertEquals(name + " replicatedToAllIndex", replicatedToAllIndex,
370 actor.getCurrentBehavior().getReplicatedToAllIndex());
373 static void verifyRaftState(ActorRef raftActor, Consumer<OnDemandRaftState> verifier) {
374 Timeout timeout = new Timeout(500, TimeUnit.MILLISECONDS);
375 AssertionError lastError = null;
376 Stopwatch sw = Stopwatch.createStarted();
377 while(sw.elapsed(TimeUnit.SECONDS) <= 5) {
379 OnDemandRaftState raftState = (OnDemandRaftState)Await.result(ask(raftActor,
380 GetOnDemandRaftState.INSTANCE, timeout), timeout.duration());
381 verifier.accept(raftState);
383 } catch (AssertionError e) {
385 Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
386 } catch (Exception e) {
387 lastError = new AssertionError("OnDemandRaftState failed", e);
388 Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);