BUG-4780: New peers failed to connect after one gets connected
[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.protocol.framework.ReconnectStrategy;
37 import org.opendaylight.protocol.framework.ReconnectStrategyFactory;
38 import org.opendaylight.tcpmd5.api.KeyMapping;
39 import org.opendaylight.tcpmd5.netty.MD5ChannelFactory;
40 import org.opendaylight.tcpmd5.netty.MD5ChannelOption;
41 import org.opendaylight.tcpmd5.netty.MD5ServerChannelFactory;
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 MD5ServerChannelFactory<?> serverChannelFactory;
55     private final MD5ChannelFactory<?> channelFactory;
56     private final BGPHandlerFactory handlerFactory;
57     private final EventLoopGroup bossGroup;
58     private final EventLoopGroup workerGroup;
59     private Optional<KeyMapping> keys;
60
61     public BGPDispatcherImpl(final MessageRegistry messageRegistry, final EventLoopGroup bossGroup, final EventLoopGroup workerGroup) {
62         this(messageRegistry, bossGroup, workerGroup, null, null);
63     }
64
65     public BGPDispatcherImpl(final MessageRegistry messageRegistry, final EventLoopGroup bossGroup, final EventLoopGroup workerGroup, final MD5ChannelFactory<?> cf, final MD5ServerChannelFactory<?> scf) {
66         this.bossGroup = Preconditions.checkNotNull(bossGroup);
67         this.workerGroup = Preconditions.checkNotNull(workerGroup);
68         this.handlerFactory = new BGPHandlerFactory(messageRegistry);
69         this.channelFactory = cf;
70         this.serverChannelFactory = scf;
71         this.keys = Optional.absent();
72     }
73
74     @Override
75     public synchronized Future<BGPSessionImpl> createClient(final InetSocketAddress address, final BGPPeerRegistry listener, final ReconnectStrategy strategy) {
76         final BGPClientSessionNegotiatorFactory snf = new BGPClientSessionNegotiatorFactory(listener);
77         final ChannelPipelineInitializer initializer = BGPChannel.createChannelPipelineInitializer(BGPDispatcherImpl.this.handlerFactory, snf);
78
79         final Bootstrap bootstrap = createClientBootStrap();
80         final BGPProtocolSessionPromise sessionPromise = new BGPProtocolSessionPromise(address, strategy, bootstrap);
81         bootstrap.handler(BGPChannel.createClientChannelHandler(initializer, sessionPromise));
82         sessionPromise.connect();
83         LOG.debug("Client created.");
84         return sessionPromise;
85     }
86
87     protected Bootstrap createClientBootStrap() {
88         final Bootstrap bootstrap = new Bootstrap();
89         if (this.keys.isPresent()) {
90             if (this.channelFactory == null) {
91                 throw new UnsupportedOperationException("No key access instance available, cannot use key mapping");
92             }
93             bootstrap.channelFactory(this.channelFactory);
94             bootstrap.option(MD5ChannelOption.TCP_MD5SIG, this.keys.get());
95         } else {
96             bootstrap.channel(NioSocketChannel.class);
97         }
98
99         // Make sure we are doing round-robin processing
100         bootstrap.option(ChannelOption.MAX_MESSAGES_PER_READ, 1);
101         bootstrap.option(ChannelOption.SO_KEEPALIVE, Boolean.TRUE);
102         bootstrap.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, HIGH_WATER_MARK);
103         bootstrap.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, LOW_WATER_MARK);
104
105         if (bootstrap.group() == null) {
106             bootstrap.group(this.workerGroup);
107         }
108
109         return bootstrap;
110     }
111
112     @Override
113     public void close() {
114     }
115
116     @Override
117     public synchronized Future<Void> createReconnectingClient(final InetSocketAddress address, final BGPPeerRegistry peerRegistry,
118         final ReconnectStrategyFactory connectStrategyFactory, final Optional<KeyMapping> keys) {
119         final BGPClientSessionNegotiatorFactory snf = new BGPClientSessionNegotiatorFactory(peerRegistry);
120         this.keys = keys;
121         final Bootstrap bootstrap = createClientBootStrap();
122         final BGPReconnectPromise reconnectPromise = new BGPReconnectPromise(GlobalEventExecutor.INSTANCE, address,
123             connectStrategyFactory, bootstrap, BGPChannel.createChannelPipelineInitializer(BGPDispatcherImpl.this.handlerFactory, snf));
124         reconnectPromise.connect();
125         this.keys = Optional.absent();
126         return reconnectPromise;
127     }
128
129     @Override
130     public ChannelFuture createServer(final BGPPeerRegistry registry, final InetSocketAddress address) {
131         final BGPServerSessionNegotiatorFactory snf = new BGPServerSessionNegotiatorFactory(registry);
132         final ChannelPipelineInitializer initializer = BGPChannel.createChannelPipelineInitializer(BGPDispatcherImpl.this.handlerFactory, snf);
133         final ServerBootstrap serverBootstrap = createServerBootstrap(initializer);
134         final ChannelFuture channelFuture = serverBootstrap.bind(address);
135         LOG.debug("Initiated server {} at {}.", channelFuture, address);
136         return channelFuture;
137     }
138
139     private ServerBootstrap createServerBootstrap(final ChannelPipelineInitializer initializer) {
140         final ServerBootstrap serverBootstrap = new ServerBootstrap();
141         final ChannelHandler serverChannelHandler = BGPChannel.createServerChannelHandler(initializer);
142         serverBootstrap.childHandler(serverChannelHandler);
143
144         serverBootstrap.option(ChannelOption.SO_BACKLOG, Integer.valueOf(SOCKET_BACKLOG_SIZE));
145         serverBootstrap.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
146         serverBootstrap.childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, HIGH_WATER_MARK);
147         serverBootstrap.childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, LOW_WATER_MARK);
148         if (this.keys.isPresent()) {
149             if (this.serverChannelFactory == null) {
150                 throw new UnsupportedOperationException("No key access instance available, cannot use key mapping");
151             }
152             serverBootstrap.channelFactory(this.serverChannelFactory);
153             serverBootstrap.option(MD5ChannelOption.TCP_MD5SIG, this.keys.get());
154         } else {
155             serverBootstrap.channel(NioServerSocketChannel.class);
156         }
157
158         // Make sure we are doing round-robin processing
159         serverBootstrap.option(ChannelOption.MAX_MESSAGES_PER_READ, 1);
160
161         if (serverBootstrap.group() == null) {
162             serverBootstrap.group(this.bossGroup, this.workerGroup);
163         }
164         return serverBootstrap;
165     }
166
167     private static final class BGPChannel {
168         private static final String NEGOTIATOR = "negotiator";
169
170         private BGPChannel() {
171
172         }
173
174         public static <S extends BGPSession, T extends BGPSessionNegotiatorFactory> ChannelPipelineInitializer
175             createChannelPipelineInitializer(final BGPHandlerFactory hf, final T snf) {
176             return new ChannelPipelineInitializer<S>() {
177                 @Override
178                 public void initializeChannel(final SocketChannel channel, final Promise<S> promise) {
179                     channel.pipeline().addLast(hf.getDecoders());
180                     channel.pipeline().addLast(NEGOTIATOR, snf.getSessionNegotiator(channel, promise));
181                     channel.pipeline().addLast(hf.getEncoders());
182                 }
183             };
184         }
185
186         public static <S extends BGPSession> ChannelHandler createClientChannelHandler(final ChannelPipelineInitializer initializer, final Promise<S> promise) {
187             return new ChannelInitializer<SocketChannel>() {
188                 @Override
189                 protected void initChannel(final SocketChannel channel) {
190                     initializer.initializeChannel(channel, promise);
191                 }
192             };
193         }
194
195         public static ChannelHandler createServerChannelHandler(final ChannelPipelineInitializer initializer) {
196             return new ChannelInitializer<SocketChannel>() {
197                 @Override
198                 protected void initChannel(final SocketChannel channel) {
199                     initializer.initializeChannel(channel, new DefaultPromise<BGPSessionImpl>(GlobalEventExecutor.INSTANCE));
200                 }
201             };
202         }
203     }
204 }