BUG-2873 : Remove dependency protocol-framework on BGP
[bgpcep.git] / bgp / rib-impl / src / main / java / org / opendaylight / protocol / bgp / rib / impl / BGPDispatcherImpl.java
index 7d924de27cf7fbcbb9e9b1100cbc9fcd9c8d6bdf..baa2073ead0d5d347043cb4a4ccd436288d46f75 100644 (file)
@@ -7,21 +7,31 @@
  */
 package org.opendaylight.protocol.bgp.rib.impl;
 
+import com.google.common.base.Preconditions;
 import io.netty.bootstrap.Bootstrap;
 import io.netty.bootstrap.ServerBootstrap;
+import io.netty.buffer.PooledByteBufAllocator;
 import io.netty.channel.ChannelFuture;
+import io.netty.channel.ChannelHandler;
+import io.netty.channel.ChannelInitializer;
 import io.netty.channel.ChannelOption;
 import io.netty.channel.EventLoopGroup;
 import io.netty.channel.socket.SocketChannel;
+import io.netty.channel.socket.nio.NioServerSocketChannel;
+import io.netty.channel.socket.nio.NioSocketChannel;
+import io.netty.util.concurrent.DefaultPromise;
+import io.netty.util.concurrent.EventExecutor;
 import io.netty.util.concurrent.Future;
+import io.netty.util.concurrent.GlobalEventExecutor;
 import io.netty.util.concurrent.Promise;
 import java.net.InetSocketAddress;
 import org.opendaylight.protocol.bgp.parser.spi.MessageRegistry;
+import org.opendaylight.protocol.bgp.rib.impl.protocol.BGPProtocolSessionPromise;
+import org.opendaylight.protocol.bgp.rib.impl.protocol.BGPReconnectPromise;
 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPDispatcher;
 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPPeerRegistry;
 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPSessionValidator;
-import org.opendaylight.protocol.bgp.rib.spi.BGPSessionListener;
-import org.opendaylight.protocol.framework.AbstractDispatcher;
+import org.opendaylight.protocol.bgp.rib.spi.BGPSessionNegotiatorFactory;
 import org.opendaylight.protocol.framework.ReconnectStrategy;
 import org.opendaylight.protocol.framework.ReconnectStrategyFactory;
 import org.opendaylight.tcpmd5.api.KeyMapping;
@@ -29,14 +39,20 @@ import org.opendaylight.tcpmd5.netty.MD5ChannelFactory;
 import org.opendaylight.tcpmd5.netty.MD5ChannelOption;
 import org.opendaylight.tcpmd5.netty.MD5ServerChannelFactory;
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.AsNumber;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 /**
  * Implementation of BGPDispatcher.
  */
