BUG-2873 : Remove dependency protocol-framework on BGP
[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.BGPSessionValidator;
34 import org.opendaylight.protocol.bgp.rib.spi.BGPSessionNegotiatorFactory;
35 import org.opendaylight.protocol.framework.ReconnectStrategy;
36 import org.opendaylight.protocol.framework.ReconnectStrategyFactory;
37 import org.opendaylight.tcpmd5.api.KeyMapping;
38 import org.opendaylight.tcpmd5.netty.MD5ChannelFactory;
39 import org.opendaylight.tcpmd5.netty.MD5ChannelOption;
40 import org.opendaylight.tcpmd5.netty.MD5ServerChannelFactory;
41 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.AsNumber;
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 final MD5ServerChannelFactory<?> scf;
51     private final MD5ChannelFactory<?> cf;
52     private final BGPHandlerFactory hf;
53     private final EventLoopGroup bossGroup;
54     private final EventLoopGroup workerGroup;
55     private final EventExecutor executor;
56     private KeyMapping keys;
57
58     public BGPDispatcherImpl(final MessageRegistry messageRegistry, final EventLoopGroup bossGroup, final EventLoopGroup workerGroup) {
59         this(messageRegistry, bossGroup, workerGroup, null, null);
60     }
61
62     public BGPDispatcherImpl(final MessageRegistry messageRegistry, final EventLoopGroup bossGroup, final EventLoopGroup workerGroup, final MD5ChannelFactory<?> cf, final MD5ServerChannelFactory<?> scf) {
63         this.bossGroup = Preconditions.checkNotNull(bossGroup);
64         this.workerGroup = Preconditions.checkNotNull(workerGroup);
65         this.executor = Preconditions.checkNotNull(GlobalEventExecutor.INSTANCE);
66         this.hf = new BGPHandlerFactory(messageRegistry);
67         this.cf = cf;
68         this.scf = scf;
69         this.keys = null;
70     }
71
72     @Override
73     public synchronized Future<BGPSessionImpl> createClient(final InetSocketAddress address,
74                                                             final AsNumber remoteAs, final BGPPeerRegistry listener, final ReconnectStrategy strategy) {
75         final BGPClientSessionNegotiatorFactory snf = new BGPClientSessionNegotiatorFactory(remoteAs, listener);
76         final ChannelPipelineInitializer initializer = BGPChannel.createChannelPipelineInitializer
77             (BGPDispatcherImpl.this.hf.getDecoders(), snf, BGPDispatcherImpl.this.hf.getEncoders());
78
79         final Bootstrap b = new Bootstrap();
80         final BGPProtocolSessionPromise p = new BGPProtocolSessionPromise(this.executor, address, strategy, b);
81         b.option(ChannelOption.SO_KEEPALIVE, Boolean.valueOf(true));
82         b.handler(BGPChannel.createChannelInitializer(initializer, p));
83         this.customizeBootstrap(b);
84         this.setWorkerGroup(b);
85         p.connect();
86         LOG.debug("Client created.");
87         return p;
88     }
89
90     @Override
91     public void close() {
92         try {
93             this.workerGroup.shutdownGracefully();
94         } finally {
95             this.bossGroup.shutdownGracefully();
96         }
97     }
98
99     @Override
100     public synchronized Future<Void> createReconnectingClient(final InetSocketAddress address,
101                                                               final AsNumber remoteAs, final BGPPeerRegistry peerRegistry, final ReconnectStrategyFactory connectStrategyFactory,
102                                                               final KeyMapping keys) {
103         final BGPClientSessionNegotiatorFactory snf = new BGPClientSessionNegotiatorFactory(remoteAs, peerRegistry);
104         this.keys = keys;
105
106         final Bootstrap b = new Bootstrap();
107         final BGPReconnectPromise p = new BGPReconnectPromise(GlobalEventExecutor.INSTANCE, address,
108             connectStrategyFactory, b, BGPChannel.createChannelPipelineInitializer(BGPDispatcherImpl.this.hf.getDecoders(), snf, BGPDispatcherImpl.this.hf.getEncoders()));
109         b.option(ChannelOption.SO_KEEPALIVE, Boolean.valueOf(true));
110         this.customizeBootstrap(b);
111         this.setWorkerGroup(b);
112         p.connect();
113
114         this.keys = null;
115
116         return p;
117     }
118
119     @Override
120     public ChannelFuture createServer(final BGPPeerRegistry registry, final InetSocketAddress address, final BGPSessionValidator sessionValidator) {
121         final BGPServerSessionNegotiatorFactory snf = new BGPServerSessionNegotiatorFactory(sessionValidator, registry);
122         final ChannelPipelineInitializer initializer = BGPChannel.createChannelPipelineInitializer
123             (BGPDispatcherImpl.this.hf.getDecoders(), snf, BGPDispatcherImpl.this.hf.getEncoders());
124         final ServerBootstrap b = new ServerBootstrap();
125         b.childHandler(BGPChannel.createChannelInitializer(initializer, new DefaultPromise(BGPDispatcherImpl.this.executor)));
126         b.option(ChannelOption.SO_BACKLOG, Integer.valueOf(128));
127         b.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
128         this.customizeBootstrap(b);
129
130         final ChannelFuture f = b.bind(address);
131         LOG.debug("Initiated server {} at {}.", f, address);
132         return f;
133     }
134
135     protected void customizeBootstrap(final Bootstrap b) {
136         if (this.keys != null && !this.keys.isEmpty()) {
137             if (this.cf == null) {
138                 throw new UnsupportedOperationException("No key access instance available, cannot use key mapping");
139             }
140             b.channelFactory(this.cf);
141             b.option(MD5ChannelOption.TCP_MD5SIG, this.keys);
142         }
143
144         // Make sure we are doing round-robin processing
145         b.option(ChannelOption.MAX_MESSAGES_PER_READ, 1);
146     }
147
148     private void customizeBootstrap(final ServerBootstrap b) {
149         if (this.keys != null && !this.keys.isEmpty()) {
150             if (this.scf == null) {
151                 throw new UnsupportedOperationException("No key access instance available, cannot use key mapping");
152             }
153             b.channelFactory(this.scf);
154             b.option(MD5ChannelOption.TCP_MD5SIG, this.keys);
155         }
156
157         // Make sure we are doing round-robin processing
158         b.option(ChannelOption.MAX_MESSAGES_PER_READ, 1);
159
160         if (b.group() == null) {
161             b.group(this.bossGroup, this.workerGroup);
162         }
163
164         try {
165             b.channel(NioServerSocketChannel.class);
166         } catch (IllegalStateException e) {
167             LOG.trace("Not overriding channelFactory on bootstrap {}", b, e);
168         }
169     }
170
171     private void setWorkerGroup(final Bootstrap b) {
172         if (b.group() == null) {
173             b.group(this.workerGroup);
174         }
175         try {
176             b.channel(NioSocketChannel.class);
177         } catch (IllegalStateException e) {
178             LOG.trace("Not overriding channelFactory on bootstrap {}", b, e);
179         }
180     }
181
182     public interface ChannelPipelineInitializer {
183         void initializeChannel(SocketChannel socketChannel, Promise<BGPSessionImpl> promise);
184     }
185
186     public static class BGPChannel {
187         private static final String NEGOTIATOR = "negotiator";
188
189         private BGPChannel() {
190
191         }
192
193         public static <T extends BGPSessionNegotiatorFactory> ChannelPipelineInitializer createChannelPipelineInitializer(final ChannelHandler[] channelDecoder,
194                                                                                                                           final T snf,
195                                                                                                                           final ChannelHandler[] channelEncoder) {
196             return new ChannelPipelineInitializer() {
197                 @Override
198                 public void initializeChannel(final SocketChannel ch, final Promise<BGPSessionImpl> promise) {
199                     ch.pipeline().addLast(channelDecoder);
200                     ch.pipeline().addLast(NEGOTIATOR, snf.getSessionNegotiator(ch, promise));
201                     ch.pipeline().addLast(channelEncoder);
202                 }
203             };
204         }
205
206         public static ChannelHandler createChannelInitializer(final ChannelPipelineInitializer initializer, final Promise<BGPSessionImpl> promise) {
207             return new ChannelInitializer<SocketChannel>() {
208                 @Override
209                 protected void initChannel(SocketChannel ch) {
210                     initializer.initializeChannel(ch, promise);
211                 }
212             };
213         }
214     }
215 }
216
217