b81dcc92acfcc1d781e68c03ad9b8c3a334cee5e
[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.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.base.Predicate;
20 import com.google.common.collect.ImmutableMap;
21 import com.google.common.util.concurrent.Uninterruptibles;
22 import java.util.ArrayList;
23 import java.util.Collections;
24 import java.util.List;
25 import java.util.Map;
26 import java.util.concurrent.ConcurrentHashMap;
27 import java.util.concurrent.TimeUnit;
28 import java.util.function.Supplier;
29 import org.junit.After;
30 import org.opendaylight.controller.cluster.raft.MockRaftActorContext.MockPayload;
31 import org.opendaylight.controller.cluster.raft.base.messages.ApplyJournalEntries;
32 import org.opendaylight.controller.cluster.raft.base.messages.ApplyState;
33 import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshotReply;
34 import org.opendaylight.controller.cluster.raft.base.messages.SendHeartBeat;
35 import org.opendaylight.controller.cluster.raft.behaviors.RaftActorBehavior;
36 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
37 import org.opendaylight.controller.cluster.raft.utils.InMemoryJournal;
38 import org.opendaylight.controller.cluster.raft.utils.InMemorySnapshotStore;
39 import org.opendaylight.controller.cluster.raft.utils.MessageCollectorActor;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42 import scala.concurrent.duration.FiniteDuration;
43
44 /**
45  * Abstract base for an integration test that tests end-to-end RaftActor and behavior functionality.
46  *
47  * @author Thomas Pantelis
48  */
49 public abstract class AbstractRaftActorIntegrationTest extends AbstractActorTest {
50
51     public static class SetPeerAddress {
52         private final String peerId;
53         private final String peerAddress;
54
55         public SetPeerAddress(String peerId, String peerAddress) {
56             this.peerId = peerId;
57             this.peerAddress = peerAddress;
58         }
59
60         public String getPeerId() {
61             return peerId;
62         }
63
64         public String getPeerAddress() {
65             return peerAddress;
66         }
67     }
68
69     public static class TestRaftActor extends MockRaftActor {
70
71         private final TestActorRef<MessageCollectorActor> collectorActor;
72         private final Map<Class<?>, Boolean> dropMessages = new ConcurrentHashMap<>();
73
74         private TestRaftActor(Builder builder) {
75             super(builder);
76             this.collectorActor = builder.collectorActor;
77         }
78
79         void startDropMessages(Class<?> msgClass) {
80             dropMessages.put(msgClass, Boolean.TRUE);
81         }
82
83         void stopDropMessages(Class<?> msgClass) {
84             dropMessages.remove(msgClass);
85         }
86
87         void setMockTotalMemory(final long mockTotalMemory) {
88             if(mockTotalMemory > 0) {
89                 getRaftActorContext().setTotalMemoryRetriever(new Supplier<Long>() {
90                     @Override
91                     public Long get() {
92                         return mockTotalMemory;
93                     }
94
95                 });
96             } else {
97                 getRaftActorContext().setTotalMemoryRetriever(null);
98             }
99         }
100
101         @Override
102         public void handleCommand(Object message) {
103             if(message instanceof MockPayload) {
104                 MockPayload payload = (MockPayload)message;
105                 super.persistData(collectorActor, payload.toString(), payload);
106                 return;
107             }
108
109             if(message instanceof SetPeerAddress) {
110                 setPeerAddress(((SetPeerAddress) message).getPeerId().toString(),
111                         ((SetPeerAddress) message).getPeerAddress());
112                 return;
113             }
114
115             try {
116                 if(!dropMessages.containsKey(message.getClass())) {
117                     super.handleCommand(message);
118                 }
119             } finally {
120                 if(!(message instanceof SendHeartBeat)) {
121                     try {
122                         collectorActor.tell(message, ActorRef.noSender());
123                     } catch (Exception e) {
124                         LOG.error("MessageCollectorActor error", e);
125                     }
126                 }
127             }
128         }
129
130         @Override
131         public void createSnapshot(ActorRef actorRef) {
132             try {
133                 actorRef.tell(new CaptureSnapshotReply(RaftActorTest.fromObject(getState()).toByteArray()), actorRef);
134             } catch (Exception e) {
135                 e.printStackTrace();
136             }
137         }
138
139         public ActorRef collectorActor() {
140             return collectorActor;
141         }
142
143         public static Builder newBuilder() {
144             return new Builder();
145         }
146
147         public static class Builder extends AbstractBuilder<Builder, TestRaftActor> {
148             private TestActorRef<MessageCollectorActor> collectorActor;
149
150             public Builder collectorActor(TestActorRef<MessageCollectorActor> collectorActor) {
151                 this.collectorActor = collectorActor;
152                 return this;
153             }
154
155             private Builder() {
156                 super(TestRaftActor.class);
157             }
158         }
159     }
160
161     protected static final int SNAPSHOT_CHUNK_SIZE = 100;
162
163     protected final Logger testLog = LoggerFactory.getLogger(getClass());
164
165     protected final TestActorFactory factory = new TestActorFactory(getSystem());
166
167     protected String leaderId = factory.generateActorId("leader");
168     protected DefaultConfigParamsImpl leaderConfigParams;
169     protected TestActorRef<TestRaftActor> leaderActor;
170     protected ActorRef leaderCollectorActor;
171     protected RaftActorContext leaderContext;
172     protected RaftActorBehavior leader;
173
174     protected String follower1Id = factory.generateActorId("follower");
175     protected TestActorRef<TestRaftActor> follower1Actor;
176     protected ActorRef follower1CollectorActor;
177     protected RaftActorBehavior follower1;
178     protected RaftActorContext follower1Context;
179
180     protected String follower2Id = factory.generateActorId("follower");
181     protected TestActorRef<TestRaftActor> follower2Actor;
182     protected ActorRef follower2CollectorActor;
183     protected  RaftActorBehavior follower2;
184     protected RaftActorContext follower2Context;
185
186     protected ImmutableMap<String, String> peerAddresses;
187
188     protected long initialTerm = 5;
189     protected long currentTerm;
190
191     protected int snapshotBatchCount = 4;
192
193     protected List<MockPayload> expSnapshotState = new ArrayList<>();
194
195     @After
196     public void tearDown() {
197         InMemoryJournal.clear();
198         InMemorySnapshotStore.clear();
199         factory.close();
200     }
201
202     protected DefaultConfigParamsImpl newLeaderConfigParams() {
203         DefaultConfigParamsImpl configParams = new DefaultConfigParamsImpl();
204         configParams.setHeartBeatInterval(new FiniteDuration(100, TimeUnit.MILLISECONDS));
205         configParams.setElectionTimeoutFactor(1);
206         configParams.setSnapshotBatchCount(snapshotBatchCount);
207         configParams.setSnapshotDataThresholdPercentage(70);
208         configParams.setIsolatedLeaderCheckInterval(new FiniteDuration(1, TimeUnit.DAYS));
209         configParams.setSnapshotChunkSize(SNAPSHOT_CHUNK_SIZE);
210         return configParams;
211     }
212
213     protected DefaultConfigParamsImpl newFollowerConfigParams() {
214         DefaultConfigParamsImpl configParams = new DefaultConfigParamsImpl();
215         configParams.setHeartBeatInterval(new FiniteDuration(500, TimeUnit.MILLISECONDS));
216         configParams.setElectionTimeoutFactor(1000);
217         return configParams;
218     }
219
220     protected void waitUntilLeader(ActorRef actorRef) {
221         RaftActorTestKit.waitUntilLeader(actorRef);
222     }
223
224     protected TestActorRef<TestRaftActor> newTestRaftActor(String id, Map<String, String> peerAddresses,
225             ConfigParams configParams) {
226         return newTestRaftActor(id, TestRaftActor.newBuilder().peerAddresses(peerAddresses != null ? peerAddresses :
227             Collections.<String, String>emptyMap()).config(configParams));
228     }
229
230     protected TestActorRef<TestRaftActor> newTestRaftActor(String id, TestRaftActor.Builder builder) {
231         builder.collectorActor(factory.<MessageCollectorActor>createTestActor(
232                 MessageCollectorActor.props().withDispatcher(Dispatchers.DefaultDispatcherId()),
233                         factory.generateActorId(id + "-collector"))).id(id);
234
235         InvalidActorNameException lastEx = null;
236         for(int i = 0; i < 10; i++) {
237             try {
238                 return factory.createTestActor(builder.props().withDispatcher(Dispatchers.DefaultDispatcherId()), id);
239             } catch (InvalidActorNameException e) {
240                 lastEx = e;
241                 Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
242             }
243         }
244
245         assertNotNull(lastEx);
246         throw lastEx;
247     }
248
249     protected void killActor(TestActorRef<TestRaftActor> leaderActor) {
250         JavaTestKit testkit = new JavaTestKit(getSystem());
251         testkit.watch(leaderActor);
252
253         leaderActor.tell(PoisonPill.getInstance(), null);
254         testkit.expectMsgClass(JavaTestKit.duration("5 seconds"), Terminated.class);
255
256         testkit.unwatch(leaderActor);
257     }
258
259     protected void verifyApplyJournalEntries(ActorRef actor, final long expIndex) {
260         MessageCollectorActor.expectFirstMatching(actor, ApplyJournalEntries.class, new Predicate<ApplyJournalEntries>() {
261             @Override
262             public boolean apply(ApplyJournalEntries msg) {
263                 return msg.getToIndex() == expIndex;
264             }
265         });
266     }
267
268     @SuppressWarnings("unchecked")
269     protected void verifySnapshot(String prefix, Snapshot snapshot, long lastAppliedTerm,
270             long lastAppliedIndex, long lastTerm, long lastIndex)
271                     throws Exception {
272         assertEquals(prefix + " Snapshot getLastAppliedTerm", lastAppliedTerm, snapshot.getLastAppliedTerm());
273         assertEquals(prefix + " Snapshot getLastAppliedIndex", lastAppliedIndex, snapshot.getLastAppliedIndex());
274         assertEquals(prefix + " Snapshot getLastTerm", lastTerm, snapshot.getLastTerm());
275         assertEquals(prefix + " Snapshot getLastIndex", lastIndex, snapshot.getLastIndex());
276
277         List<Object> actualState = (List<Object>)MockRaftActor.toObject(snapshot.getState());
278         assertEquals(String.format("%s Snapshot getState size. Expected %s: . Actual: %s", prefix, expSnapshotState,
279                 actualState), expSnapshotState.size(), actualState.size());
280         for(int i = 0; i < expSnapshotState.size(); i++) {
281             assertEquals(prefix + " Snapshot state " + i, expSnapshotState.get(i), actualState.get(i));
282         }
283     }
284
285     protected void verifyPersistedJournal(String persistenceId, List<? extends ReplicatedLogEntry> expJournal) {
286         List<ReplicatedLogEntry> journal = InMemoryJournal.get(persistenceId, ReplicatedLogEntry.class);
287         assertEquals("Journal ReplicatedLogEntry count", expJournal.size(), journal.size());
288         for(int i = 0; i < expJournal.size(); i++) {
289             ReplicatedLogEntry expected = expJournal.get(i);
290             ReplicatedLogEntry actual = journal.get(i);
291             verifyReplicatedLogEntry(expected, actual.getTerm(), actual.getIndex(), actual.getData());
292         }
293     }
294
295     protected MockPayload sendPayloadData(ActorRef leaderActor, String data) {
296         return sendPayloadData(leaderActor, data, 0);
297     }
298
299     protected MockPayload sendPayloadData(ActorRef leaderActor, String data, int size) {
300         MockPayload payload;
301         if(size > 0) {
302             payload = new MockPayload(data, size);
303         } else {
304             payload = new MockPayload(data);
305         }
306
307         leaderActor.tell(payload, ActorRef.noSender());
308         return payload;
309     }
310
311     protected void verifyApplyState(ApplyState applyState, ActorRef expClientActor,
312             String expId, long expTerm, long expIndex, MockPayload payload) {
313         assertEquals("ApplyState getClientActor", expClientActor, applyState.getClientActor());
314         assertEquals("ApplyState getIdentifier", expId, applyState.getIdentifier());
315         ReplicatedLogEntry replicatedLogEntry = applyState.getReplicatedLogEntry();
316         verifyReplicatedLogEntry(replicatedLogEntry, expTerm, expIndex, payload);
317     }
318
319     protected void verifyReplicatedLogEntry(ReplicatedLogEntry replicatedLogEntry, long expTerm, long expIndex,
320             Payload payload) {
321         assertEquals("ReplicatedLogEntry getTerm", expTerm, replicatedLogEntry.getTerm());
322         assertEquals("ReplicatedLogEntry getIndex", expIndex, replicatedLogEntry.getIndex());
323         assertEquals("ReplicatedLogEntry getData", payload, replicatedLogEntry.getData());
324     }
325
326     protected String testActorPath(String id){
327         return factory.createTestActorPath(id);
328     }
329
330     protected void verifyLeadersTrimmedLog(long lastIndex) {
331         verifyTrimmedLog("Leader", leaderActor, lastIndex, lastIndex - 1);
332     }
333
334     protected void verifyLeadersTrimmedLog(long lastIndex, long replicatedToAllIndex) {
335         verifyTrimmedLog("Leader", leaderActor, lastIndex, replicatedToAllIndex);
336     }
337
338     protected void verifyFollowersTrimmedLog(int num, TestActorRef<TestRaftActor> actorRef, long lastIndex) {
339         verifyTrimmedLog("Follower " + num, actorRef, lastIndex, lastIndex - 1);
340     }
341
342     protected void verifyTrimmedLog(String name, TestActorRef<TestRaftActor> actorRef, long lastIndex,
343             long replicatedToAllIndex) {
344         TestRaftActor actor = actorRef.underlyingActor();
345         RaftActorContext context = actor.getRaftActorContext();
346         long snapshotIndex = lastIndex - 1;
347         assertEquals(name + " snapshot term", snapshotIndex < 0 ? -1 : currentTerm,
348                 context.getReplicatedLog().getSnapshotTerm());
349         assertEquals(name + " snapshot index", snapshotIndex, context.getReplicatedLog().getSnapshotIndex());
350         assertEquals(name + " journal log size", 1, context.getReplicatedLog().size());
351         assertEquals(name + " journal last index", lastIndex, context.getReplicatedLog().lastIndex());
352         assertEquals(name + " commit index", lastIndex, context.getCommitIndex());
353         assertEquals(name + " last applied", lastIndex, context.getLastApplied());
354         assertEquals(name + " replicatedToAllIndex", replicatedToAllIndex,
355                 actor.getCurrentBehavior().getReplicatedToAllIndex());
356     }
357 }

©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.