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.io.ByteSource;
20 import com.google.common.util.concurrent.Uninterruptibles;
21 import java.io.IOException;
22 import java.io.OutputStream;
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.apache.commons.lang3.SerializationUtils;
31 import org.opendaylight.controller.cluster.DataPersistenceProvider;
32 import org.opendaylight.controller.cluster.raft.behaviors.RaftActorBehavior;
33 import org.opendaylight.controller.cluster.raft.persisted.Snapshot;
34 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
35 import org.opendaylight.yangtools.concepts.Identifier;
37 public class MockRaftActor extends RaftActor implements RaftActorRecoveryCohort, RaftActorSnapshotCohort {
38 public static final short PAYLOAD_VERSION = 5;
40 final RaftActor actorDelegate;
41 final RaftActorRecoveryCohort recoveryCohortDelegate;
42 volatile RaftActorSnapshotCohort snapshotCohortDelegate;
43 private final CountDownLatch recoveryComplete = new CountDownLatch(1);
44 private final List<Object> state;
45 private final ActorRef roleChangeNotifier;
46 protected final CountDownLatch initializeBehaviorComplete = new CountDownLatch(1);
47 private RaftActorRecoverySupport raftActorRecoverySupport;
48 private RaftActorSnapshotMessageSupport snapshotMessageSupport;
49 private final Snapshot restoreFromSnapshot;
50 final CountDownLatch snapshotCommitted = new CountDownLatch(1);
51 private final Function<Runnable, Void> pauseLeaderFunction;
53 protected MockRaftActor(AbstractBuilder<?, ?> builder) {
54 super(builder.id, builder.peerAddresses != null ? builder.peerAddresses :
55 Collections.<String, String>emptyMap(), Optional.fromNullable(builder.config), PAYLOAD_VERSION);
56 state = new ArrayList<>();
57 this.actorDelegate = mock(RaftActor.class);
58 this.recoveryCohortDelegate = mock(RaftActorRecoveryCohort.class);
60 this.snapshotCohortDelegate = builder.snapshotCohort != null ? builder.snapshotCohort :
61 mock(RaftActorSnapshotCohort.class);
63 if (builder.dataPersistenceProvider == null) {
64 setPersistence(builder.persistent.isPresent() ? builder.persistent.get() : true);
66 setPersistence(builder.dataPersistenceProvider);
69 roleChangeNotifier = builder.roleChangeNotifier;
70 snapshotMessageSupport = builder.snapshotMessageSupport;
71 restoreFromSnapshot = builder.restoreFromSnapshot;
72 pauseLeaderFunction = builder.pauseLeaderFunction;
75 public void setRaftActorRecoverySupport(RaftActorRecoverySupport support) {
76 raftActorRecoverySupport = support;
80 public RaftActorRecoverySupport newRaftActorRecoverySupport() {
81 return raftActorRecoverySupport != null ? raftActorRecoverySupport : super.newRaftActorRecoverySupport();
85 protected RaftActorSnapshotMessageSupport newRaftActorSnapshotMessageSupport() {
86 return snapshotMessageSupport != null ? snapshotMessageSupport :
87 (snapshotMessageSupport = super.newRaftActorSnapshotMessageSupport());
91 public RaftActorContext getRaftActorContext() {
92 return super.getRaftActorContext();
95 public RaftActorSnapshotMessageSupport getSnapshotMessageSupport() {
96 return snapshotMessageSupport;
99 public void waitForRecoveryComplete() {
101 assertEquals("Recovery complete", true, recoveryComplete.await(5, TimeUnit.SECONDS));
102 } catch (InterruptedException e) {
103 Throwables.propagate(e);
107 public void waitForInitializeBehaviorComplete() {
109 assertEquals("Behavior initialized", true, initializeBehaviorComplete.await(5, TimeUnit.SECONDS));
110 } catch (InterruptedException e) {
111 Throwables.propagate(e);
116 public void waitUntilLeader() {
117 for (int i = 0; i < 10; i++) {
121 Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
125 public List<Object> getState() {
130 protected void applyState(ActorRef clientActor, Identifier identifier, Object data) {
131 actorDelegate.applyState(clientActor, identifier, data);
132 LOG.info("{}: applyState called: {}", persistenceId(), data);
139 protected RaftActorRecoveryCohort getRaftActorRecoveryCohort() {
144 protected RaftActorSnapshotCohort getRaftActorSnapshotCohort() {
149 public void startLogRecoveryBatch(int maxBatchSize) {
153 public void appendRecoveredLogEntry(Payload data) {
158 public void applyCurrentLogRecoveryBatch() {
162 protected void onRecoveryComplete() {
163 actorDelegate.onRecoveryComplete();
164 recoveryComplete.countDown();
168 protected void initializeBehavior() {
169 super.initializeBehavior();
170 initializeBehaviorComplete.countDown();
174 public void applyRecoverySnapshot(Snapshot.State newState) {
175 recoveryCohortDelegate.applyRecoverySnapshot(newState);
176 applySnapshotState(newState);
179 private void applySnapshotState(Snapshot.State newState) {
180 if (newState instanceof MockSnapshotState) {
182 state.addAll(((MockSnapshotState)newState).getState());
187 public void createSnapshot(ActorRef actorRef, java.util.Optional<OutputStream> installSnapshotStream) {
188 LOG.info("{}: createSnapshot called", persistenceId());
189 snapshotCohortDelegate.createSnapshot(actorRef, installSnapshotStream);
193 public void applySnapshot(Snapshot.State newState) {
194 LOG.info("{}: applySnapshot called", persistenceId());
195 applySnapshotState(newState);
196 snapshotCohortDelegate.applySnapshot(newState);
200 public Snapshot.State deserializeSnapshot(ByteSource snapshotBytes) {
202 return (Snapshot.State) SerializationUtils.deserialize(snapshotBytes.read());
203 } catch (IOException e) {
204 throw new RuntimeException("Error deserializing state", e);
209 protected void onStateChanged() {
210 actorDelegate.onStateChanged();
214 protected Optional<ActorRef> getRoleChangeNotifier() {
215 return Optional.fromNullable(roleChangeNotifier);
218 @Override public String persistenceId() {
222 protected void newBehavior(RaftActorBehavior newBehavior) {
223 self().tell(newBehavior, ActorRef.noSender());
227 protected void handleCommand(final Object message) {
228 if (message instanceof RaftActorBehavior) {
229 super.changeCurrentBehavior((RaftActorBehavior)message);
231 super.handleCommand(message);
233 if (RaftActorSnapshotMessageSupport.COMMIT_SNAPSHOT.equals(message)) {
234 snapshotCommitted.countDown();
240 protected void pauseLeader(Runnable operation) {
241 if (pauseLeaderFunction != null) {
242 pauseLeaderFunction.apply(operation);
244 super.pauseLeader(operation);
248 public static List<Object> fromState(Snapshot.State from) {
249 if (from instanceof MockSnapshotState) {
250 return ((MockSnapshotState)from).getState();
253 throw new IllegalStateException("Unexpected snapshot State: " + from);
256 public ReplicatedLog getReplicatedLog() {
257 return this.getRaftActorContext().getReplicatedLog();
261 public Snapshot getRestoreFromSnapshot() {
262 return restoreFromSnapshot;
265 public static Props props(final String id, final Map<String, String> peerAddresses, ConfigParams config) {
266 return builder().id(id).peerAddresses(peerAddresses).config(config).props();
269 public static Props props(final String id, final Map<String, String> peerAddresses,
270 ConfigParams config, DataPersistenceProvider dataPersistenceProvider) {
271 return builder().id(id).peerAddresses(peerAddresses).config(config)
272 .dataPersistenceProvider(dataPersistenceProvider).props();
275 public static Builder builder() {
276 return new Builder();
279 public static class AbstractBuilder<T extends AbstractBuilder<T, A>, A extends MockRaftActor> {
280 private Map<String, String> peerAddresses = Collections.emptyMap();
282 private ConfigParams config;
283 private DataPersistenceProvider dataPersistenceProvider;
284 private ActorRef roleChangeNotifier;
285 private RaftActorSnapshotMessageSupport snapshotMessageSupport;
286 private Snapshot restoreFromSnapshot;
287 private Optional<Boolean> persistent = Optional.absent();
288 private final Class<A> actorClass;
289 private Function<Runnable, Void> pauseLeaderFunction;
290 private RaftActorSnapshotCohort snapshotCohort;
292 protected AbstractBuilder(Class<A> actorClass) {
293 this.actorClass = actorClass;
296 @SuppressWarnings("unchecked")
301 public T id(String newId) {
306 public T peerAddresses(Map<String, String> newPeerAddresses) {
307 this.peerAddresses = newPeerAddresses;
311 public T config(ConfigParams newConfig) {
312 this.config = newConfig;
316 public T dataPersistenceProvider(DataPersistenceProvider newDataPersistenceProvider) {
317 this.dataPersistenceProvider = newDataPersistenceProvider;
321 public T roleChangeNotifier(ActorRef newRoleChangeNotifier) {
322 this.roleChangeNotifier = newRoleChangeNotifier;
326 public T snapshotMessageSupport(RaftActorSnapshotMessageSupport newSnapshotMessageSupport) {
327 this.snapshotMessageSupport = newSnapshotMessageSupport;
331 public T restoreFromSnapshot(Snapshot newRestoreFromSnapshot) {
332 this.restoreFromSnapshot = newRestoreFromSnapshot;
336 public T persistent(Optional<Boolean> newPersistent) {
337 this.persistent = newPersistent;
341 public T pauseLeaderFunction(Function<Runnable, Void> newPauseLeaderFunction) {
342 this.pauseLeaderFunction = newPauseLeaderFunction;
346 public T snapshotCohort(RaftActorSnapshotCohort newSnapshotCohort) {
347 this.snapshotCohort = newSnapshotCohort;
351 public Props props() {
352 return Props.create(actorClass, this);
356 public static class Builder extends AbstractBuilder<Builder, MockRaftActor> {
358 super(MockRaftActor.class);
362 public static class MockSnapshotState implements Snapshot.State {
363 private static final long serialVersionUID = 1L;
365 private final List<Object> state;
367 public MockSnapshotState(List<Object> state) {
371 public List<Object> getState() {
376 public int hashCode() {
377 final int prime = 31;
379 result = prime * result + (state == null ? 0 : state.hashCode());
384 public boolean equals(Object obj) {
391 if (getClass() != obj.getClass()) {
394 MockSnapshotState other = (MockSnapshotState) obj;
396 if (other.state != null) {
399 } else if (!state.equals(other.state)) {
406 public String toString() {
407 return "MockSnapshotState [state=" + state + "]";