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.PoisonPill;
13 import akka.actor.Props;
14 import akka.actor.Terminated;
15 import akka.dispatch.Dispatchers;
16 import akka.testkit.JavaTestKit;
17 import akka.testkit.TestActorRef;
18 import com.google.common.base.Optional;
19 import com.google.common.base.Predicate;
20 import com.google.common.base.Supplier;
21 import com.google.common.collect.ImmutableMap;
22 import java.util.ArrayList;
23 import java.util.Collections;
24 import java.util.List;
26 import java.util.concurrent.ConcurrentHashMap;
27 import java.util.concurrent.TimeUnit;
28 import org.junit.After;
29 import org.opendaylight.controller.cluster.raft.MockRaftActorContext.MockPayload;
30 import org.opendaylight.controller.cluster.raft.base.messages.ApplyJournalEntries;
31 import org.opendaylight.controller.cluster.raft.base.messages.ApplyState;
32 import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshotReply;
33 import org.opendaylight.controller.cluster.raft.base.messages.SendHeartBeat;
34 import org.opendaylight.controller.cluster.raft.behaviors.RaftActorBehavior;
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.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41 import scala.concurrent.duration.FiniteDuration;
44 * Abstract base for an integration test that tests end-to-end RaftActor and behavior functionality.
46 * @author Thomas Pantelis
48 public abstract class AbstractRaftActorIntegrationTest extends AbstractActorTest {
50 public static class TestRaftActor extends MockRaftActor {
52 private final TestActorRef<MessageCollectorActor> collectorActor;
53 private final Map<Class<?>, Boolean> dropMessages = new ConcurrentHashMap<>();
55 private TestRaftActor(String id, Map<String, String> peerAddresses, ConfigParams config,
56 TestActorRef<MessageCollectorActor> collectorActor) {
57 super(id, peerAddresses, Optional.of(config), null);
58 this.collectorActor = collectorActor;
61 public static Props props(String id, Map<String, String> peerAddresses, ConfigParams config,
62 TestActorRef<MessageCollectorActor> collectorActor) {
63 return Props.create(TestRaftActor.class, id, peerAddresses, config, collectorActor).
64 withDispatcher(Dispatchers.DefaultDispatcherId());
67 void startDropMessages(Class<?> msgClass) {
68 dropMessages.put(msgClass, Boolean.TRUE);
71 void stopDropMessages(Class<?> msgClass) {
72 dropMessages.remove(msgClass);
75 void setMockTotalMemory(final long mockTotalMemory) {
76 if(mockTotalMemory > 0) {
77 getRaftActorContext().setTotalMemoryRetriever(new Supplier<Long>() {
80 return mockTotalMemory;
85 getRaftActorContext().setTotalMemoryRetriever(null);
90 public void handleCommand(Object message) {
91 if(message instanceof MockPayload) {
92 MockPayload payload = (MockPayload)message;
93 super.persistData(collectorActor, payload.toString(), payload);
98 if(!dropMessages.containsKey(message.getClass())) {
99 super.handleCommand(message);
102 if(!(message instanceof SendHeartBeat)) {
104 collectorActor.tell(message, ActorRef.noSender());
105 } catch (Exception e) {
106 LOG.error("MessageCollectorActor error", e);
113 public void createSnapshot(ActorRef actorRef) {
115 actorRef.tell(new CaptureSnapshotReply(RaftActorTest.fromObject(getState()).toByteArray()), actorRef);
116 } catch (Exception e) {
121 public ActorRef collectorActor() {
122 return collectorActor;
126 protected final Logger testLog = LoggerFactory.getLogger(getClass());
128 protected final TestActorFactory factory = new TestActorFactory(getSystem());
130 protected String leaderId = factory.generateActorId("leader");
131 protected DefaultConfigParamsImpl leaderConfigParams;
132 protected TestActorRef<TestRaftActor> leaderActor;
133 protected ActorRef leaderCollectorActor;
134 protected RaftActorContext leaderContext;
135 protected RaftActorBehavior leader;
137 protected String follower1Id = factory.generateActorId("follower");
138 protected TestActorRef<TestRaftActor> follower1Actor;
139 protected ActorRef follower1CollectorActor;
140 protected RaftActorBehavior follower1;
141 protected RaftActorContext follower1Context;
143 protected String follower2Id = factory.generateActorId("follower");
144 protected TestActorRef<TestRaftActor> follower2Actor;
145 protected ActorRef follower2CollectorActor;
146 protected RaftActorBehavior follower2;
147 protected RaftActorContext follower2Context;
149 protected ImmutableMap<String, String> peerAddresses;
151 protected long initialTerm = 5;
152 protected long currentTerm;
154 protected List<Object> expSnapshotState = new ArrayList<>();
157 public void tearDown() {
158 InMemoryJournal.clear();
159 InMemorySnapshotStore.clear();
163 protected DefaultConfigParamsImpl newLeaderConfigParams() {
164 DefaultConfigParamsImpl configParams = new DefaultConfigParamsImpl();
165 configParams.setHeartBeatInterval(new FiniteDuration(100, TimeUnit.MILLISECONDS));
166 configParams.setElectionTimeoutFactor(1);
167 configParams.setSnapshotBatchCount(4);
168 configParams.setSnapshotDataThresholdPercentage(70);
169 configParams.setIsolatedLeaderCheckInterval(new FiniteDuration(1, TimeUnit.DAYS));
173 protected DefaultConfigParamsImpl newFollowerConfigParams() {
174 DefaultConfigParamsImpl configParams = new DefaultConfigParamsImpl();
175 configParams.setHeartBeatInterval(new FiniteDuration(500, TimeUnit.MILLISECONDS));
176 configParams.setElectionTimeoutFactor(1000);
180 protected void waitUntilLeader(ActorRef actorRef) {
181 RaftActorTestKit.waitUntilLeader(actorRef);
184 protected TestActorRef<TestRaftActor> newTestRaftActor(String id, Map<String, String> peerAddresses,
185 ConfigParams configParams) {
186 TestActorRef<MessageCollectorActor> collectorActor = factory.createTestActor(
187 MessageCollectorActor.props().withDispatcher(Dispatchers.DefaultDispatcherId()),
188 factory.generateActorId(id + "-collector"));
189 return factory.createTestActor(TestRaftActor.props(id,
190 peerAddresses != null ? peerAddresses : Collections.<String, String>emptyMap(),
191 configParams, collectorActor), id);
194 protected void killActor(TestActorRef<TestRaftActor> leaderActor) {
195 JavaTestKit testkit = new JavaTestKit(getSystem());
196 testkit.watch(leaderActor);
198 leaderActor.tell(PoisonPill.getInstance(), null);
199 testkit.expectMsgClass(JavaTestKit.duration("5 seconds"), Terminated.class);
201 testkit.unwatch(leaderActor);
204 protected void verifyApplyJournalEntries(ActorRef actor, final long expIndex) {
205 MessageCollectorActor.expectFirstMatching(actor, ApplyJournalEntries.class, new Predicate<ApplyJournalEntries>() {
207 public boolean apply(ApplyJournalEntries msg) {
208 return msg.getToIndex() == expIndex;
213 @SuppressWarnings("unchecked")
214 protected void verifySnapshot(String prefix, Snapshot snapshot, long lastAppliedTerm,
215 int lastAppliedIndex, long lastTerm, long lastIndex)
217 assertEquals(prefix + " Snapshot getLastAppliedTerm", lastAppliedTerm, snapshot.getLastAppliedTerm());
218 assertEquals(prefix + " Snapshot getLastAppliedIndex", lastAppliedIndex, snapshot.getLastAppliedIndex());
219 assertEquals(prefix + " Snapshot getLastTerm", lastTerm, snapshot.getLastTerm());
220 assertEquals(prefix + " Snapshot getLastIndex", lastIndex, snapshot.getLastIndex());
222 List<Object> actualState = (List<Object>)MockRaftActor.toObject(snapshot.getState());
223 assertEquals(prefix + " Snapshot getState size", expSnapshotState.size(), actualState.size());
224 for(int i = 0; i < expSnapshotState.size(); i++) {
225 assertEquals(prefix + " Snapshot state " + i, expSnapshotState.get(i), actualState.get(i));
229 protected void verifyPersistedJournal(String persistenceId, List<? extends ReplicatedLogEntry> expJournal) {
230 List<ReplicatedLogEntry> journal = InMemoryJournal.get(persistenceId, ReplicatedLogEntry.class);
231 assertEquals("Journal ReplicatedLogEntry count", expJournal.size(), journal.size());
232 for(int i = 0; i < expJournal.size(); i++) {
233 ReplicatedLogEntry expected = expJournal.get(i);
234 ReplicatedLogEntry actual = journal.get(i);
235 verifyReplicatedLogEntry(expected, actual.getTerm(), actual.getIndex(), actual.getData());
239 protected MockPayload sendPayloadData(ActorRef leaderActor, String data) {
240 return sendPayloadData(leaderActor, data, 0);
243 protected MockPayload sendPayloadData(ActorRef leaderActor, String data, int size) {
246 payload = new MockPayload(data, size);
248 payload = new MockPayload(data);
251 leaderActor.tell(payload, ActorRef.noSender());
255 protected void verifyApplyState(ApplyState applyState, ActorRef expClientActor,
256 String expId, long expTerm, long expIndex, MockPayload payload) {
257 assertEquals("ApplyState getClientActor", expClientActor, applyState.getClientActor());
258 assertEquals("ApplyState getIdentifier", expId, applyState.getIdentifier());
259 ReplicatedLogEntry replicatedLogEntry = applyState.getReplicatedLogEntry();
260 verifyReplicatedLogEntry(replicatedLogEntry, expTerm, expIndex, payload);
263 protected void verifyReplicatedLogEntry(ReplicatedLogEntry replicatedLogEntry, long expTerm, long expIndex,
265 assertEquals("ReplicatedLogEntry getTerm", expTerm, replicatedLogEntry.getTerm());
266 assertEquals("ReplicatedLogEntry getIndex", expIndex, replicatedLogEntry.getIndex());
267 assertEquals("ReplicatedLogEntry getData", payload, replicatedLogEntry.getData());
270 protected String testActorPath(String id){
271 return "akka://test/user" + id;