Fix checkstyle
[bgpcep.git] / bgp / rib-impl / src / main / java / org / opendaylight / protocol / bgp / rib / impl / protocol / BGPProtocolSessionPromise.java
index b017962eeaa9237ced8d02352d66ceb88a1d2846..e59e87e696a5d66b818ee19bd6d80bdf241d487d 100644 (file)
  */
 package org.opendaylight.protocol.bgp.rib.impl.protocol;
 
-import com.google.common.base.Preconditions;
+import static com.google.common.base.Preconditions.checkState;
+import static java.util.Objects.requireNonNull;
+
 import io.netty.bootstrap.Bootstrap;
 import io.netty.channel.ChannelFuture;
 import io.netty.channel.ChannelFutureListener;
 import io.netty.channel.ChannelOption;
+import io.netty.channel.EventLoop;
 import io.netty.util.concurrent.DefaultPromise;
-import io.netty.util.concurrent.Future;
-import io.netty.util.concurrent.FutureListener;
 import io.netty.util.concurrent.GlobalEventExecutor;
 import io.netty.util.concurrent.Promise;
 import java.net.InetSocketAddress;
-import javax.annotation.concurrent.GuardedBy;
+import java.util.concurrent.TimeUnit;
+import org.checkerframework.checker.lock.qual.GuardedBy;
+import org.eclipse.jdt.annotation.NonNull;
+import org.opendaylight.protocol.bgp.rib.impl.StrictBGPPeerRegistry;
+import org.opendaylight.protocol.bgp.rib.impl.spi.BGPPeerRegistry;
+import org.opendaylight.protocol.bgp.rib.impl.spi.PeerRegistrySessionListener;
 import org.opendaylight.protocol.bgp.rib.spi.BGPSession;
