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