BUG-7006: Unit-tests sometimes hangs during execution
[bgpcep.git] / bgp / rib-impl / src / main / java / org / opendaylight / protocol / bgp / rib / impl / BGPDispatcherImpl.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.protocol.bgp.rib.impl;
9
10 import com.google.common.annotations.VisibleForTesting;
11 import com.google.common.base.Optional;
12 import com.google.common.base.Preconditions;
13 import io.netty.bootstrap.Bootstrap;
14 import io.netty.bootstrap.ServerBootstrap;
15 import io.netty.buffer.PooledByteBufAllocator;
16 import io.netty.channel.ChannelFuture;
17 import io.netty.channel.ChannelHandler;
18 import io.netty.channel.ChannelInitializer;
19 import io.netty.channel.ChannelOption;
20 import io.netty.channel.EventLoopGroup;
21 import io.netty.channel.epoll.Epoll;
22 import io.netty.channel.epoll.EpollChannelOption;
23 import io.netty.channel.epoll.EpollEventLoopGroup;
24 import io.netty.channel.epoll.EpollMode;
25 import io.netty.channel.epoll.EpollServerSocketChannel;
26 import io.netty.channel.epoll.EpollSocketChannel;
27 import io.netty.channel.socket.SocketChannel;
28 import io.netty.channel.socket.nio.NioServerSocketChannel;
29 import io.netty.channel.socket.nio.NioSocketChannel;
30 import io.netty.util.concurrent.DefaultPromise;
31 import io.netty.util.concurrent.Future;
32 import io.netty.util.concurrent.GlobalEventExecutor;
33 import io.netty.util.concurrent.Promise;
34 import java.net.InetSocketAddress;
35 import org.opendaylight.protocol.bgp.parser.spi.MessageRegistry;
36 import org.opendaylight.protocol.bgp.rib.impl.protocol.BGPProtocolSessionPromise;
37 import org.opendaylight.protocol.bgp.rib.impl.protocol.BGPReconnectPromise;
38 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPDispatcher;
39 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPPeerRegistry;
40 import org.opendaylight.protocol.bgp.rib.impl.spi.ChannelPipelineInitializer;
41 import org.opendaylight.protocol.bgp.rib.spi.BGPSession;
42 import org.opendaylight.protocol.bgp.rib.spi.BGPSessionNegotiatorFactory;
43 import org.opendaylight.protocol.concepts.KeyMapping;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46
47 /**
48  * Implementation of BGPDispatcher.
49  */
50 public class BGPDispatcherImpl implements BGPDispatcher, AutoCloseable {
51     private static final Logger LOG = LoggerFactory.getLogger(BGPDispatcherImpl.class);
52     private static final int SOCKET_BACKLOG_SIZE = 128;
53     private static final int HIGH_WATER_MARK = 256 * 1024;
54     private static final int LOW_WATER_MARK = 128 * 1024;
55
56     private final BGPHandlerFactory handlerFactory;
57     private final EventLoopGroup bossGroup;
58     private final EventLoopGroup workerGroup;
59
60     public BGPDispatcherImpl(final MessageRegistry messageRegistry, final EventLoopGroup bossGroup, final EventLoopGroup workerGroup) {
61         if (Epoll.isAvailable()) {
62             this.bossGroup = new EpollEventLoopGroup();
63             this.workerGroup = new EpollEventLoopGroup();
64         } else {
65             this.bossGroup = Preconditions.checkNotNull(bossGroup);
66             this.workerGroup = Preconditions.checkNotNull(workerGroup);
67         }
68         this.handlerFactory = new BGPHandlerFactory(messageRegistry);
69     }
70
71     @Override
72     public synchronized Future<BGPSessionImpl> createClient(final InetSocketAddress remoteAddress, final BGPPeerRegistry listener, final int retryTimer) {
73         return createClient(remoteAddress, listener, retryTimer, createClientBootStrap(Optional.absent(), false));
74     }
75
76     private synchronized Future<BGPSessionImpl> createClient(final InetSocketAddress remoteAddress, final BGPPeerRegistry listener, final int retryTimer,
77             final Bootstrap clientBootStrap) {
78         final BGPClientSessionNegotiatorFactory snf = new BGPClientSessionNegotiatorFactory(listener);
79         final ChannelPipelineInitializer initializer = BGPChannel.createChannelPipelineInitializer(BGPDispatcherImpl.this.handlerFactory, snf);
80
81         final BGPProtocolSessionPromise sessionPromise = new BGPProtocolSessionPromise(remoteAddress, retryTimer, clientBootStrap, listener);
82         clientBootStrap.handler(BGPChannel.createClientChannelHandler(initializer, sessionPromise));
83         sessionPromise.connect();
84         LOG.debug("Client created.");
85         return sessionPromise;
86     }
87
88     @VisibleForTesting
89     public synchronized Future<BGPSessionImpl> createClient(final InetSocketAddress localAddress, final InetSocketAddress remoteAddress,
90             final BGPPeerRegistry strictBGPPeerRegistry, final int retryTimer, final boolean reuseAddress) {
91         final Bootstrap clientBootStrap = createClientBootStrap(Optional.absent(), reuseAddress);
92         clientBootStrap.localAddress(localAddress);
93         return createClient(remoteAddress, strictBGPPeerRegistry, retryTimer, clientBootStrap);
94     }
95
96     private synchronized Bootstrap createClientBootStrap(final Optional<KeyMapping> keys, final boolean reuseAddress) {
97         final Bootstrap bootstrap = new Bootstrap();
98         if (Epoll.isAvailable()) {
99             bootstrap.channel(EpollSocketChannel.class);
100             bootstrap.option(EpollChannelOption.EPOLL_MODE, EpollMode.LEVEL_TRIGGERED);
101         } else {
102             bootstrap.channel(NioSocketChannel.class);
103         }
104         if (keys.isPresent()) {
105             if (Epoll.isAvailable()) {
106                 bootstrap.option(EpollChannelOption.TCP_MD5SIG, keys.get());
107             } else {
108                 throw new UnsupportedOperationException(Epoll.unavailabilityCause().getCause());
109             }
110         }
111
112         // Make sure we are doing round-robin processing
113         bootstrap.option(ChannelOption.MAX_MESSAGES_PER_READ, 1);
114         bootstrap.option(ChannelOption.SO_KEEPALIVE, Boolean.TRUE);
115         bootstrap.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, HIGH_WATER_MARK);
116         bootstrap.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, LOW_WATER_MARK);
117         bootstrap.option(ChannelOption.SO_REUSEADDR, reuseAddress);
118
119         if (bootstrap.group() == null) {
120             bootstrap.group(this.workerGroup);
121         }
122
123         return bootstrap;
124     }
125
126     @Override
127     public synchronized void close() {
128         if (Epoll.isAvailable()) {
129             this.workerGroup.shutdownGracefully().awaitUninterruptibly();
130             this.bossGroup.shutdownGracefully().awaitUninterruptibly();
131         }
132     }
133
134     @Override
135     public synchronized Future<Void> createReconnectingClient(final InetSocketAddress remoteAddress, final BGPPeerRegistry peerRegistry,
136             final int retryTimer, final Optional<KeyMapping> keys) {
137         return createReconnectingClient(remoteAddress, peerRegistry, retryTimer, keys, null, false);
138     }
139
140     @VisibleForTesting
141     protected synchronized Future<Void> createReconnectingClient(final InetSocketAddress remoteAddress, final BGPPeerRegistry peerRegistry,
142         final int retryTimer, final Optional<KeyMapping> keys, final InetSocketAddress localAddress, final boolean reuseAddress) {
143         final BGPClientSessionNegotiatorFactory snf = new BGPClientSessionNegotiatorFactory(peerRegistry);
144         final Bootstrap bootstrap = createClientBootStrap(keys, reuseAddress);
145         bootstrap.localAddress(localAddress);
146         final BGPReconnectPromise reconnectPromise = new BGPReconnectPromise(GlobalEventExecutor.INSTANCE, remoteAddress,
147             retryTimer, bootstrap, peerRegistry, BGPChannel.createChannelPipelineInitializer(BGPDispatcherImpl.this.handlerFactory, snf));
148         reconnectPromise.connect();
149         return reconnectPromise;
150     }
151
152     @Override
153     public synchronized ChannelFuture createServer(final BGPPeerRegistry registry, final InetSocketAddress serverAddress) {
154         final BGPServerSessionNegotiatorFactory snf = new BGPServerSessionNegotiatorFactory(registry);
155         final ChannelPipelineInitializer initializer = BGPChannel.createChannelPipelineInitializer(BGPDispatcherImpl.this.handlerFactory, snf);
156         final ServerBootstrap serverBootstrap = createServerBootstrap(initializer);
157         final ChannelFuture channelFuture = serverBootstrap.bind(serverAddress);
158         LOG.debug("Initiated server {} at {}.", channelFuture, serverAddress);
159         return channelFuture;
160     }
161
162     private synchronized ServerBootstrap createServerBootstrap(final ChannelPipelineInitializer initializer) {
163         final ServerBootstrap serverBootstrap = new ServerBootstrap();
164         if (Epoll.isAvailable()) {
165             serverBootstrap.channel(EpollServerSocketChannel.class);
166             serverBootstrap.childOption(EpollChannelOption.EPOLL_MODE, EpollMode.LEVEL_TRIGGERED);
167         } else {
168             serverBootstrap.channel(NioServerSocketChannel.class);
169         }
170         final ChannelHandler serverChannelHandler = BGPChannel.createServerChannelHandler(initializer);
171         serverBootstrap.childHandler(serverChannelHandler);
172
173         serverBootstrap.option(ChannelOption.SO_BACKLOG, SOCKET_BACKLOG_SIZE);
174         serverBootstrap.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
175         serverBootstrap.childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, HIGH_WATER_MARK);
176         serverBootstrap.childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, LOW_WATER_MARK);
177
178         // Make sure we are doing round-robin processing
179         serverBootstrap.option(ChannelOption.MAX_MESSAGES_PER_READ, 1);
180
181         if (serverBootstrap.group() == null) {
182             serverBootstrap.group(this.bossGroup, this.workerGroup);
183         }
184         return serverBootstrap;
185     }
186
187     private static final class BGPChannel {
188         private static final String NEGOTIATOR = "negotiator";
189
190         private BGPChannel() {
191
192         }
193
194         static <T extends BGPSessionNegotiatorFactory> ChannelPipelineInitializer
195         createChannelPipelineInitializer(final BGPHandlerFactory hf, final T snf) {
196             return (channel, promise) -> {
197                 channel.pipeline().addLast(hf.getDecoders());
198                 channel.pipeline().addLast(NEGOTIATOR, snf.getSessionNegotiator(channel, promise));
199                 channel.pipeline().addLast(hf.getEncoders());
200             };
201         }
202
203         static <S extends BGPSession> ChannelHandler createClientChannelHandler(final ChannelPipelineInitializer initializer, final Promise<S> promise) {
204             return new ChannelInitializer<SocketChannel>() {
205                 @Override
206                 protected void initChannel(final SocketChannel channel) {
207                     initializer.initializeChannel(channel, promise);
208                 }
209             };
210         }
211
212         static ChannelHandler createServerChannelHandler(final ChannelPipelineInitializer initializer) {
213             return new ChannelInitializer<SocketChannel>() {
214                 @Override
215                 protected void initChannel(final SocketChannel channel) {
216                     initializer.initializeChannel(channel, new DefaultPromise<BGPSessionImpl>(GlobalEventExecutor.INSTANCE));
217                 }
218             };
219         }
220     }
221 }