-import org.opendaylight.protocol.framework.ReconnectStrategy;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddressNoZone;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-public class BGPProtocolSessionPromise<S extends BGPSession> extends DefaultPromise<S> {
+public final class BGPProtocolSessionPromise<S extends BGPSession> extends DefaultPromise<S> {
     private static final Logger LOG = LoggerFactory.getLogger(BGPProtocolSessionPromise.class);
-    private final ReconnectStrategy strategy;
+    private static final int CONNECT_TIMEOUT = 5000;
+    private final int retryTimer;
     private final Bootstrap bootstrap;
-
+    @GuardedBy("this")
+    private final AutoCloseable listenerRegistration;
+    @GuardedBy("this")
     private InetSocketAddress address;
     @GuardedBy("this")
-    private Future<?> pending;
+    private ChannelFuture pending;
+    @GuardedBy("this")
+    private boolean peerSessionPresent;
+    @GuardedBy("this")
+    private boolean connectSkipped;
+
 
-    public BGPProtocolSessionPromise(InetSocketAddress address, ReconnectStrategy strategy, Bootstrap bootstrap) {
+    public BGPProtocolSessionPromise(final @NonNull InetSocketAddress remoteAddress, final int retryTimer,
+            final @NonNull Bootstrap bootstrap, final @NonNull BGPPeerRegistry peerRegistry) {
         super(GlobalEventExecutor.INSTANCE);
-        this.strategy = Preconditions.checkNotNull(strategy);
-        this.address = Preconditions.checkNotNull(address);
-        this.bootstrap = Preconditions.checkNotNull(bootstrap);
+        address = requireNonNull(remoteAddress);
+        this.retryTimer = retryTimer;
+        this.bootstrap = requireNonNull(bootstrap);
+        listenerRegistration = requireNonNull(peerRegistry).registerPeerSessionListener(
+                new PeerRegistrySessionListenerImpl(StrictBGPPeerRegistry.getIpAddress(address)));
     }
 
+    @SuppressWarnings("checkstyle:illegalCatch")
     public synchronized void connect() {
-        final BGPProtocolSessionPromise lock = this;
+        if (peerSessionPresent) {
+            LOG.debug("Connection to {} already exists", address);
+            connectSkipped = true;
+            return;
+        }
+
+        connectSkipped = false;
 
+        final BGPProtocolSessionPromise<?> lock = this;
         try {
-            int timeout = this.strategy.getConnectTimeout();
-            LOG.debug("Promise {} attempting connect for {}ms", lock, Integer.valueOf(timeout));
-            if (this.address.isUnresolved()) {
-                this.address = new InetSocketAddress(this.address.getHostName(), this.address.getPort());
+            LOG.debug("Promise {} attempting connect for {}ms", lock, CONNECT_TIMEOUT);
+            if (address.isUnresolved()) {
+                address = new InetSocketAddress(address.getHostName(), address.getPort());
             }
 
-            this.bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, timeout);
-            final ChannelFuture connectFuture = this.bootstrap.connect(this.address);
-            connectFuture.addListener(new BGPProtocolSessionPromise.BootstrapConnectListener(lock));
-            this.pending = connectFuture;
-        } catch (Exception e) {
-            LOG.info("Failed to connect to {}", this.address, e);
-            this.setFailure(e);
+            bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, CONNECT_TIMEOUT);
+            bootstrap.remoteAddress(address);
+            final ChannelFuture connectFuture = bootstrap.connect();
+            connectFuture.addListener(new BootstrapConnectListener());
+            pending = connectFuture;
+        } catch (final Exception e) {
+            LOG.warn("Failed to connect to {}", address, e);
+            setFailure(e);
         }
+    }
+
+    synchronized void reconnect() {
+        if (retryTimer == 0) {
+            LOG.debug("Retry timer value is 0. Reconnection will not be attempted");
+            setFailure(pending.cause());
+            return;
+        }
+
+        final EventLoop loop = pending.channel().eventLoop();
+        loop.schedule(() -> {
+            synchronized (BGPProtocolSessionPromise.this) {
+                if (BGPProtocolSessionPromise.this.peerSessionPresent) {
+                    LOG.debug("Connection to {} already exists", BGPProtocolSessionPromise.this.address);
+                    BGPProtocolSessionPromise.this.connectSkipped = true;
+                    return;
+                }
 
+                BGPProtocolSessionPromise.this.connectSkipped = false;
+                LOG.debug("Attempting to connect to {}", BGPProtocolSessionPromise.this.address);
+                final ChannelFuture reconnectFuture = BGPProtocolSessionPromise.this.bootstrap.connect();
+                reconnectFuture.addListener(new BootstrapConnectListener());
+                BGPProtocolSessionPromise.this.pending = reconnectFuture;
+            }
+        }, retryTimer, TimeUnit.SECONDS);
+        LOG.debug("Next reconnection attempt in {}s", retryTimer);
     }
 
     @Override
     public synchronized boolean cancel(final boolean mayInterruptIfRunning) {
+        closePeerSessionListener();
         if (super.cancel(mayInterruptIfRunning)) {
-            this.pending.cancel(mayInterruptIfRunning);
+            requireNonNull(pending);
+            pending.cancel(mayInterruptIfRunning);
             return true;
-        } else {
-            return false;
+        }
+
+        return false;
+    }
+
+    @SuppressWarnings("checkstyle:illegalCatch")
+    private synchronized void closePeerSessionListener() {
+        try {
+            listenerRegistration.close();
+        } catch (final Exception e) {
+            LOG.debug("Exception encountered while closing peer registry session listener registration", e);
         }
     }
 
     @Override
     public synchronized Promise<S> setSuccess(final S result) {
         LOG.debug("Promise {} completed", this);
-        this.strategy.reconnectSuccessful();
         return super.setSuccess(result);
     }
 
-    private class BootstrapConnectListener implements ChannelFutureListener {
-        private final Object lock;
-
-        public BootstrapConnectListener(final Object lock) {
-            this.lock = lock;
-        }
-
+    private final class BootstrapConnectListener implements ChannelFutureListener {
         @Override
         public void operationComplete(final ChannelFuture channelFuture) throws Exception {
-            synchronized (this.lock) {
-                BGPProtocolSessionPromise.LOG.debug("Promise {} connection resolved", this.lock);
-                Preconditions.checkState(BGPProtocolSessionPromise.this.pending.equals(channelFuture));
-                if (BGPProtocolSessionPromise.this.isCancelled()) {
+            synchronized (BGPProtocolSessionPromise.this) {
+                LOG.debug("Promise {} connection resolved", BGPProtocolSessionPromise.this);
+                checkState(BGPProtocolSessionPromise.this.pending.equals(channelFuture), "Unexpected promise %s",
+                    channelFuture);
+                if (isCancelled()) {
                     if (channelFuture.isSuccess()) {
-                        BGPProtocolSessionPromise.LOG.debug("Closing channel for cancelled promise {}", this.lock);
+                        LOG.debug("Closing channel for cancelled promise {}", BGPProtocolSessionPromise.this);
                         channelFuture.channel().close();
                     }
-
                 } else if (channelFuture.isSuccess()) {
-                    BGPProtocolSessionPromise.LOG.debug("Promise {} connection successful", this.lock);
+                    LOG.debug("Promise {} connection successful", BGPProtocolSessionPromise.this);
                 } else {
-                    BGPProtocolSessionPromise.LOG.debug("Attempt to connect to {} failed", BGPProtocolSessionPromise.this.address, channelFuture.cause());
-                    final Future reconnectFuture = BGPProtocolSessionPromise.this.strategy.scheduleReconnect(channelFuture.cause());
-                    reconnectFuture.addListener(new BGPProtocolSessionPromise.BootstrapConnectListener.ReconnectingStrategyListener());
-                    BGPProtocolSessionPromise.this.pending = reconnectFuture;
+                    LOG.warn("Attempt to connect to {} failed", BGPProtocolSessionPromise.this.address,
+                        channelFuture.cause());
+                    BGPProtocolSessionPromise.this.reconnect();
                 }
             }
         }
+    }
+
+    private class PeerRegistrySessionListenerImpl implements PeerRegistrySessionListener {
+        private final IpAddressNoZone peerAddress;
+
+        PeerRegistrySessionListenerImpl(final IpAddressNoZone peerAddress) {
+            this.peerAddress = peerAddress;
+        }
 
-        private final class ReconnectingStrategyListener implements FutureListener<Void> {
-            private ReconnectingStrategyListener() {
+        @Override
+        public void onSessionCreated(final IpAddressNoZone ip) {
+            if (ip.equals(peerAddress)) {
+                LOG.debug("Callback for session creation with peer {} received", ip);
+                synchronized (BGPProtocolSessionPromise.this) {
+                    BGPProtocolSessionPromise.this.peerSessionPresent = true;
+                }
             }
+        }
 
-            @Override
-            public void operationComplete(final Future<Void> sessionFuture) {
-                synchronized (BootstrapConnectListener.this.lock) {
-                    Preconditions.checkState(BGPProtocolSessionPromise.this.pending.equals(sessionFuture));
-                    if (!BGPProtocolSessionPromise.this.isCancelled()) {
-                        if (sessionFuture.isSuccess()) {
-                            BGPProtocolSessionPromise.this.connect();
-                        } else {
-                            BGPProtocolSessionPromise.this.setFailure(sessionFuture.cause());
-                        }
+        @Override
+        public void onSessionRemoved(final IpAddressNoZone ip) {
+            if (ip.equals(peerAddress)) {
+                LOG.debug("Callback for session removal with peer {} received", ip);
+                synchronized (BGPProtocolSessionPromise.this) {
+                    BGPProtocolSessionPromise.this.peerSessionPresent = false;
+                    if (BGPProtocolSessionPromise.this.connectSkipped) {
+                        BGPProtocolSessionPromise.this.connect();
                     }
-
                 }
             }
         }
     }
-}
\ No newline at end of file
+}