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 org.junit.Assert.assertEquals;
11 import static org.junit.Assert.assertNotNull;
12 import akka.actor.ActorRef;
13 import akka.actor.InvalidActorNameException;
14 import akka.actor.PoisonPill;
15 import akka.actor.Terminated;
16 import akka.dispatch.Dispatchers;
17 import akka.testkit.JavaTestKit;
18 import akka.testkit.TestActorRef;
19 import com.google.common.collect.ImmutableMap;
20 import com.google.common.util.concurrent.Uninterruptibles;
21 import java.util.ArrayList;
22 import java.util.Collections;
23 import java.util.List;
25 import java.util.concurrent.ConcurrentHashMap;
26 import java.util.concurrent.TimeUnit;
27 import org.junit.After;
28 import org.opendaylight.controller.cluster.raft.MockRaftActorContext.MockPayload;
29 import org.opendaylight.controller.cluster.raft.base.messages.ApplyState;
30 import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshotReply;
31 import org.opendaylight.controller.cluster.raft.base.messages.SendHeartBeat;
32 import org.opendaylight.controller.cluster.raft.behaviors.RaftActorBehavior;
33 import org.opendaylight.controller.cluster.raft.persisted.ApplyJournalEntries;
34 import org.opendaylight.controller.cluster.raft.persisted.ServerConfigurationPayload;
35 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
36 import org.opendaylight.controller.cluster.raft.utils.InMemoryJournal;
37 import org.opendaylight.controller.cluster.raft.utils.InMemorySnapshotStore;
38 import org.opendaylight.controller.cluster.raft.utils.MessageCollectorActor;
39 import org.opendaylight.yangtools.concepts.Identifier;
40 import org.opendaylight.yangtools.util.AbstractStringIdentifier;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43 import scala.concurrent.duration.FiniteDuration;
46 * Abstract base for an integration test that tests end-to-end RaftActor and behavior functionality.
48 * @author Thomas Pantelis
50 public abstract class AbstractRaftActorIntegrationTest extends AbstractActorTest {
52 private static final class MockIdentifier extends AbstractStringIdentifier<MockIdentifier> {
53 private static final long serialVersionUID = 1L;
55 protected MockIdentifier(String string) {
60 public static class SetPeerAddress {
61 private final String peerId;
62 private final String peerAddress;
64 public SetPeerAddress(String peerId, String peerAddress) {
66 this.peerAddress = peerAddress;
69 public String getPeerId() {
73 public String getPeerAddress() {
78 public static class TestRaftActor extends MockRaftActor {
80 private final TestActorRef<MessageCollectorActor> collectorActor;
81 private final Map<Class<?>, Boolean> dropMessages = new ConcurrentHashMap<>();
83 private TestRaftActor(Builder builder) {
85 this.collectorActor = builder.collectorActor;
88 public void startDropMessages(Class<?> msgClass) {
89 dropMessages.put(msgClass, Boolean.TRUE);
92 public void stopDropMessages(Class<?> msgClass) {
93 dropMessages.remove(msgClass);
96 void setMockTotalMemory(final long mockTotalMemory) {
97 getRaftActorContext().setTotalMemoryRetriever(mockTotalMemory > 0 ? () -> mockTotalMemory : null);
101 public void handleCommand(Object message) {
102 if(message instanceof MockPayload) {
103 MockPayload payload = (MockPayload)message;
104 super.persistData(collectorActor, new MockIdentifier(payload.toString()), payload);
108 if(message instanceof ServerConfigurationPayload) {
109 super.persistData(collectorActor, new MockIdentifier("serverConfig"), (Payload)message);
113 if(message instanceof SetPeerAddress) {
114 setPeerAddress(((SetPeerAddress) message).getPeerId().toString(),
115 ((SetPeerAddress) message).getPeerAddress());
120 if(!dropMessages.containsKey(message.getClass())) {
121 super.handleCommand(message);
124 if(!(message instanceof SendHeartBeat)) {
126 collectorActor.tell(message, ActorRef.noSender());
127 } catch (Exception e) {
128 LOG.error("MessageCollectorActor error", e);
135 public void createSnapshot(ActorRef actorRef) {
137 actorRef.tell(new CaptureSnapshotReply(RaftActorTest.fromObject(getState()).toByteArray()), actorRef);
138 } catch (Exception e) {
143 public ActorRef collectorActor() {
144 return collectorActor;
147 public static Builder newBuilder() {
148 return new Builder();
151 public static class Builder extends AbstractBuilder<Builder, TestRaftActor> {
152 private TestActorRef<MessageCollectorActor> collectorActor;
154 public Builder collectorActor(TestActorRef<MessageCollectorActor> collectorActor) {
155 this.collectorActor = collectorActor;
160 super(TestRaftActor.class);
165 protected static final int SNAPSHOT_CHUNK_SIZE = 100;
167 protected final Logger testLog = LoggerFactory.getLogger(getClass());
169 protected final TestActorFactory factory = new TestActorFactory(getSystem());
171 protected String leaderId = factory.generateActorId("leader");
172 protected DefaultConfigParamsImpl leaderConfigParams;
173 protected TestActorRef<TestRaftActor> leaderActor;
174 protected ActorRef leaderCollectorActor;
175 protected RaftActorContext leaderContext;
176 protected RaftActorBehavior leader;
178 protected String follower1Id = factory.generateActorId("follower");
179 protected TestActorRef<TestRaftActor> follower1Actor;
180 protected ActorRef follower1CollectorActor;
181 protected RaftActorBehavior follower1;
182 protected RaftActorContext follower1Context;
184 protected String follower2Id = factory.generateActorId("follower");
185 protected TestActorRef<TestRaftActor> follower2Actor;
186 protected ActorRef follower2CollectorActor;
187 protected RaftActorBehavior follower2;
188 protected RaftActorContext follower2Context;
190 protected ImmutableMap<String, String> peerAddresses;
192 protected long initialTerm = 5;
193 protected long currentTerm;
195 protected int snapshotBatchCount = 4;
197 protected List<MockPayload> expSnapshotState = new ArrayList<>();
200 public void tearDown() {
201 InMemoryJournal.clear();
202 InMemorySnapshotStore.clear();
206 protected DefaultConfigParamsImpl newLeaderConfigParams() {
207 DefaultConfigParamsImpl configParams = new DefaultConfigParamsImpl();
208 configParams.setHeartBeatInterval(new FiniteDuration(100, TimeUnit.MILLISECONDS));
209 configParams.setElectionTimeoutFactor(1);
210 configParams.setSnapshotBatchCount(snapshotBatchCount);
211 configParams.setSnapshotDataThresholdPercentage(70);
212 configParams.setIsolatedLeaderCheckInterval(new FiniteDuration(1, TimeUnit.DAYS));
213 configParams.setSnapshotChunkSize(SNAPSHOT_CHUNK_SIZE);
217 protected DefaultConfigParamsImpl newFollowerConfigParams() {
218 DefaultConfigParamsImpl configParams = new DefaultConfigParamsImpl();
219 configParams.setHeartBeatInterval(new FiniteDuration(500, TimeUnit.MILLISECONDS));
220 configParams.setElectionTimeoutFactor(1000);
224 protected void waitUntilLeader(ActorRef actorRef) {
225 RaftActorTestKit.waitUntilLeader(actorRef);
228 protected TestActorRef<TestRaftActor> newTestRaftActor(String id, Map<String, String> peerAddresses,
229 ConfigParams configParams) {
230 return newTestRaftActor(id, TestRaftActor.newBuilder().peerAddresses(peerAddresses != null ? peerAddresses :
231 Collections.<String, String>emptyMap()).config(configParams));
234 protected TestActorRef<TestRaftActor> newTestRaftActor(String id, TestRaftActor.Builder builder) {
235 builder.collectorActor(factory.<MessageCollectorActor>createTestActor(
236 MessageCollectorActor.props().withDispatcher(Dispatchers.DefaultDispatcherId()),
237 factory.generateActorId(id + "-collector"))).id(id);
239 InvalidActorNameException lastEx = null;
240 for(int i = 0; i < 10; i++) {
242 return factory.createTestActor(builder.props().withDispatcher(Dispatchers.DefaultDispatcherId()), id);
243 } catch (InvalidActorNameException e) {
245 Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
249 assertNotNull(lastEx);
253 protected void killActor(TestActorRef<TestRaftActor> leaderActor) {
254 JavaTestKit testkit = new JavaTestKit(getSystem());
255 testkit.watch(leaderActor);
257 leaderActor.tell(PoisonPill.getInstance(), null);
258 testkit.expectMsgClass(JavaTestKit.duration("5 seconds"), Terminated.class);
260 testkit.unwatch(leaderActor);
263 protected void verifyApplyJournalEntries(ActorRef actor, final long expIndex) {
264 MessageCollectorActor.expectFirstMatching(actor, ApplyJournalEntries.class, msg -> msg.getToIndex() == expIndex);
267 @SuppressWarnings("unchecked")
268 protected void verifySnapshot(String prefix, Snapshot snapshot, long lastAppliedTerm,
269 long lastAppliedIndex, long lastTerm, long lastIndex)
271 assertEquals(prefix + " Snapshot getLastAppliedTerm", lastAppliedTerm, snapshot.getLastAppliedTerm());
272 assertEquals(prefix + " Snapshot getLastAppliedIndex", lastAppliedIndex, snapshot.getLastAppliedIndex());
273 assertEquals(prefix + " Snapshot getLastTerm", lastTerm, snapshot.getLastTerm());
274 assertEquals(prefix + " Snapshot getLastIndex", lastIndex, snapshot.getLastIndex());
276 List<Object> actualState = (List<Object>)MockRaftActor.toObject(snapshot.getState());
277 assertEquals(String.format("%s Snapshot getState size. Expected %s: . Actual: %s", prefix, expSnapshotState,
278 actualState), expSnapshotState.size(), actualState.size());
279 for(int i = 0; i < expSnapshotState.size(); i++) {
280 assertEquals(prefix + " Snapshot state " + i, expSnapshotState.get(i), actualState.get(i));
284 protected void verifyPersistedJournal(String persistenceId, List<? extends ReplicatedLogEntry> expJournal) {
285 List<ReplicatedLogEntry> journal = InMemoryJournal.get(persistenceId, ReplicatedLogEntry.class);
286 assertEquals("Journal ReplicatedLogEntry count", expJournal.size(), journal.size());
287 for(int i = 0; i < expJournal.size(); i++) {
288 ReplicatedLogEntry expected = expJournal.get(i);
289 ReplicatedLogEntry actual = journal.get(i);
290 verifyReplicatedLogEntry(expected, actual.getTerm(), actual.getIndex(), actual.getData());
294 protected MockPayload sendPayloadData(ActorRef leaderActor, String data) {
295 return sendPayloadData(leaderActor, data, 0);
298 protected MockPayload sendPayloadData(ActorRef leaderActor, String data, int size) {
301 payload = new MockPayload(data, size);
303 payload = new MockPayload(data);
306 leaderActor.tell(payload, ActorRef.noSender());
310 protected void verifyApplyState(ApplyState applyState, ActorRef expClientActor,
311 String expId, long expTerm, long expIndex, Payload payload) {
312 assertEquals("ApplyState getClientActor", expClientActor, applyState.getClientActor());
314 final Identifier id = expId == null ? null : new MockIdentifier(expId);
315 assertEquals("ApplyState getIdentifier", id, applyState.getIdentifier());
316 ReplicatedLogEntry replicatedLogEntry = applyState.getReplicatedLogEntry();
317 verifyReplicatedLogEntry(replicatedLogEntry, expTerm, expIndex, payload);
320 protected void verifyReplicatedLogEntry(ReplicatedLogEntry replicatedLogEntry, long expTerm, long expIndex,
322 assertEquals("ReplicatedLogEntry getTerm", expTerm, replicatedLogEntry.getTerm());
323 assertEquals("ReplicatedLogEntry getIndex", expIndex, replicatedLogEntry.getIndex());
324 assertEquals("ReplicatedLogEntry getData", payload, replicatedLogEntry.getData());
327 protected String testActorPath(String id){
328 return factory.createTestActorPath(id);
331 protected void verifyLeadersTrimmedLog(long lastIndex) {
332 verifyTrimmedLog("Leader", leaderActor, lastIndex, lastIndex - 1);
335 protected void verifyLeadersTrimmedLog(long lastIndex, long replicatedToAllIndex) {
336 verifyTrimmedLog("Leader", leaderActor, lastIndex, replicatedToAllIndex);
339 protected void verifyFollowersTrimmedLog(int num, TestActorRef<TestRaftActor> actorRef, long lastIndex) {
340 verifyTrimmedLog("Follower " + num, actorRef, lastIndex, lastIndex - 1);
343 protected void verifyTrimmedLog(String name, TestActorRef<TestRaftActor> actorRef, long lastIndex,
344 long replicatedToAllIndex) {
345 TestRaftActor actor = actorRef.underlyingActor();
346 RaftActorContext context = actor.getRaftActorContext();
347 long snapshotIndex = lastIndex - 1;
348 assertEquals(name + " snapshot term", snapshotIndex < 0 ? -1 : currentTerm,
349 context.getReplicatedLog().getSnapshotTerm());
350 assertEquals(name + " snapshot index", snapshotIndex, context.getReplicatedLog().getSnapshotIndex());
351 assertEquals(name + " journal log size", 1, context.getReplicatedLog().size());
352 assertEquals(name + " journal last index", lastIndex, context.getReplicatedLog().lastIndex());
353 assertEquals(name + " commit index", lastIndex, context.getCommitIndex());
354 assertEquals(name + " last applied", lastIndex, context.getLastApplied());
355 assertEquals(name + " replicatedToAllIndex", replicatedToAllIndex,
356 actor.getCurrentBehavior().getReplicatedToAllIndex());