BUG-4370: BGP reconnecting client: channel initiation
[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.Preconditions;
11 import io.netty.bootstrap.Bootstrap;
12 import io.netty.bootstrap.ServerBootstrap;
13 import io.netty.buffer.PooledByteBufAllocator;
14 import io.netty.channel.ChannelFuture;
15 import io.netty.channel.ChannelHandler;
16 import io.netty.channel.ChannelInitializer;
17 import io.netty.channel.ChannelOption;
18 import io.netty.channel.EventLoopGroup;
19 import io.netty.channel.socket.SocketChannel;
20 import io.netty.channel.socket.nio.NioServerSocketChannel;
21 import io.netty.channel.socket.nio.NioSocketChannel;
22 import io.netty.util.concurrent.DefaultPromise;
23 import io.netty.util.concurrent.EventExecutor;
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 final MD5ServerChannelFactory<?> scf;
52     private final MD5ChannelFactory<?> cf;
53     private final BGPHandlerFactory hf;
54     private final EventLoopGroup bossGroup;
55     private final EventLoopGroup workerGroup;
56     private final EventExecutor executor;
57     private 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.executor = Preconditions.checkNotNull(GlobalEventExecutor.INSTANCE);
67         this.hf = new BGPHandlerFactory(messageRegistry);
68         this.cf = cf;
69         this.scf = scf;
70         this.keys = null;
71     }
72
73     @Override
74     public synchronized Future<BGPSessionImpl> createClient(final InetSocketAddress address, final BGPPeerRegistry listener, final ReconnectStrategy strategy) {
75         final BGPClientSessionNegotiatorFactory snf = new BGPClientSessionNegotiatorFactory(listener);
76         final ChannelPipelineInitializer initializer = BGPChannel.createChannelPipelineInitializer(BGPDispatcherImpl.this.hf, snf);
77
78         final Bootstrap b = new Bootstrap();
79         final BGPProtocolSessionPromise p = new BGPProtocolSessionPromise(this.executor, address, strategy, b);
80         b.option(ChannelOption.SO_KEEPALIVE, Boolean.TRUE);
81         b.handler(BGPChannel.createChannelInitializer(initializer, p));
82         this.customizeBootstrap(b);
83         setWorkerGroup(b);
84         p.connect();
85         LOG.debug("Client created.");
86         return p;
87     }
88
89     @Override
90     public void close() {
91         try {
92             this.workerGroup.shutdownGracefully();
93         } finally {
94             this.bossGroup.shutdownGracefully();
95         }
96     }
97
98     @Override
99     public synchronized Future<Void> createReconnectingClient(final InetSocketAddress address, final BGPPeerRegistry peerRegistry,
100         final ReconnectStrategyFactory connectStrategyFactory, final KeyMapping keys) {
101         final BGPClientSessionNegotiatorFactory snf = new BGPClientSessionNegotiatorFactory(peerRegistry);
102         this.keys = keys;
103
104         final Bootstrap b = new Bootstrap();
105         final BGPReconnectPromise p = new BGPReconnectPromise<BGPSessionImpl>(GlobalEventExecutor.INSTANCE, address,
106             connectStrategyFactory, b, BGPChannel.createChannelPipelineInitializer(BGPDispatcherImpl.this.hf, snf));
107         b.option(ChannelOption.SO_KEEPALIVE, Boolean.TRUE);
108         this.customizeBootstrap(b);
109         setWorkerGroup(b);
110         p.connect();
111
112         this.keys = null;
113
114         return p;
115     }
116
117     @Override
118     public ChannelFuture createServer(final BGPPeerRegistry registry, final InetSocketAddress address) {
119         final BGPServerSessionNegotiatorFactory snf = new BGPServerSessionNegotiatorFactory(registry);
120         final ChannelPipelineInitializer initializer = BGPChannel.createChannelPipelineInitializer(BGPDispatcherImpl.this.hf, snf);
121         final ServerBootstrap b = new ServerBootstrap();
122         b.childHandler(BGPChannel.createChannelInitializer(initializer, new DefaultPromise(BGPDispatcherImpl.this.executor)));
123         b.option(ChannelOption.SO_BACKLOG, Integer.valueOf(SOCKET_BACKLOG_SIZE));
124         b.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
125         this.customizeBootstrap(b);
126
127         final ChannelFuture f = b.bind(address);
128         LOG.debug("Initiated server {} at {}.", f, address);
129         return f;
130     }
131
132     protected void customizeBootstrap(final Bootstrap b) {
133         if (this.keys != null && !this.keys.isEmpty()) {
134             if (this.cf == null) {
135                 throw new UnsupportedOperationException("No key access instance available, cannot use key mapping");
136             }
137             b.channelFactory(this.cf);
138             b.option(MD5ChannelOption.TCP_MD5SIG, this.keys);
139         }
140
141         // Make sure we are doing round-robin processing
142         b.option(ChannelOption.MAX_MESSAGES_PER_READ, 1);
143     }
144
145     private void customizeBootstrap(final ServerBootstrap b) {
146         if (this.keys != null && !this.keys.isEmpty()) {
147             if (this.scf == null) {
148                 throw new UnsupportedOperationException("No key access instance available, cannot use key mapping");
149             }
150             b.channelFactory(this.scf);
151             b.option(MD5ChannelOption.TCP_MD5SIG, this.keys);
152         }
153
154         // Make sure we are doing round-robin processing
155         b.option(ChannelOption.MAX_MESSAGES_PER_READ, 1);
156
157         if (b.group() == null) {
158             b.group(this.bossGroup, this.workerGroup);
159         }
160
161         try {
162             b.channel(NioServerSocketChannel.class);
163         } catch (final IllegalStateException e) {
164             LOG.trace("Not overriding channelFactory on bootstrap {}", b, e);
165         }
166     }
167
168     private void setWorkerGroup(final Bootstrap b) {
169         if (b.group() == null) {
170             b.group(this.workerGroup);
171         }
172         try {
173             b.channel(NioSocketChannel.class);
174         } catch (final IllegalStateException e) {
175             LOG.trace("Not overriding channelFactory on bootstrap {}", b, e);
176         }
177     }
178
179     private static final class BGPChannel {
180         private static final String NEGOTIATOR = "negotiator";
181
182         private BGPChannel() {
183
184         }
185
186         public static <S extends BGPSession, T extends BGPSessionNegotiatorFactory> ChannelPipelineInitializer
187             createChannelPipelineInitializer(final BGPHandlerFactory hf, final T snf) {
188             return new ChannelPipelineInitializer<S>() {
189                 @Override
190                 public void initializeChannel(final SocketChannel ch, final Promise<S> promise) {
191                     ch.pipeline().addLast(hf.getDecoders());
192                     ch.pipeline().addLast(NEGOTIATOR, snf.getSessionNegotiator(ch, promise));
193                     ch.pipeline().addLast(hf.getEncoders());
194                 }
195             };
196         }
197
198         public static <S extends BGPSession> ChannelHandler createChannelInitializer(final ChannelPipelineInitializer initializer, final Promise<S> promise) {
199             return new ChannelInitializer<SocketChannel>() {
200                 @Override
201                 protected void initChannel(final SocketChannel ch) {
202                     initializer.initializeChannel(ch, promise);
203                 }
204             };
205         }
206     }
207 }