-public final class BGPDispatcherImpl extends AbstractDispatcher<BGPSessionImpl, BGPSessionListener> implements BGPDispatcher, AutoCloseable {
+public class BGPDispatcherImpl implements BGPDispatcher, AutoCloseable {
+    private static final Logger LOG = LoggerFactory.getLogger(BGPDispatcherImpl.class);
     private final MD5ServerChannelFactory<?> scf;
     private final MD5ChannelFactory<?> cf;
     private final BGPHandlerFactory hf;
+    private final EventLoopGroup bossGroup;
+    private final EventLoopGroup workerGroup;
+    private final EventExecutor executor;
     private KeyMapping keys;
 
     public BGPDispatcherImpl(final MessageRegistry messageRegistry, final EventLoopGroup bossGroup, final EventLoopGroup workerGroup) {
@@ -44,82 +60,78 @@ public final class BGPDispatcherImpl extends AbstractDispatcher<BGPSessionImpl,
     }
 
     public BGPDispatcherImpl(final MessageRegistry messageRegistry, final EventLoopGroup bossGroup, final EventLoopGroup workerGroup, final MD5ChannelFactory<?> cf, final MD5ServerChannelFactory<?> scf) {
-        super(bossGroup, workerGroup);
+        this.bossGroup = Preconditions.checkNotNull(bossGroup);
+        this.workerGroup = Preconditions.checkNotNull(workerGroup);
+        this.executor = Preconditions.checkNotNull(GlobalEventExecutor.INSTANCE);
         this.hf = new BGPHandlerFactory(messageRegistry);
         this.cf = cf;
         this.scf = scf;
+        this.keys = null;
     }
 
     @Override
     public synchronized Future<BGPSessionImpl> createClient(final InetSocketAddress address,
-        final AsNumber remoteAs, final BGPPeerRegistry listener, final ReconnectStrategy strategy) {
+                                                            final AsNumber remoteAs, final BGPPeerRegistry listener, final ReconnectStrategy strategy) {
         final BGPClientSessionNegotiatorFactory snf = new BGPClientSessionNegotiatorFactory(remoteAs, listener);
-        return super.createClient(address, strategy, new PipelineInitializer<BGPSessionImpl>() {
-            @Override
-            public void initializeChannel(final SocketChannel ch, final Promise<BGPSessionImpl> promise) {
-                ch.pipeline().addLast(BGPDispatcherImpl.this.hf.getDecoders());
-                ch.pipeline().addLast("negotiator", snf.getSessionNegotiator(null, ch, promise));
-                ch.pipeline().addLast(BGPDispatcherImpl.this.hf.getEncoders());
-            }
-        });
-    }
-
-    @Override
-    public Future<Void> createReconnectingClient(final InetSocketAddress address,
-        final AsNumber remoteAs, final BGPPeerRegistry listener, final ReconnectStrategyFactory connectStrategyFactory,
-        final ReconnectStrategyFactory reestablishStrategyFactory) {
-        return this.createReconnectingClient(address, remoteAs, listener, connectStrategyFactory, reestablishStrategyFactory,
-            null);
+        final ChannelPipelineInitializer initializer = BGPChannel.createChannelPipelineInitializer
+            (BGPDispatcherImpl.this.hf.getDecoders(), snf, BGPDispatcherImpl.this.hf.getEncoders());
+
+        final Bootstrap b = new Bootstrap();
+        final BGPProtocolSessionPromise p = new BGPProtocolSessionPromise(this.executor, address, strategy, b);
+        b.option(ChannelOption.SO_KEEPALIVE, Boolean.valueOf(true));
+        b.handler(BGPChannel.createChannelInitializer(initializer, p));
+        this.customizeBootstrap(b);
+        this.setWorkerGroup(b);
+        p.connect();
+        LOG.debug("Client created.");
+        return p;
     }
 
     @Override
     public void close() {
+        try {
+            this.workerGroup.shutdownGracefully();
+        } finally {
+            this.bossGroup.shutdownGracefully();
+        }
     }
 
     @Override
     public synchronized Future<Void> createReconnectingClient(final InetSocketAddress address,
-        final AsNumber remoteAs, final BGPPeerRegistry peerRegistry, final ReconnectStrategyFactory connectStrategyFactory,
-        final ReconnectStrategyFactory reestablishStrategyFactory, final KeyMapping keys) {
+                                                              final AsNumber remoteAs, final BGPPeerRegistry peerRegistry, final ReconnectStrategyFactory connectStrategyFactory,
+                                                              final KeyMapping keys) {
         final BGPClientSessionNegotiatorFactory snf = new BGPClientSessionNegotiatorFactory(remoteAs, peerRegistry);
-
         this.keys = keys;
-        final Future<Void> ret = super.createReconnectingClient(address, connectStrategyFactory, reestablishStrategyFactory.createReconnectStrategy(), new PipelineInitializer<BGPSessionImpl>() {
-            @Override
-            public void initializeChannel(final SocketChannel ch, final Promise<BGPSessionImpl> promise) {
-                ch.pipeline().addLast(BGPDispatcherImpl.this.hf.getDecoders());
-                ch.pipeline().addLast("negotiator", snf.getSessionNegotiator(null, ch, promise));
-                ch.pipeline().addLast(BGPDispatcherImpl.this.hf.getEncoders());
-            }
-        });
+
+        final Bootstrap b = new Bootstrap();
+        final BGPReconnectPromise p = new BGPReconnectPromise(GlobalEventExecutor.INSTANCE, address,
+            connectStrategyFactory, b, BGPChannel.createChannelPipelineInitializer(BGPDispatcherImpl.this.hf.getDecoders(), snf, BGPDispatcherImpl.this.hf.getEncoders()));
+        b.option(ChannelOption.SO_KEEPALIVE, Boolean.valueOf(true));
+        this.customizeBootstrap(b);
+        this.setWorkerGroup(b);
+        p.connect();
+
         this.keys = null;
 
-        return ret;
+        return p;
     }
 
     @Override
     public ChannelFuture createServer(final BGPPeerRegistry registry, final InetSocketAddress address, final BGPSessionValidator sessionValidator) {
-        return this.createServer(registry, address, sessionValidator, null);
-    }
-
-    @Override
-    public ChannelFuture createServer(final BGPPeerRegistry registry, final InetSocketAddress address, final BGPSessionValidator sessionValidator, final KeyMapping keys) {
         final BGPServerSessionNegotiatorFactory snf = new BGPServerSessionNegotiatorFactory(sessionValidator, registry);
-
-        this.keys = keys;
-        final ChannelFuture ret = super.createServer(address, new PipelineInitializer<BGPSessionImpl>() {
-            @Override
-            public void initializeChannel(final SocketChannel ch, final Promise<BGPSessionImpl> promise) {
-                ch.pipeline().addLast(BGPDispatcherImpl.this.hf.getDecoders());
-                ch.pipeline().addLast("negotiator", snf.getSessionNegotiator(null, ch, promise));
-                ch.pipeline().addLast(BGPDispatcherImpl.this.hf.getEncoders());
-            }
-        });
-        this.keys = null;
-
-        return ret;
+        final ChannelPipelineInitializer initializer = BGPChannel.createChannelPipelineInitializer
+            (BGPDispatcherImpl.this.hf.getDecoders(), snf, BGPDispatcherImpl.this.hf.getEncoders());
+        final ServerBootstrap b = new ServerBootstrap();
+        b.childHandler(BGPChannel.createChannelInitializer(initializer, new DefaultPromise(BGPDispatcherImpl.this.executor)));
+        b.option(ChannelOption.SO_BACKLOG, Integer.valueOf(128));
+        b.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
+        this.customizeBootstrap(b);
+
+        final ChannelFuture f = b.bind(address);
+        LOG.debug("Initiated server {} at {}.", f, address);
+        return f;
     }
 
-    @Override
     protected void customizeBootstrap(final Bootstrap b) {
         if (this.keys != null && !this.keys.isEmpty()) {
             if (this.cf == null) {
@@ -127,22 +139,79 @@ public final class BGPDispatcherImpl extends AbstractDispatcher<BGPSessionImpl,
             }
             b.channelFactory(this.cf);
             b.option(MD5ChannelOption.TCP_MD5SIG, this.keys);
-            // Make sure we are doing round-robin processing
-            b.option(ChannelOption.MAX_MESSAGES_PER_READ, 1);
         }
+
+        // Make sure we are doing round-robin processing
+        b.option(ChannelOption.MAX_MESSAGES_PER_READ, 1);
     }
 
-    @Override
-    protected void customizeBootstrap(final ServerBootstrap b) {
+    private void customizeBootstrap(final ServerBootstrap b) {
         if (this.keys != null && !this.keys.isEmpty()) {
             if (this.scf == null) {
                 throw new UnsupportedOperationException("No key access instance available, cannot use key mapping");
             }
             b.channelFactory(this.scf);
             b.option(MD5ChannelOption.TCP_MD5SIG, this.keys);
-            // Make sure we are doing round-robin processing
-            b.childOption(ChannelOption.MAX_MESSAGES_PER_READ, 1);
         }
+
+        // Make sure we are doing round-robin processing
+        b.option(ChannelOption.MAX_MESSAGES_PER_READ, 1);
+
+        if (b.group() == null) {
+            b.group(this.bossGroup, this.workerGroup);
+        }
+
+        try {
+            b.channel(NioServerSocketChannel.class);
+        } catch (IllegalStateException e) {
+            LOG.trace("Not overriding channelFactory on bootstrap {}", b, e);
+        }
+    }
+
+    private void setWorkerGroup(final Bootstrap b) {
+        if (b.group() == null) {
+            b.group(this.workerGroup);
+        }
+        try {
+            b.channel(NioSocketChannel.class);
+        } catch (IllegalStateException e) {
+            LOG.trace("Not overriding channelFactory on bootstrap {}", b, e);
+        }
+    }
+
+    public interface ChannelPipelineInitializer {
+        void initializeChannel(SocketChannel socketChannel, Promise<BGPSessionImpl> promise);
     }
 
+    public static class BGPChannel {
+        private static final String NEGOTIATOR = "negotiator";
+
+        private BGPChannel() {
+
+        }
+
+        public static <T extends BGPSessionNegotiatorFactory> ChannelPipelineInitializer createChannelPipelineInitializer(final ChannelHandler[] channelDecoder,
+                                                                                                                          final T snf,
+                                                                                                                          final ChannelHandler[] channelEncoder) {
+            return new ChannelPipelineInitializer() {
+                @Override
+                public void initializeChannel(final SocketChannel ch, final Promise<BGPSessionImpl> promise) {
+                    ch.pipeline().addLast(channelDecoder);
+                    ch.pipeline().addLast(NEGOTIATOR, snf.getSessionNegotiator(ch, promise));
+                    ch.pipeline().addLast(channelEncoder);
+                }
+            };
+        }
+
+        public static ChannelHandler createChannelInitializer(final ChannelPipelineInitializer initializer, final Promise<BGPSessionImpl> promise) {
+            return new ChannelInitializer<SocketChannel>() {
+                @Override
+                protected void initChannel(SocketChannel ch) {
+                    initializer.initializeChannel(ch, promise);
+                }
+            };
+        }
+    }
 }
+
+