Add RaftActor integration tests
[controller.git] / opendaylight / md-sal / sal-akka-raft / src / test / java / org / opendaylight / controller / cluster / raft / AbstractRaftActorIntegrationTest.java
1 /*
2  * Copyright (c) 2015 Brocade Communications Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.controller.cluster.raft;
9
10 import static org.junit.Assert.assertArrayEquals;
11 import static org.junit.Assert.assertEquals;
12 import akka.actor.ActorRef;
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.collect.ImmutableMap;
22 import java.util.Collections;
23 import java.util.List;
24 import java.util.Map;
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.RaftActorTest.MockRaftActor;
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;
42
43 /**
44  * Abstract base for an integration test that tests end-to-end RaftActor and behavior functionality.
45  *
46  * @author Thomas Pantelis
47  */
48 public abstract class AbstractRaftActorIntegrationTest extends AbstractActorTest {
49
50     public static class TestRaftActor extends MockRaftActor {
51
52         private final TestActorRef<MessageCollectorActor> collectorActor;
53         private final Map<Class<?>, Boolean> dropMessages = new ConcurrentHashMap<>();
54         private volatile byte[] snapshot;
55         private volatile long mockTotalMemory;
56
57         private TestRaftActor(String id, Map<String, String> peerAddresses, ConfigParams config,
58                 TestActorRef<MessageCollectorActor> collectorActor) {
59             super(id, peerAddresses, Optional.of(config), null);
60             dataPersistenceProvider = new PersistentDataProvider();
61             this.collectorActor = collectorActor;
62         }
63
64         public static Props props(String id, Map<String, String> peerAddresses, ConfigParams config,
65                 TestActorRef<MessageCollectorActor> collectorActor) {
66             return Props.create(TestRaftActor.class, id, peerAddresses, config, collectorActor).
67                     withDispatcher(Dispatchers.DefaultDispatcherId());
68         }
69
70         void startDropMessages(Class<?> msgClass) {
71             dropMessages.put(msgClass, Boolean.TRUE);
72         }
73
74         void stopDropMessages(Class<?> msgClass) {
75             dropMessages.remove(msgClass);
76         }
77
78         void setMockTotalMemory(long mockTotalMemory) {
79             this.mockTotalMemory = mockTotalMemory;
80         }
81
82         @Override
83         protected long getTotalMemory() {
84             return mockTotalMemory > 0 ? mockTotalMemory : super.getTotalMemory();
85         }
86
87         @Override
88         public void handleCommand(Object message) {
89             if(message instanceof MockPayload) {
90                 MockPayload payload = (MockPayload)message;
91                 super.persistData(collectorActor, payload.toString(), payload);
92                 return;
93             }
94
95             try {
96                 if(!dropMessages.containsKey(message.getClass())) {
97                     super.handleCommand(message);
98                 }
99             } finally {
100                 if(!(message instanceof SendHeartBeat)) {
101                     try {
102                         collectorActor.tell(message, ActorRef.noSender());
103                     } catch (Exception e) {
104                         LOG.error("MessageCollectorActor error", e);
105                     }
106                 }
107             }
108         }
109
110         @Override
111         protected void createSnapshot() {
112             if(snapshot != null) {
113                 getSelf().tell(new CaptureSnapshotReply(snapshot), ActorRef.noSender());
114             }
115         }
116
117         @Override
118         protected void applyRecoverySnapshot(byte[] bytes) {
119         }
120
121         void setSnapshot(byte[] snapshot) {
122             this.snapshot = snapshot;
123         }
124
125         public ActorRef collectorActor() {
126             return collectorActor;
127         }
128     }
129
130     protected final Logger testLog = LoggerFactory.getLogger(getClass());
131
132     protected final TestActorFactory factory = new TestActorFactory(getSystem());
133
134     protected String leaderId = factory.generateActorId("leader");
135     protected DefaultConfigParamsImpl leaderConfigParams;
136     protected TestActorRef<TestRaftActor> leaderActor;
137     protected ActorRef leaderCollectorActor;
138     protected RaftActorContext leaderContext;
139     protected RaftActorBehavior leader;
140
141     protected String follower1Id = factory.generateActorId("follower");
142     protected TestActorRef<TestRaftActor> follower1Actor;
143     protected ActorRef follower1CollectorActor;
144     protected RaftActorBehavior follower1;
145     protected RaftActorContext follower1Context;
146
147     protected String follower2Id = factory.generateActorId("follower");
148     protected TestActorRef<TestRaftActor> follower2Actor;
149     protected ActorRef follower2CollectorActor;
150     protected  RaftActorBehavior follower2;
151     protected RaftActorContext follower2Context;
152
153     protected ImmutableMap<String, String> peerAddresses;
154
155     protected long initialTerm = 5;
156     protected long currentTerm;
157
158     @After
159     public void tearDown() {
160         InMemoryJournal.clear();
161         InMemorySnapshotStore.clear();
162         factory.close();
163     }
164
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));
172         return configParams;
173     }
174
175     protected DefaultConfigParamsImpl newFollowerConfigParams() {
176         DefaultConfigParamsImpl configParams = new DefaultConfigParamsImpl();
177         configParams.setHeartBeatInterval(new FiniteDuration(500, TimeUnit.MILLISECONDS));
178         configParams.setElectionTimeoutFactor(1000);
179         return configParams;
180     }
181
182     protected void waitUntilLeader(ActorRef actorRef) {
183         RaftActorTest.RaftActorTestKit.waitUntilLeader(actorRef);
184     }
185
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"));
191         return factory.createTestActor(TestRaftActor.props(id,
192                 peerAddresses != null ? peerAddresses : Collections.<String, String>emptyMap(),
193                         configParams, collectorActor), id);
194     }
195
196     protected void killActor(TestActorRef<TestRaftActor> leaderActor) {
197         JavaTestKit testkit = new JavaTestKit(getSystem());
198         testkit.watch(leaderActor);
199
200         leaderActor.tell(PoisonPill.getInstance(), null);
201         testkit.expectMsgClass(JavaTestKit.duration("5 seconds"), Terminated.class);
202
203         testkit.unwatch(leaderActor);
204     }
205
206     protected void verifyApplyJournalEntries(ActorRef actor, final long expIndex) {
207         MessageCollectorActor.expectFirstMatching(actor, ApplyJournalEntries.class, new Predicate<ApplyJournalEntries>() {
208             @Override
209             public boolean apply(ApplyJournalEntries msg) {
210                 return msg.getToIndex() == expIndex;
211             }
212         });
213     }
214
215     protected void verifySnapshot(String prefix, Snapshot snapshot, long lastAppliedTerm,
216             int lastAppliedIndex, long lastTerm, long lastIndex, byte[] data) {
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());
221         assertArrayEquals(prefix + " Snapshot getState", data, snapshot.getState());
222     }
223
224     protected void verifyPersistedJournal(String persistenceId, List<? extends ReplicatedLogEntry> expJournal) {
225         List<ReplicatedLogEntry> journal = InMemoryJournal.get(persistenceId, ReplicatedLogEntry.class);
226         assertEquals("Journal ReplicatedLogEntry count", expJournal.size(), journal.size());
227         for(int i = 0; i < expJournal.size(); i++) {
228             ReplicatedLogEntry expected = expJournal.get(i);
229             ReplicatedLogEntry actual = journal.get(i);
230             verifyReplicatedLogEntry(expected, actual.getTerm(), actual.getIndex(), actual.getData());
231         }
232     }
233
234     protected MockPayload sendPayloadData(ActorRef leaderActor, String data) {
235         return sendPayloadData(leaderActor, data, 0);
236     }
237
238     protected MockPayload sendPayloadData(ActorRef leaderActor, String data, int size) {
239         MockPayload payload;
240         if(size > 0) {
241             payload = new MockPayload(data, size);
242         } else {
243             payload = new MockPayload(data);
244         }
245
246         leaderActor.tell(payload, ActorRef.noSender());
247         return payload;
248     }
249
250     protected void verifyApplyState(ApplyState applyState, ActorRef expClientActor,
251             String expId, long expTerm, long expIndex, MockPayload payload) {
252         assertEquals("ApplyState getClientActor", expClientActor, applyState.getClientActor());
253         assertEquals("ApplyState getIdentifier", expId, applyState.getIdentifier());
254         ReplicatedLogEntry replicatedLogEntry = applyState.getReplicatedLogEntry();
255         verifyReplicatedLogEntry(replicatedLogEntry, expTerm, expIndex, payload);
256     }
257
258     protected void verifyReplicatedLogEntry(ReplicatedLogEntry replicatedLogEntry, long expTerm, long expIndex,
259             Payload payload) {
260         assertEquals("ReplicatedLogEntry getTerm", expTerm, replicatedLogEntry.getTerm());
261         assertEquals("ReplicatedLogEntry getIndex", expIndex, replicatedLogEntry.getIndex());
262         assertEquals("ReplicatedLogEntry getData", payload, replicatedLogEntry.getData());
263     }
264 }

©2013 OpenDaylight, A Linux Foundation Collaborative Project. All Rights Reserved.
OpenDaylight is a registered trademark of The OpenDaylight Project, Inc.
Linux Foundation and OpenDaylight are registered trademarks of the Linux Foundation.
Linux is a registered trademark of Linus Torvalds.