Refactor BGP session
[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<?> serverChannelFactory;
52     private final MD5ChannelFactory<?> channelFactory;
53     private final BGPHandlerFactory handlerFactory;
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.handlerFactory = new BGPHandlerFactory(messageRegistry);
68         this.channelFactory = cf;
69         this.serverChannelFactory = 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.handlerFactory, snf);
77
78         final Bootstrap bootstrap = new Bootstrap();
79         final BGPProtocolSessionPromise sessionPromise = new BGPProtocolSessionPromise(this.executor, address, strategy, bootstrap);
80         bootstrap.option(ChannelOption.SO_KEEPALIVE, Boolean.TRUE);
81         bootstrap.handler(BGPChannel.createChannelInitializer(initializer, sessionPromise));
82         this.customizeBootstrap(bootstrap);
83         setWorkerGroup(bootstrap);
84         sessionPromise.connect();
85         LOG.debug("Client created.");
86         return sessionPromise;
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 bootstrap = new Bootstrap();
105         final BGPReconnectPromise reconnectPromise = new BGPReconnectPromise<BGPSessionImpl>(GlobalEventExecutor.INSTANCE, address,
106             connectStrategyFactory, bootstrap, BGPChannel.createChannelPipelineInitializer(BGPDispatcherImpl.this.handlerFactory, snf));
107         bootstrap.option(ChannelOption.SO_KEEPALIVE, Boolean.TRUE);
108         this.customizeBootstrap(bootstrap);
109         setWorkerGroup(bootstrap);
110         reconnectPromise.connect();
111
112         this.keys = null;
113
114         return reconnectPromise;
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.handlerFactory, snf);
121         final ServerBootstrap serverBootstrap = new ServerBootstrap();
122         serverBootstrap.childHandler(BGPChannel.createChannelInitializer(initializer, new DefaultPromise(BGPDispatcherImpl.this.executor)));
123         serverBootstrap.option(ChannelOption.SO_BACKLOG, Integer.valueOf(SOCKET_BACKLOG_SIZE));
124         serverBootstrap.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
125         this.customizeBootstrap(serverBootstrap);
126
127         final ChannelFuture channelFuture = serverBootstrap.bind(address);
128         LOG.debug("Initiated server {} at {}.", channelFuture, address);
129         return channelFuture;
130     }
131
132     protected void customizeBootstrap(final Bootstrap bootstrap) {
133         if (this.keys != null && !this.keys.isEmpty()) {
134             if (this.channelFactory == null) {
135                 throw new UnsupportedOperationException("No key access instance available, cannot use key mapping");
136             }
137             bootstrap.channelFactory(this.channelFactory);
138             bootstrap.option(MD5ChannelOption.TCP_MD5SIG, this.keys);
139         }
140
141         // Make sure we are doing round-robin processing
142         bootstrap.option(ChannelOption.MAX_MESSAGES_PER_READ, 1);
143     }
144
145     private void customizeBootstrap(final ServerBootstrap serverBootstrap) {
146         if (this.keys != null && !this.keys.isEmpty()) {
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);
152         }
153
154         // Make sure we are doing round-robin processing
155         serverBootstrap.option(ChannelOption.MAX_MESSAGES_PER_READ, 1);
156
157         if (serverBootstrap.group() == null) {
158             serverBootstrap.group(this.bossGroup, this.workerGroup);
159         }
160
161         try {
162             serverBootstrap.channel(NioServerSocketChannel.class);
163         } catch (final IllegalStateException e) {
164             LOG.trace("Not overriding channelFactory on bootstrap {}", serverBootstrap, e);
165         }
166     }
167
168     private void setWorkerGroup(final Bootstrap bootstrap) {
169         if (bootstrap.group() == null) {
170             bootstrap.group(this.workerGroup);
171         }
172         try {
173             bootstrap.channel(NioSocketChannel.class);
174         } catch (final IllegalStateException e) {
175             LOG.trace("Not overriding channelFactory on bootstrap {}", bootstrap, 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 channel, final Promise<S> promise) {
191                     channel.pipeline().addLast(hf.getDecoders());
192                     channel.pipeline().addLast(NEGOTIATOR, snf.getSessionNegotiator(channel, promise));
193                     channel.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 channel) {
202                     initializer.initializeChannel(channel, promise);
203                 }
204             };
205         }
206     }
207 }