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