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