2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.controller.cluster.raft;
10 import static org.junit.Assert.fail;
12 import akka.actor.ActorRef;
13 import akka.actor.ActorSystem;
14 import akka.pattern.Patterns;
15 import akka.testkit.javadsl.EventFilter;
16 import akka.testkit.javadsl.TestKit;
17 import akka.util.Timeout;
18 import com.google.common.util.concurrent.Uninterruptibles;
19 import java.util.Optional;
20 import java.util.concurrent.TimeUnit;
21 import org.opendaylight.controller.cluster.raft.client.messages.FindLeader;
22 import org.opendaylight.controller.cluster.raft.client.messages.FindLeaderReply;
23 import org.slf4j.Logger;
24 import org.slf4j.LoggerFactory;
25 import scala.concurrent.Await;
26 import scala.concurrent.Future;
27 import scala.concurrent.duration.FiniteDuration;
29 public class RaftActorTestKit extends TestKit {
30 private static final Logger LOG = LoggerFactory.getLogger(RaftActorTestKit.class);
31 private final ActorRef raftActor;
33 public RaftActorTestKit(final ActorSystem actorSystem, final String actorName) {
35 raftActor = getSystem().actorOf(MockRaftActor.builder().id(actorName).props(), actorName);
38 public ActorRef getRaftActor() {
42 public boolean waitForLogMessage(final Class<?> logEventClass, final String message) {
43 // Wait for a specific log message to show up
44 return new EventFilter(logEventClass, getSystem()).from(raftActor.path().toString()).message(message)
45 .occurrences(1).intercept(() -> Boolean.TRUE);
48 protected void waitUntilLeader() {
49 waitUntilLeader(raftActor);
52 @SuppressWarnings("checkstyle:IllegalCatch")
53 public static void waitUntilLeader(final ActorRef actorRef) {
54 FiniteDuration duration = FiniteDuration.create(100, TimeUnit.MILLISECONDS);
55 for (int i = 0; i < 20 * 5; i++) {
56 Future<Object> future = Patterns.ask(actorRef, FindLeader.INSTANCE, new Timeout(duration));
58 final Optional<String> maybeLeader = ((FindLeaderReply)Await.result(future, duration)).getLeaderActor();
59 if (maybeLeader.isPresent()) {
62 } catch (Exception e) {
63 LOG.error("FindLeader failed", e);
66 Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
69 fail("Leader not found for actorRef " + actorRef.path());