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 akka.actor.ActorRef;
11 import akka.actor.ActorSystem;
12 import akka.pattern.Patterns;
13 import akka.testkit.JavaTestKit;
14 import akka.util.Timeout;
15 import com.google.common.util.concurrent.Uninterruptibles;
16 import java.util.Optional;
17 import java.util.concurrent.TimeUnit;
18 import org.junit.Assert;
19 import org.opendaylight.controller.cluster.raft.client.messages.FindLeader;
20 import org.opendaylight.controller.cluster.raft.client.messages.FindLeaderReply;
21 import org.slf4j.Logger;
22 import org.slf4j.LoggerFactory;
23 import scala.concurrent.Await;
24 import scala.concurrent.Future;
25 import scala.concurrent.duration.Duration;
26 import scala.concurrent.duration.FiniteDuration;
28 public class RaftActorTestKit extends JavaTestKit {
29 private static final Logger LOG = LoggerFactory.getLogger(RaftActorTestKit.class);
30 private final ActorRef raftActor;
32 public RaftActorTestKit(ActorSystem actorSystem, String actorName) {
35 raftActor = this.getSystem().actorOf(MockRaftActor.builder().id(actorName).props(), actorName);
40 public ActorRef getRaftActor() {
44 public boolean waitForLogMessage(final Class<?> logEventClass, String message) {
45 // Wait for a specific log message to show up
47 new JavaTestKit.EventFilter<Boolean>(logEventClass
50 protected Boolean run() {
53 }.from(raftActor.path().toString())
55 .occurrences(1).exec();
60 protected void waitUntilLeader() {
61 waitUntilLeader(raftActor);
64 @SuppressWarnings("checkstyle:IllegalCatch")
65 public static void waitUntilLeader(ActorRef actorRef) {
66 FiniteDuration duration = Duration.create(100, TimeUnit.MILLISECONDS);
67 for (int i = 0; i < 20 * 5; i++) {
68 Future<Object> future = Patterns.ask(actorRef, FindLeader.INSTANCE, new Timeout(duration));
70 final Optional<String> maybeLeader = ((FindLeaderReply)Await.result(future, duration)).getLeaderActor();
71 if (maybeLeader.isPresent()) {
74 } catch (Exception e) {
75 LOG.error("FindLeader failed", e);
78 Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
81 Assert.fail("Leader not found for actorRef " + actorRef.path());