BUG-3888 : remove unused remote-as from negotiators.
[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
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.TRUE);
82         b.handler(BGPChannel.createChannelInitializer(initializer, p));
83         this.customizeBootstrap(b);
84         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, final BGPPeerRegistry peerRegistry,
101         final ReconnectStrategyFactory connectStrategyFactory, final KeyMapping keys) {
102         final BGPClientSessionNegotiatorFactory snf = new BGPClientSessionNegotiatorFactory(peerRegistry);
103         this.keys = keys;
104
105         final Bootstrap b = new Bootstrap();
106         final BGPReconnectPromise p = new BGPReconnectPromise<BGPSessionImpl>(GlobalEventExecutor.INSTANCE, address,
107             connectStrategyFactory, b, BGPChannel.createChannelPipelineInitializer(BGPDispatcherImpl.this.hf.getDecoders(), snf, BGPDispatcherImpl.this.hf.getEncoders()));
108         b.option(ChannelOption.SO_KEEPALIVE, Boolean.TRUE);
109         this.customizeBootstrap(b);
110         setWorkerGroup(b);
111         p.connect();
112
113         this.keys = null;
114
115         return p;
116     }
117
118     @Override
119     public ChannelFuture createServer(final BGPPeerRegistry registry, final InetSocketAddress address) {
120         final BGPServerSessionNegotiatorFactory snf = new BGPServerSessionNegotiatorFactory(registry);
121         final ChannelPipelineInitializer initializer = BGPChannel.createChannelPipelineInitializer
122             (BGPDispatcherImpl.this.hf.getDecoders(), snf, BGPDispatcherImpl.this.hf.getEncoders());
123         final ServerBootstrap b = new ServerBootstrap();
124         b.childHandler(BGPChannel.createChannelInitializer(initializer, new DefaultPromise(BGPDispatcherImpl.this.executor)));
125         b.option(ChannelOption.SO_BACKLOG, Integer.valueOf(SOCKET_BACKLOG_SIZE));
126         b.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
127         this.customizeBootstrap(b);
128
129         final ChannelFuture f = b.bind(address);
130         LOG.debug("Initiated server {} at {}.", f, address);
131         return f;
132     }
133
134     protected void customizeBootstrap(final Bootstrap b) {
135         if (this.keys != null && !this.keys.isEmpty()) {
136             if (this.cf == null) {
137                 throw new UnsupportedOperationException("No key access instance available, cannot use key mapping");
138             }
139             b.channelFactory(this.cf);
140             b.option(MD5ChannelOption.TCP_MD5SIG, this.keys);
141         }
142
143         // Make sure we are doing round-robin processing
144         b.option(ChannelOption.MAX_MESSAGES_PER_READ, 1);
145     }
146
147     private void customizeBootstrap(final ServerBootstrap b) {
148         if (this.keys != null && !this.keys.isEmpty()) {
149             if (this.scf == null) {
150                 throw new UnsupportedOperationException("No key access instance available, cannot use key mapping");
151             }
152             b.channelFactory(this.scf);
153             b.option(MD5ChannelOption.TCP_MD5SIG, this.keys);
154         }
155
156         // Make sure we are doing round-robin processing
157         b.option(ChannelOption.MAX_MESSAGES_PER_READ, 1);
158
159         if (b.group() == null) {
160             b.group(this.bossGroup, this.workerGroup);
161         }
162
163         try {
164             b.channel(NioServerSocketChannel.class);
165         } catch (final IllegalStateException e) {
166             LOG.trace("Not overriding channelFactory on bootstrap {}", b, e);
167         }
168     }
169
170     private void setWorkerGroup(final Bootstrap b) {
171         if (b.group() == null) {
172             b.group(this.workerGroup);
173         }
174         try {
175             b.channel(NioSocketChannel.class);
176         } catch (final IllegalStateException e) {
177             LOG.trace("Not overriding channelFactory on bootstrap {}", b, e);
178         }
179     }
180
181     private static final class BGPChannel {
182         private static final String NEGOTIATOR = "negotiator";
183
184         private BGPChannel() {
185
186         }
187
188         public static <S extends BGPSession, T extends BGPSessionNegotiatorFactory> ChannelPipelineInitializer
189             createChannelPipelineInitializer(final ChannelHandler[] channelDecoder, final T snf, final ChannelHandler[] channelEncoder) {
190             return new ChannelPipelineInitializer<S>() {
191                 @Override
192                 public void initializeChannel(final SocketChannel ch, final Promise<S> promise) {
193                     ch.pipeline().addLast(channelDecoder);
194                     ch.pipeline().addLast(NEGOTIATOR, snf.getSessionNegotiator(ch, promise));
195                     ch.pipeline().addLast(channelEncoder);
196                 }
197             };
198         }
199
200         public static <S extends BGPSession> ChannelHandler createChannelInitializer(final ChannelPipelineInitializer initializer, final Promise<S> promise) {
201             return new ChannelInitializer<SocketChannel>() {
202                 @Override
203                 protected void initChannel(final SocketChannel ch) {
204                     initializer.initializeChannel(ch, promise);
205                 }
206             };
207         }
208     }
209 }