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

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