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 akka.actor.ActorRef;
12 import akka.actor.InvalidActorNameException;
13 import akka.actor.PoisonPill;
14 import akka.actor.Props;
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.base.Optional;
20 import com.google.common.base.Predicate;
21 import com.google.common.base.Supplier;
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 org.junit.After;
31 import org.opendaylight.controller.cluster.raft.MockRaftActorContext.MockPayload;
32 import org.opendaylight.controller.cluster.raft.base.messages.ApplyJournalEntries;
33 import org.opendaylight.controller.cluster.raft.base.messages.ApplyState;
34 import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshotReply;
35 import org.opendaylight.controller.cluster.raft.base.messages.SendHeartBeat;
36 import org.opendaylight.controller.cluster.raft.behaviors.RaftActorBehavior;
37 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
38 import org.opendaylight.controller.cluster.raft.utils.InMemoryJournal;
39 import org.opendaylight.controller.cluster.raft.utils.InMemorySnapshotStore;
40 import org.opendaylight.controller.cluster.raft.utils.MessageCollectorActor;
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 public static class TestRaftActor extends MockRaftActor {
54 private final TestActorRef<MessageCollectorActor> collectorActor;
55 private final Map<Class<?>, Boolean> dropMessages = new ConcurrentHashMap<>();
57 private TestRaftActor(String id, Map<String, String> peerAddresses, ConfigParams config,
58 TestActorRef<MessageCollectorActor> collectorActor) {
59 super(id, peerAddresses, Optional.of(config), null);
60 this.collectorActor = collectorActor;
63 public static Props props(String id, Map<String, String> peerAddresses, ConfigParams config,
64 TestActorRef<MessageCollectorActor> collectorActor) {
65 return Props.create(TestRaftActor.class, id, peerAddresses, config, collectorActor).
66 withDispatcher(Dispatchers.DefaultDispatcherId());
69 void startDropMessages(Class<?> msgClass) {
70 dropMessages.put(msgClass, Boolean.TRUE);
73 void stopDropMessages(Class<?> msgClass) {
74 dropMessages.remove(msgClass);
77 void setMockTotalMemory(final long mockTotalMemory) {
78 if(mockTotalMemory > 0) {
79 getRaftActorContext().setTotalMemoryRetriever(new Supplier<Long>() {
82 return mockTotalMemory;
87 getRaftActorContext().setTotalMemoryRetriever(null);
92 public void handleCommand(Object message) {
93 if(message instanceof MockPayload) {
94 MockPayload payload = (MockPayload)message;
95 super.persistData(collectorActor, payload.toString(), payload);
100 if(!dropMessages.containsKey(message.getClass())) {
101 super.handleCommand(message);
104 if(!(message instanceof SendHeartBeat)) {
106 collectorActor.tell(message, ActorRef.noSender());
107 } catch (Exception e) {
108 LOG.error("MessageCollectorActor error", e);
115 public void createSnapshot(ActorRef actorRef) {
117 actorRef.tell(new CaptureSnapshotReply(RaftActorTest.fromObject(getState()).toByteArray()), actorRef);
118 } catch (Exception e) {
123 public ActorRef collectorActor() {
124 return collectorActor;
128 protected final Logger testLog = LoggerFactory.getLogger(getClass());
130 protected final TestActorFactory factory = new TestActorFactory(getSystem());
132 protected String leaderId = factory.generateActorId("leader");
133 protected DefaultConfigParamsImpl leaderConfigParams;
134 protected TestActorRef<TestRaftActor> leaderActor;
135 protected ActorRef leaderCollectorActor;
136 protected RaftActorContext leaderContext;
137 protected RaftActorBehavior leader;
139 protected String follower1Id = factory.generateActorId("follower");
140 protected TestActorRef<TestRaftActor> follower1Actor;
141 protected ActorRef follower1CollectorActor;
142 protected RaftActorBehavior follower1;
143 protected RaftActorContext follower1Context;
145 protected String follower2Id = factory.generateActorId("follower");
146 protected TestActorRef<TestRaftActor> follower2Actor;
147 protected ActorRef follower2CollectorActor;
148 protected RaftActorBehavior follower2;
149 protected RaftActorContext follower2Context;
151 protected ImmutableMap<String, String> peerAddresses;
153 protected long initialTerm = 5;
154 protected long currentTerm;
156 protected List<Object> expSnapshotState = new ArrayList<>();
159 public void tearDown() {
160 InMemoryJournal.clear();
161 InMemorySnapshotStore.clear();
165 protected DefaultConfigParamsImpl newLeaderConfigParams() {
166 DefaultConfigParamsImpl configParams = new DefaultConfigParamsImpl();
167 configParams.setHeartBeatInterval(new FiniteDuration(100, TimeUnit.MILLISECONDS));
168 configParams.setElectionTimeoutFactor(1);
169 configParams.setSnapshotBatchCount(4);
170 configParams.setSnapshotDataThresholdPercentage(70);
171 configParams.setIsolatedLeaderCheckInterval(new FiniteDuration(1, TimeUnit.DAYS));
175 protected DefaultConfigParamsImpl newFollowerConfigParams() {
176 DefaultConfigParamsImpl configParams = new DefaultConfigParamsImpl();
177 configParams.setHeartBeatInterval(new FiniteDuration(500, TimeUnit.MILLISECONDS));
178 configParams.setElectionTimeoutFactor(1000);
182 protected void waitUntilLeader(ActorRef actorRef) {
183 RaftActorTestKit.waitUntilLeader(actorRef);
186 protected TestActorRef<TestRaftActor> newTestRaftActor(String id, Map<String, String> peerAddresses,
187 ConfigParams configParams) {
188 TestActorRef<MessageCollectorActor> collectorActor = factory.createTestActor(
189 MessageCollectorActor.props().withDispatcher(Dispatchers.DefaultDispatcherId()),
190 factory.generateActorId(id + "-collector"));
192 InvalidActorNameException lastEx = null;
193 for(int i = 0; i < 10; i++) {
195 return factory.createTestActor(TestRaftActor.props(id,
196 peerAddresses != null ? peerAddresses : Collections.<String, String>emptyMap(),
197 configParams, collectorActor), id);
198 } catch (InvalidActorNameException e) {
200 Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
207 protected void killActor(TestActorRef<TestRaftActor> leaderActor) {
208 JavaTestKit testkit = new JavaTestKit(getSystem());
209 testkit.watch(leaderActor);
211 leaderActor.tell(PoisonPill.getInstance(), null);
212 testkit.expectMsgClass(JavaTestKit.duration("5 seconds"), Terminated.class);
214 testkit.unwatch(leaderActor);
217 protected void verifyApplyJournalEntries(ActorRef actor, final long expIndex) {
218 MessageCollectorActor.expectFirstMatching(actor, ApplyJournalEntries.class, new Predicate<ApplyJournalEntries>() {
220 public boolean apply(ApplyJournalEntries msg) {
221 return msg.getToIndex() == expIndex;
226 @SuppressWarnings("unchecked")
227 protected void verifySnapshot(String prefix, Snapshot snapshot, long lastAppliedTerm,
228 int lastAppliedIndex, long lastTerm, long lastIndex)
230 assertEquals(prefix + " Snapshot getLastAppliedTerm", lastAppliedTerm, snapshot.getLastAppliedTerm());
231 assertEquals(prefix + " Snapshot getLastAppliedIndex", lastAppliedIndex, snapshot.getLastAppliedIndex());
232 assertEquals(prefix + " Snapshot getLastTerm", lastTerm, snapshot.getLastTerm());
233 assertEquals(prefix + " Snapshot getLastIndex", lastIndex, snapshot.getLastIndex());
235 List<Object> actualState = (List<Object>)MockRaftActor.toObject(snapshot.getState());
236 assertEquals(prefix + " Snapshot getState size", expSnapshotState.size(), actualState.size());
237 for(int i = 0; i < expSnapshotState.size(); i++) {
238 assertEquals(prefix + " Snapshot state " + i, expSnapshotState.get(i), actualState.get(i));
242 protected void verifyPersistedJournal(String persistenceId, List<? extends ReplicatedLogEntry> expJournal) {
243 List<ReplicatedLogEntry> journal = InMemoryJournal.get(persistenceId, ReplicatedLogEntry.class);
244 assertEquals("Journal ReplicatedLogEntry count", expJournal.size(), journal.size());
245 for(int i = 0; i < expJournal.size(); i++) {
246 ReplicatedLogEntry expected = expJournal.get(i);
247 ReplicatedLogEntry actual = journal.get(i);
248 verifyReplicatedLogEntry(expected, actual.getTerm(), actual.getIndex(), actual.getData());
252 protected MockPayload sendPayloadData(ActorRef leaderActor, String data) {
253 return sendPayloadData(leaderActor, data, 0);
256 protected MockPayload sendPayloadData(ActorRef leaderActor, String data, int size) {
259 payload = new MockPayload(data, size);
261 payload = new MockPayload(data);
264 leaderActor.tell(payload, ActorRef.noSender());
268 protected void verifyApplyState(ApplyState applyState, ActorRef expClientActor,
269 String expId, long expTerm, long expIndex, MockPayload payload) {
270 assertEquals("ApplyState getClientActor", expClientActor, applyState.getClientActor());
271 assertEquals("ApplyState getIdentifier", expId, applyState.getIdentifier());
272 ReplicatedLogEntry replicatedLogEntry = applyState.getReplicatedLogEntry();
273 verifyReplicatedLogEntry(replicatedLogEntry, expTerm, expIndex, payload);
276 protected void verifyReplicatedLogEntry(ReplicatedLogEntry replicatedLogEntry, long expTerm, long expIndex,
278 assertEquals("ReplicatedLogEntry getTerm", expTerm, replicatedLogEntry.getTerm());
279 assertEquals("ReplicatedLogEntry getIndex", expIndex, replicatedLogEntry.getIndex());
280 assertEquals("ReplicatedLogEntry getData", payload, replicatedLogEntry.getData());
283 protected String testActorPath(String id){
284 return "akka://test/user" + id;