BUG-5790: BGP Test tool
[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.socket.SocketChannel;
21 import io.netty.channel.socket.nio.NioServerSocketChannel;
22 import io.netty.channel.socket.nio.NioSocketChannel;
23 import io.netty.util.concurrent.DefaultPromise;
24 import io.netty.util.concurrent.Future;
25 import io.netty.util.concurrent.GlobalEventExecutor;
26 import io.netty.util.concurrent.Promise;
27 import java.net.InetSocketAddress;
28 import org.opendaylight.protocol.bgp.parser.spi.MessageRegistry;
29 import org.opendaylight.protocol.bgp.rib.impl.protocol.BGPProtocolSessionPromise;
30 import org.opendaylight.protocol.bgp.rib.impl.protocol.BGPReconnectPromise;
31 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPDispatcher;
32 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPPeerRegistry;
33 import org.opendaylight.protocol.bgp.rib.impl.spi.ChannelPipelineInitializer;
34 import org.opendaylight.protocol.bgp.rib.spi.BGPSession;
35 import org.opendaylight.protocol.bgp.rib.spi.BGPSessionNegotiatorFactory;
36 import org.opendaylight.tcpmd5.api.KeyMapping;
37 import org.opendaylight.tcpmd5.netty.MD5ChannelFactory;
38 import org.opendaylight.tcpmd5.netty.MD5ChannelOption;
39 import org.opendaylight.tcpmd5.netty.MD5ServerChannelFactory;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42
43 /**
44  * Implementation of BGPDispatcher.
45  */
46 public class BGPDispatcherImpl implements BGPDispatcher, AutoCloseable {
47     private static final Logger LOG = LoggerFactory.getLogger(BGPDispatcherImpl.class);
48     private static final int SOCKET_BACKLOG_SIZE = 128;
49     private static final int HIGH_WATER_MARK = 256 * 1024;
50     private static final int LOW_WATER_MARK = 128 * 1024;
51
52     private final MD5ServerChannelFactory<?> serverChannelFactory;
53     private final MD5ChannelFactory<?> channelFactory;
54     private final BGPHandlerFactory handlerFactory;
55     private final EventLoopGroup bossGroup;
56     private final EventLoopGroup workerGroup;
57     private Optional<KeyMapping> keys;
58
59     public BGPDispatcherImpl(final MessageRegistry messageRegistry, final EventLoopGroup bossGroup, final EventLoopGroup workerGroup) {
60         this(messageRegistry, bossGroup, workerGroup, null, null);
61     }
62
63     public BGPDispatcherImpl(final MessageRegistry messageRegistry, final EventLoopGroup bossGroup, final EventLoopGroup workerGroup,
64         final MD5ChannelFactory<?> cf, final MD5ServerChannelFactory<?> scf) {
65         this.bossGroup = Preconditions.checkNotNull(bossGroup);
66         this.workerGroup = Preconditions.checkNotNull(workerGroup);
67         this.handlerFactory = new BGPHandlerFactory(messageRegistry);
68         this.channelFactory = cf;
69         this.serverChannelFactory = scf;
70         this.keys = Optional.absent();
71     }
72
73     @Override
74     public synchronized Future<BGPSessionImpl> createClient(final InetSocketAddress remoteAddress, final BGPPeerRegistry listener, final int retryTimer) {
75         return createClient(remoteAddress, listener, retryTimer, createClientBootStrap());
76     }
77
78     private Future<BGPSessionImpl> createClient(final InetSocketAddress remoteAddress, final BGPPeerRegistry listener, final int retryTimer,
79         final Bootstrap clientBootStrap) {
80         final BGPClientSessionNegotiatorFactory snf = new BGPClientSessionNegotiatorFactory(listener);
81         final ChannelPipelineInitializer initializer = BGPChannel.createChannelPipelineInitializer(BGPDispatcherImpl.this.handlerFactory, snf);
82
83         final BGPProtocolSessionPromise sessionPromise = new BGPProtocolSessionPromise(remoteAddress, retryTimer, clientBootStrap);
84         clientBootStrap.handler(BGPChannel.createClientChannelHandler(initializer, sessionPromise));
85         sessionPromise.connect();
86         LOG.debug("Client created.");
87         return sessionPromise;
88     }
89
90     public Future<BGPSessionImpl> createClient(final InetSocketAddress localAddress, final InetSocketAddress remoteAddress,
91         final StrictBGPPeerRegistry strictBGPPeerRegistry, final int retryTimer) {
92         final Bootstrap clientBootStrap = createClientBootStrap();
93         clientBootStrap.localAddress(localAddress);
94         return createClient(remoteAddress, strictBGPPeerRegistry, retryTimer, clientBootStrap);
95     }
96
97     protected Bootstrap createClientBootStrap() {
98         return createClientBootStrap(this.keys, this.channelFactory, this.workerGroup);
99     }
100
101     private static Bootstrap createClientBootStrap(final Optional<KeyMapping> keys, final MD5ChannelFactory<?> channelFactory, final EventLoopGroup
102         workerGroup) {
103         final Bootstrap bootstrap = new Bootstrap();
104         if (keys.isPresent()) {
105             if (channelFactory == null) {
106                 throw new UnsupportedOperationException("No key access instance available, cannot use key mapping");
107             }
108             bootstrap.channelFactory(channelFactory);
109             bootstrap.option(MD5ChannelOption.TCP_MD5SIG, keys.get());
110         } else {
111             bootstrap.channel(NioSocketChannel.class);
112         }
113
114         // Make sure we are doing round-robin processing
115         bootstrap.option(ChannelOption.MAX_MESSAGES_PER_READ, 1);
116         bootstrap.option(ChannelOption.SO_KEEPALIVE, Boolean.TRUE);
117         bootstrap.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, HIGH_WATER_MARK);
118         bootstrap.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, LOW_WATER_MARK);
119
120         if (bootstrap.group() == null) {
121             bootstrap.group(workerGroup);
122         }
123
124         return bootstrap;
125     }
126
127     @Override
128     public void close() {
129     }
130
131     @Override
132     public synchronized Future<Void> createReconnectingClient(final InetSocketAddress remoteAddress, final BGPPeerRegistry peerRegistry,
133             final int retryTimer, final Optional<KeyMapping> keys) {
134         final BGPClientSessionNegotiatorFactory snf = new BGPClientSessionNegotiatorFactory(peerRegistry);
135         this.keys = keys;
136         final Bootstrap bootstrap = createClientBootStrap();
137         final BGPReconnectPromise reconnectPromise = new BGPReconnectPromise(GlobalEventExecutor.INSTANCE, remoteAddress,
138             retryTimer, bootstrap, BGPChannel.createChannelPipelineInitializer(BGPDispatcherImpl.this.handlerFactory, snf));
139         reconnectPromise.connect();
140         this.keys = Optional.absent();
141         return reconnectPromise;
142     }
143
144     @Override
145     public ChannelFuture createServer(final BGPPeerRegistry registry, final InetSocketAddress localAddress) {
146         final BGPServerSessionNegotiatorFactory snf = new BGPServerSessionNegotiatorFactory(registry);
147         final ChannelPipelineInitializer initializer = BGPChannel.createChannelPipelineInitializer(BGPDispatcherImpl.this.handlerFactory, snf);
148         final ServerBootstrap serverBootstrap = createServerBootstrap(initializer, this.keys, serverChannelFactory, this.bossGroup, this.workerGroup);
149         final ChannelFuture channelFuture = serverBootstrap.bind(localAddress);
150         LOG.debug("Initiated server {} at {}.", channelFuture, localAddress);
151         return channelFuture;
152     }
153
154     public static ServerBootstrap createServerBootstrap(final ChannelPipelineInitializer initializer, final Optional<KeyMapping> keys,
155         final MD5ServerChannelFactory<?> serverChannelFactory, final EventLoopGroup bossGroup, final EventLoopGroup workerGroup) {
156         final ServerBootstrap serverBootstrap = new ServerBootstrap();
157         final ChannelHandler serverChannelHandler = BGPChannel.createServerChannelHandler(initializer);
158         serverBootstrap.childHandler(serverChannelHandler);
159
160         serverBootstrap.option(ChannelOption.SO_BACKLOG, Integer.valueOf(SOCKET_BACKLOG_SIZE));
161         serverBootstrap.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
162         serverBootstrap.childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, HIGH_WATER_MARK);
163         serverBootstrap.childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, LOW_WATER_MARK);
164         if (keys.isPresent()) {
165             if (serverChannelFactory == null) {
166                 throw new UnsupportedOperationException("No key access instance available, cannot use key mapping");
167             }
168             serverBootstrap.channelFactory(serverChannelFactory);
169             serverBootstrap.option(MD5ChannelOption.TCP_MD5SIG, keys.get());
170         } else {
171             serverBootstrap.channel(NioServerSocketChannel.class);
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 }