BUG-4531: Error channelFactory set already
[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.Optional;
11 import com.google.common.base.Preconditions;
12 import io.netty.bootstrap.Bootstrap;
13 import io.netty.bootstrap.ServerBootstrap;
14 import io.netty.buffer.PooledByteBufAllocator;
15 import io.netty.channel.ChannelFuture;
16 import io.netty.channel.ChannelHandler;
17 import io.netty.channel.ChannelInitializer;
18 import io.netty.channel.ChannelOption;
19 import io.netty.channel.EventLoopGroup;
20 import io.netty.channel.socket.SocketChannel;
21 import io.netty.channel.socket.nio.NioServerSocketChannel;
22 import io.netty.channel.socket.nio.NioSocketChannel;
23 import io.netty.util.concurrent.DefaultPromise;
24 import io.netty.util.concurrent.EventExecutor;
25 import io.netty.util.concurrent.Future;
26 import io.netty.util.concurrent.GlobalEventExecutor;
27 import io.netty.util.concurrent.Promise;
28 import java.net.InetSocketAddress;
29 import org.opendaylight.protocol.bgp.parser.spi.MessageRegistry;
30 import org.opendaylight.protocol.bgp.rib.impl.protocol.BGPProtocolSessionPromise;
31 import org.opendaylight.protocol.bgp.rib.impl.protocol.BGPReconnectPromise;
32 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPDispatcher;
33 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPPeerRegistry;
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.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<?> serverChannelFactory;
53     private final MD5ChannelFactory<?> channelFactory;
54     private final BGPHandlerFactory handlerFactory;
55     private final EventLoopGroup bossGroup;
56     private final EventLoopGroup workerGroup;
57     private final EventExecutor executor;
58     private Optional<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.handlerFactory = new BGPHandlerFactory(messageRegistry);
69         this.channelFactory = cf;
70         this.serverChannelFactory = scf;
71         this.keys = Optional.absent();
72     }
73
74     @Override
75     public synchronized Future<BGPSessionImpl> createClient(final InetSocketAddress address, final BGPPeerRegistry listener, final ReconnectStrategy strategy) {
76         final BGPClientSessionNegotiatorFactory snf = new BGPClientSessionNegotiatorFactory(listener);
77         final ChannelPipelineInitializer initializer = BGPChannel.createChannelPipelineInitializer(BGPDispatcherImpl.this.handlerFactory, snf);
78
79         final Bootstrap bootstrap = createClientBootStrap();
80         final BGPProtocolSessionPromise sessionPromise = new BGPProtocolSessionPromise(this.executor, address, strategy, bootstrap);
81         bootstrap.handler(BGPChannel.createChannelInitializer(initializer, sessionPromise));
82         sessionPromise.connect();
83         LOG.debug("Client created.");
84         return sessionPromise;
85     }
86
87     protected Bootstrap createClientBootStrap() {
88         final Bootstrap bootstrap = new Bootstrap();
89         if (this.keys.isPresent()) {
90             if (this.channelFactory == null) {
91                 throw new UnsupportedOperationException("No key access instance available, cannot use key mapping");
92             }
93             bootstrap.channelFactory(this.channelFactory);
94             bootstrap.option(MD5ChannelOption.TCP_MD5SIG, this.keys.get());
95         } else {
96             bootstrap.channel(NioSocketChannel.class);
97         }
98
99         // Make sure we are doing round-robin processing
100         bootstrap.option(ChannelOption.MAX_MESSAGES_PER_READ, 1);
101         bootstrap.option(ChannelOption.SO_KEEPALIVE, Boolean.TRUE);
102
103         if (bootstrap.group() == null) {
104             bootstrap.group(this.workerGroup);
105         }
106
107         return bootstrap;
108     }
109
110     @Override
111     public void close() {
112         try {
113             this.workerGroup.shutdownGracefully();
114         } finally {
115             this.bossGroup.shutdownGracefully();
116         }
117     }
118
119     @Override
120     public synchronized Future<Void> createReconnectingClient(final InetSocketAddress address, final BGPPeerRegistry peerRegistry,
121         final ReconnectStrategyFactory connectStrategyFactory, final Optional<KeyMapping> keys) {
122         final BGPClientSessionNegotiatorFactory snf = new BGPClientSessionNegotiatorFactory(peerRegistry);
123         this.keys = keys;
124         final Bootstrap bootstrap = createClientBootStrap();
125         final BGPReconnectPromise reconnectPromise = new BGPReconnectPromise<BGPSessionImpl>(GlobalEventExecutor.INSTANCE, address,
126             connectStrategyFactory, bootstrap, BGPChannel.createChannelPipelineInitializer(BGPDispatcherImpl.this.handlerFactory, snf));
127         reconnectPromise.connect();
128         this.keys = null;
129         return reconnectPromise;
130     }
131
132     @Override
133     public ChannelFuture createServer(final BGPPeerRegistry registry, final InetSocketAddress address) {
134         final BGPServerSessionNegotiatorFactory snf = new BGPServerSessionNegotiatorFactory(registry);
135         final ChannelPipelineInitializer initializer = BGPChannel.createChannelPipelineInitializer(BGPDispatcherImpl.this.handlerFactory, snf);
136         final ServerBootstrap serverBootstrap = createServerBootstrap(initializer);
137         final ChannelFuture channelFuture = serverBootstrap.bind(address);
138         LOG.debug("Initiated server {} at {}.", channelFuture, address);
139         return channelFuture;
140     }
141
142     private ServerBootstrap createServerBootstrap(final ChannelPipelineInitializer initializer) {
143         final ServerBootstrap serverBootstrap = new ServerBootstrap();
144         serverBootstrap.childHandler(BGPChannel.createChannelInitializer(initializer, new DefaultPromise(BGPDispatcherImpl.this.executor)));
145         serverBootstrap.option(ChannelOption.SO_BACKLOG, Integer.valueOf(SOCKET_BACKLOG_SIZE));
146         serverBootstrap.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
147         if (this.keys.isPresent()) {
148             if (this.serverChannelFactory == null) {
149                 throw new UnsupportedOperationException("No key access instance available, cannot use key mapping");
150             }
151             serverBootstrap.channelFactory(this.serverChannelFactory);
152             serverBootstrap.option(MD5ChannelOption.TCP_MD5SIG, this.keys.get());
153         } else {
154             serverBootstrap.channel(NioServerSocketChannel.class);
155         }
156
157         // Make sure we are doing round-robin processing
158         serverBootstrap.option(ChannelOption.MAX_MESSAGES_PER_READ, 1);
159
160         if (serverBootstrap.group() == null) {
161             serverBootstrap.group(this.bossGroup, this.workerGroup);
162         }
163         return serverBootstrap;
164     }
165
166     private static final class BGPChannel {
167         private static final String NEGOTIATOR = "negotiator";
168
169         private BGPChannel() {
170
171         }
172
173         public static <S extends BGPSession, T extends BGPSessionNegotiatorFactory> ChannelPipelineInitializer
174             createChannelPipelineInitializer(final BGPHandlerFactory hf, final T snf) {
175             return new ChannelPipelineInitializer<S>() {
176                 @Override
177                 public void initializeChannel(final SocketChannel channel, final Promise<S> promise) {
178                     channel.pipeline().addLast(hf.getDecoders());
179                     channel.pipeline().addLast(NEGOTIATOR, snf.getSessionNegotiator(channel, promise));
180                     channel.pipeline().addLast(hf.getEncoders());
181                 }
182             };
183         }
184
185         public static <S extends BGPSession> ChannelHandler createChannelInitializer(final ChannelPipelineInitializer initializer, final Promise<S> promise) {
186             return new ChannelInitializer<SocketChannel>() {
187                 @Override
188                 protected void initChannel(final SocketChannel channel) {
189                     initializer.initializeChannel(channel, promise);
190                 }
191             };
192         }
193     }
194 }