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