2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
3 * Copyright (c) 2015 Brocade Communications Systems, Inc. and others. All rights reserved.
5 * This program and the accompanying materials are made available under the
6 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
7 * and is available at http://www.eclipse.org/legal/epl-v10.html
9 package org.opendaylight.controller.cluster.raft;
11 import static org.junit.Assert.assertEquals;
12 import static org.mockito.Mockito.mock;
14 import akka.actor.ActorRef;
15 import akka.actor.Props;
16 import com.google.common.base.Function;
17 import com.google.common.base.Optional;
18 import com.google.common.base.Throwables;
19 import com.google.common.util.concurrent.Uninterruptibles;
20 import java.io.ByteArrayInputStream;
21 import java.io.IOException;
22 import java.io.ObjectInputStream;
23 import java.util.ArrayList;
24 import java.util.Collections;
25 import java.util.List;
27 import java.util.concurrent.CountDownLatch;
28 import java.util.concurrent.TimeUnit;
29 import javax.annotation.Nonnull;
30 import org.opendaylight.controller.cluster.DataPersistenceProvider;
31 import org.opendaylight.controller.cluster.raft.behaviors.RaftActorBehavior;
32 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
33 import org.opendaylight.yangtools.concepts.Identifier;
35 public class MockRaftActor extends RaftActor implements RaftActorRecoveryCohort, RaftActorSnapshotCohort {
36 public static final short PAYLOAD_VERSION = 5;
38 final RaftActor actorDelegate;
39 final RaftActorRecoveryCohort recoveryCohortDelegate;
40 volatile RaftActorSnapshotCohort snapshotCohortDelegate;
41 private final CountDownLatch recoveryComplete = new CountDownLatch(1);
42 private final List<Object> state;
43 private final ActorRef roleChangeNotifier;
44 protected final CountDownLatch initializeBehaviorComplete = new CountDownLatch(1);
45 private RaftActorRecoverySupport raftActorRecoverySupport;
46 private RaftActorSnapshotMessageSupport snapshotMessageSupport;
47 private final byte[] restoreFromSnapshot;
48 final CountDownLatch snapshotCommitted = new CountDownLatch(1);
49 private final Function<Runnable, Void> pauseLeaderFunction;
51 protected MockRaftActor(AbstractBuilder<?, ?> builder) {
52 super(builder.id, builder.peerAddresses != null ? builder.peerAddresses :
53 Collections.<String, String>emptyMap(), Optional.fromNullable(builder.config), PAYLOAD_VERSION);
54 state = new ArrayList<>();
55 this.actorDelegate = mock(RaftActor.class);
56 this.recoveryCohortDelegate = mock(RaftActorRecoveryCohort.class);
58 this.snapshotCohortDelegate = builder.snapshotCohort != null ? builder.snapshotCohort :
59 mock(RaftActorSnapshotCohort.class);
61 if (builder.dataPersistenceProvider == null) {
62 setPersistence(builder.persistent.isPresent() ? builder.persistent.get() : true);
64 setPersistence(builder.dataPersistenceProvider);
67 roleChangeNotifier = builder.roleChangeNotifier;
68 snapshotMessageSupport = builder.snapshotMessageSupport;
69 restoreFromSnapshot = builder.restoreFromSnapshot;
70 pauseLeaderFunction = builder.pauseLeaderFunction;
73 public void setRaftActorRecoverySupport(RaftActorRecoverySupport support) {
74 raftActorRecoverySupport = support;
78 public RaftActorRecoverySupport newRaftActorRecoverySupport() {
79 return raftActorRecoverySupport != null ? raftActorRecoverySupport : super.newRaftActorRecoverySupport();
83 protected RaftActorSnapshotMessageSupport newRaftActorSnapshotMessageSupport() {
84 return snapshotMessageSupport != null ? snapshotMessageSupport :
85 (snapshotMessageSupport = super.newRaftActorSnapshotMessageSupport());
89 public RaftActorContext getRaftActorContext() {
90 return super.getRaftActorContext();
93 public RaftActorSnapshotMessageSupport getSnapshotMessageSupport() {
94 return snapshotMessageSupport;
97 public void waitForRecoveryComplete() {
99 assertEquals("Recovery complete", true, recoveryComplete.await(5, TimeUnit.SECONDS));
100 } catch (InterruptedException e) {
101 Throwables.propagate(e);
105 public void waitForInitializeBehaviorComplete() {
107 assertEquals("Behavior initialized", true, initializeBehaviorComplete.await(5, TimeUnit.SECONDS));
108 } catch (InterruptedException e) {
109 Throwables.propagate(e);
114 public void waitUntilLeader() {
115 for (int i = 0; i < 10; i++) {
119 Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
123 public List<Object> getState() {
128 protected void applyState(ActorRef clientActor, Identifier identifier, Object data) {
129 actorDelegate.applyState(clientActor, identifier, data);
130 LOG.info("{}: applyState called: {}", persistenceId(), data);
137 protected RaftActorRecoveryCohort getRaftActorRecoveryCohort() {
142 protected RaftActorSnapshotCohort getRaftActorSnapshotCohort() {
147 public void startLogRecoveryBatch(int maxBatchSize) {
151 public void appendRecoveredLogEntry(Payload data) {
156 public void applyCurrentLogRecoveryBatch() {
160 protected void onRecoveryComplete() {
161 actorDelegate.onRecoveryComplete();
162 recoveryComplete.countDown();
166 protected void initializeBehavior() {
167 super.initializeBehavior();
168 initializeBehaviorComplete.countDown();
172 public void applyRecoverySnapshot(byte[] bytes) {
173 recoveryCohortDelegate.applyRecoverySnapshot(bytes);
174 applySnapshotBytes(bytes);
177 private void applySnapshotBytes(byte[] bytes) {
178 if (bytes.length == 0) {
183 Object data = toObject(bytes);
184 if (data instanceof List) {
186 state.addAll((List<?>) data);
188 } catch (ClassNotFoundException | IOException e) {
189 Throwables.propagate(e);
194 public void createSnapshot(ActorRef actorRef) {
195 LOG.info("{}: createSnapshot called", persistenceId());
196 snapshotCohortDelegate.createSnapshot(actorRef);
200 public void applySnapshot(byte [] snapshot) {
201 LOG.info("{}: applySnapshot called", persistenceId());
202 applySnapshotBytes(snapshot);
203 snapshotCohortDelegate.applySnapshot(snapshot);
207 protected void onStateChanged() {
208 actorDelegate.onStateChanged();
212 protected Optional<ActorRef> getRoleChangeNotifier() {
213 return Optional.fromNullable(roleChangeNotifier);
216 @Override public String persistenceId() {
220 protected void newBehavior(RaftActorBehavior newBehavior) {
221 self().tell(newBehavior, ActorRef.noSender());
225 protected void handleCommand(final Object message) {
226 if (message instanceof RaftActorBehavior) {
227 super.changeCurrentBehavior((RaftActorBehavior)message);
229 super.handleCommand(message);
231 if (RaftActorSnapshotMessageSupport.COMMIT_SNAPSHOT.equals(message)) {
232 snapshotCommitted.countDown();
238 protected void pauseLeader(Runnable operation) {
239 if (pauseLeaderFunction != null) {
240 pauseLeaderFunction.apply(operation);
242 super.pauseLeader(operation);
246 public static Object toObject(byte[] bs) throws ClassNotFoundException, IOException {
248 ByteArrayInputStream bis = null;
249 ObjectInputStream ois = null;
251 bis = new ByteArrayInputStream(bs);
252 ois = new ObjectInputStream(bis);
253 obj = ois.readObject();
265 public ReplicatedLog getReplicatedLog() {
266 return this.getRaftActorContext().getReplicatedLog();
270 public byte[] getRestoreFromSnapshot() {
271 return restoreFromSnapshot;
274 public static Props props(final String id, final Map<String, String> peerAddresses, ConfigParams config) {
275 return builder().id(id).peerAddresses(peerAddresses).config(config).props();
278 public static Props props(final String id, final Map<String, String> peerAddresses,
279 ConfigParams config, DataPersistenceProvider dataPersistenceProvider) {
280 return builder().id(id).peerAddresses(peerAddresses).config(config)
281 .dataPersistenceProvider(dataPersistenceProvider).props();
284 public static Builder builder() {
285 return new Builder();
288 public static class AbstractBuilder<T extends AbstractBuilder<T, A>, A extends MockRaftActor> {
289 private Map<String, String> peerAddresses = Collections.emptyMap();
291 private ConfigParams config;
292 private DataPersistenceProvider dataPersistenceProvider;
293 private ActorRef roleChangeNotifier;
294 private RaftActorSnapshotMessageSupport snapshotMessageSupport;
295 private byte[] restoreFromSnapshot;
296 private Optional<Boolean> persistent = Optional.absent();
297 private final Class<A> actorClass;
298 private Function<Runnable, Void> pauseLeaderFunction;
299 private RaftActorSnapshotCohort snapshotCohort;
301 protected AbstractBuilder(Class<A> actorClass) {
302 this.actorClass = actorClass;
305 @SuppressWarnings("unchecked")
310 public T id(String newId) {
315 public T peerAddresses(Map<String, String> newPeerAddresses) {
316 this.peerAddresses = newPeerAddresses;
320 public T config(ConfigParams newConfig) {
321 this.config = newConfig;
325 public T dataPersistenceProvider(DataPersistenceProvider newDataPersistenceProvider) {
326 this.dataPersistenceProvider = newDataPersistenceProvider;
330 public T roleChangeNotifier(ActorRef newRoleChangeNotifier) {
331 this.roleChangeNotifier = newRoleChangeNotifier;
335 public T snapshotMessageSupport(RaftActorSnapshotMessageSupport newSnapshotMessageSupport) {
336 this.snapshotMessageSupport = newSnapshotMessageSupport;
340 public T restoreFromSnapshot(byte[] newRestoreFromSnapshot) {
341 this.restoreFromSnapshot = newRestoreFromSnapshot;
345 public T persistent(Optional<Boolean> newPersistent) {
346 this.persistent = newPersistent;
350 public T pauseLeaderFunction(Function<Runnable, Void> newPauseLeaderFunction) {
351 this.pauseLeaderFunction = newPauseLeaderFunction;
355 public T snapshotCohort(RaftActorSnapshotCohort newSnapshotCohort) {
356 this.snapshotCohort = newSnapshotCohort;
360 public Props props() {
361 return Props.create(actorClass, this);
365 public static class Builder extends AbstractBuilder<Builder, MockRaftActor> {
367 super(MockRaftActor.class);