2 * Copyright (c) 2016 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.protocol.bgp.rib.impl;
10 import com.google.common.base.Stopwatch;
11 import com.google.common.util.concurrent.Uninterruptibles;
12 import java.util.concurrent.TimeUnit;
13 import java.util.function.Function;
14 import org.junit.Assert;
15 import org.opendaylight.protocol.bgp.rib.spi.State;
16 import org.opendaylight.protocol.bgp.rib.spi.state.BGPGracelfulRestartState;
17 import org.opendaylight.protocol.bgp.rib.spi.state.BGPSessionState;
19 public final class CheckUtil {
20 private static final int SLEEP_FOR_MILLIS = 50;
21 private static final int TIMEOUT_SECONDS = 10;
27 public static void checkIdleState(final SimpleSessionListener sessionListener) {
28 checkInLoop(State.IDLE, sessionListener, SimpleSessionListener::getState, SLEEP_FOR_MILLIS, TIMEOUT_SECONDS);
31 public static void checkIdleState(final BGPPeer bgpPeer) {
32 checkInLoop(State.IDLE, bgpPeer, peer -> {
33 synchronized (bgpPeer) {
34 final BGPSessionState state = peer.getBGPSessionState();
35 return state == null ? State.IDLE : state.getSessionState();
37 }, SLEEP_FOR_MILLIS, TIMEOUT_SECONDS);
40 public static void checkUpState(final SimpleSessionListener sessionListener) {
41 checkInLoop(State.UP, sessionListener, SimpleSessionListener::getState, SLEEP_FOR_MILLIS, TIMEOUT_SECONDS);
44 public static void checkUpState(final BGPPeer bgpPeer) {
45 checkInLoop(State.UP, bgpPeer, peer -> {
46 synchronized (bgpPeer) {
47 final BGPSessionState state = peer.getBGPSessionState();
48 return state == null ? State.IDLE : state.getSessionState();
50 }, SLEEP_FOR_MILLIS, TIMEOUT_SECONDS);
53 private static <T> void checkInLoop(final State state, final T object, final Function<T, State> function,
54 final int sleepForMillis, final int timeoutSeconds) {
55 final long timeoutNanos = TimeUnit.SECONDS.toNanos(timeoutSeconds);
56 final Stopwatch sw = Stopwatch.createStarted();
57 while (sw.elapsed(TimeUnit.NANOSECONDS) <= timeoutNanos) {
58 if (state != function.apply(object)) {
59 Uninterruptibles.sleepUninterruptibly(sleepForMillis, TimeUnit.MILLISECONDS);
67 public static void checkStateIsNotRestarting(final BGPPeer peer, final int restartTimeSeconds) {
68 final long restartTimeNanos = TimeUnit.SECONDS.toNanos(restartTimeSeconds + 1);
69 final Stopwatch sw = Stopwatch.createStarted();
70 while (sw.elapsed(TimeUnit.NANOSECONDS) <= restartTimeNanos) {
71 final BGPGracelfulRestartState restartState = peer.getPeerState().getBGPGracelfulRestart();
72 if (restartState.isPeerRestarting() || restartState.isLocalRestarting()) {
73 Uninterruptibles.sleepUninterruptibly(SLEEP_FOR_MILLIS, TimeUnit.MILLISECONDS);