Enable netty config modules to restart when blueprint container restarts
[controller.git] / opendaylight / commons / protocol-framework / src / main / java / org / opendaylight / protocol / framework / AbstractDispatcher.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.framework;
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.Channel;
15 import io.netty.channel.ChannelFuture;
16 import io.netty.channel.ChannelInitializer;
17 import io.netty.channel.ChannelOption;
18 import io.netty.channel.EventLoopGroup;
19 import io.netty.channel.ServerChannel;
20 import io.netty.channel.local.LocalServerChannel;
21 import io.netty.channel.socket.SocketChannel;
22 import io.netty.channel.socket.nio.NioServerSocketChannel;
23 import io.netty.channel.socket.nio.NioSocketChannel;
24 import io.netty.util.concurrent.DefaultPromise;
25 import io.netty.util.concurrent.EventExecutor;
26 import io.netty.util.concurrent.Future;
27 import io.netty.util.concurrent.GlobalEventExecutor;
28 import io.netty.util.concurrent.Promise;
29 import java.io.Closeable;
30 import java.net.InetSocketAddress;
31 import java.net.SocketAddress;
32 import org.slf4j.Logger;
33 import org.slf4j.LoggerFactory;
34
35 /**
36  * Dispatcher class for creating servers and clients. The idea is to first create servers and clients and the run the
37  * start method that will handle sockets in different thread.
38  */
39 @Deprecated
40 public abstract class AbstractDispatcher<S extends ProtocolSession<?>, L extends SessionListener<?, ?, ?>> implements Closeable {
41
42
43     protected interface ChannelPipelineInitializer<CH extends Channel, S extends ProtocolSession<?>> {
44         /**
45          * Initializes channel by specifying the handlers in its pipeline. Handlers are protocol specific, therefore this
46          * method needs to be implemented in protocol specific Dispatchers.
47          *
48          * @param channel whose pipeline should be defined, also to be passed to {@link SessionNegotiatorFactory}
49          * @param promise to be passed to {@link SessionNegotiatorFactory}
50          */
51         void initializeChannel(CH channel, Promise<S> promise);
52     }
53
54     protected interface PipelineInitializer<S extends ProtocolSession<?>> extends ChannelPipelineInitializer<SocketChannel, S> {
55
56     }
57
58
59     private static final Logger LOG = LoggerFactory.getLogger(AbstractDispatcher.class);
60
61     private final EventLoopGroup bossGroup;
62
63     private final EventLoopGroup workerGroup;
64
65     private final EventExecutor executor;
66
67     protected AbstractDispatcher(final EventLoopGroup bossGroup, final EventLoopGroup workerGroup) {
68         this(GlobalEventExecutor.INSTANCE, bossGroup, workerGroup);
69     }
70
71     protected AbstractDispatcher(final EventExecutor executor, final EventLoopGroup bossGroup, final EventLoopGroup workerGroup) {
72         this.bossGroup = Preconditions.checkNotNull(bossGroup);
73         this.workerGroup = Preconditions.checkNotNull(workerGroup);
74         this.executor = Preconditions.checkNotNull(executor);
75     }
76
77
78     /**
79      * Creates server. Each server needs factories to pass their instances to client sessions.
80      *
81      * @param address address to which the server should be bound
82      * @param initializer instance of PipelineInitializer used to initialize the channel pipeline
83      *
84      * @return ChannelFuture representing the binding process
85      */
86     protected ChannelFuture createServer(final InetSocketAddress address, final PipelineInitializer<S> initializer) {
87         return createServer(address, NioServerSocketChannel.class, initializer);
88     }
89
90     /**
91      * Creates server. Each server needs factories to pass their instances to client sessions.
92      *
93      * @param address address to which the server should be bound
94      * @param channelClass The {@link Class} which is used to create {@link Channel} instances from.
95      * @param initializer instance of PipelineInitializer used to initialize the channel pipeline
96      *
97      * @return ChannelFuture representing the binding process
98      */
99     protected <CH extends Channel> ChannelFuture createServer(final SocketAddress address, final Class<? extends ServerChannel> channelClass,
100             final ChannelPipelineInitializer<CH, S> initializer) {
101         final ServerBootstrap b = new ServerBootstrap();
102         b.childHandler(new ChannelInitializer<CH>() {
103
104             @Override
105             protected void initChannel(final CH ch) {
106                 initializer.initializeChannel(ch, new DefaultPromise<S>(executor));
107             }
108         });
109
110         b.option(ChannelOption.SO_BACKLOG, 128);
111         if (LocalServerChannel.class.equals(channelClass) == false) {
112             // makes no sense for LocalServer and produces warning
113             b.childOption(ChannelOption.SO_KEEPALIVE, true);
114             b.childOption(ChannelOption.TCP_NODELAY , true);
115         }
116         b.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
117         customizeBootstrap(b);
118
119         if (b.group() == null) {
120             b.group(bossGroup, workerGroup);
121         }
122         try {
123             b.channel(channelClass);
124         } catch (IllegalStateException e) {
125             // FIXME: if this is ok, document why
126             LOG.trace("Not overriding channelFactory on bootstrap {}", b, e);
127         }
128
129         // Bind and start to accept incoming connections.
130         final ChannelFuture f = b.bind(address);
131         LOG.debug("Initiated server {} at {}.", f, address);
132         return f;
133     }
134
135     /**
136      * Customize a server bootstrap before the server is created. This allows
137      * subclasses to assign non-default server options before the server is
138      * created.
139      *
140      * @param b Server bootstrap
141      */
142     protected void customizeBootstrap(final ServerBootstrap b) {
143         // The default is a no-op
144     }
145
146     /**
147      * Creates a client.
148      *
149      * @param address remote address
150      * @param connectStrategy Reconnection strategy to be used when initial connection fails
151      *
152      * @return Future representing the connection process. Its result represents the combined success of TCP connection
153      *         as well as session negotiation.
154      */
155     protected Future<S> createClient(final InetSocketAddress address, final ReconnectStrategy strategy, final PipelineInitializer<S> initializer) {
156         final Bootstrap b = new Bootstrap();
157         final ProtocolSessionPromise<S> p = new ProtocolSessionPromise<>(executor, address, strategy, b);
158         b.option(ChannelOption.SO_KEEPALIVE, true).handler(
159                 new ChannelInitializer<SocketChannel>() {
160                     @Override
161                     protected void initChannel(final SocketChannel ch) {
162                         initializer.initializeChannel(ch, p);
163                     }
164                 });
165
166         customizeBootstrap(b);
167         setWorkerGroup(b);
168         setChannelFactory(b);
169
170         p.connect();
171         LOG.debug("Client created.");
172         return p;
173     }
174
175     private void setWorkerGroup(final Bootstrap b) {
176         if (b.group() == null) {
177             b.group(workerGroup);
178         }
179     }
180
181     /**
182      * Create a client but use a pre-configured bootstrap.
183      * This method however replaces the ChannelInitializer in the bootstrap. All other configuration is preserved.
184      *
185      * @param address remote address
186      */
187     protected Future<S> createClient(final InetSocketAddress address, final ReconnectStrategy strategy, final Bootstrap bootstrap, final PipelineInitializer<S> initializer) {
188         final ProtocolSessionPromise<S> p = new ProtocolSessionPromise<>(executor, address, strategy, bootstrap);
189
190         bootstrap.handler(
191                 new ChannelInitializer<SocketChannel>() {
192                     @Override
193                     protected void initChannel(final SocketChannel ch) {
194                         initializer.initializeChannel(ch, p);
195                     }
196                 });
197
198         p.connect();
199         LOG.debug("Client created.");
200         return p;
201     }
202
203     /**
204      * Customize a client bootstrap before the connection is attempted. This
205      * allows subclasses to assign non-default options before the client is
206      * created.
207      *
208      * @param b Client bootstrap
209      */
210     protected void customizeBootstrap(final Bootstrap b) {
211         // The default is a no-op
212     }
213
214     /**
215      *
216      * @deprecated use {@link org.opendaylight.protocol.framework.AbstractDispatcher#createReconnectingClient(java.net.InetSocketAddress, ReconnectStrategyFactory, org.opendaylight.protocol.framework.AbstractDispatcher.PipelineInitializer)} with only one reconnectStrategyFactory instead.
217      *
218      * Creates a client.
219      *
220      * @param address remote address
221      * @param connectStrategyFactory Factory for creating reconnection strategy to be used when initial connection fails
222      * @param reestablishStrategy Reconnection strategy to be used when the already-established session fails
223      *
224      * @return Future representing the reconnection task. It will report completion based on reestablishStrategy, e.g.
225      *         success if it indicates no further attempts should be made and failure if it reports an error
226      */
227     @Deprecated
228     protected Future<Void> createReconnectingClient(final InetSocketAddress address, final ReconnectStrategyFactory connectStrategyFactory,
229             final ReconnectStrategy reestablishStrategy, final PipelineInitializer<S> initializer) {
230         return createReconnectingClient(address, connectStrategyFactory, initializer);
231     }
232
233     /**
234      * Creates a reconnecting client.
235      *
236      * @param address remote address
237      * @param connectStrategyFactory Factory for creating reconnection strategy for every reconnect attempt
238      *
239      * @return Future representing the reconnection task. It will report completion based on reestablishStrategy, e.g.
240      *         success is never reported, only failure when it runs out of reconnection attempts.
241      */
242     protected Future<Void> createReconnectingClient(final InetSocketAddress address, final ReconnectStrategyFactory connectStrategyFactory,
243             final PipelineInitializer<S> initializer) {
244         final Bootstrap b = new Bootstrap();
245
246         final ReconnectPromise<S, L> p = new ReconnectPromise<>(GlobalEventExecutor.INSTANCE, this, address, connectStrategyFactory, b, initializer);
247
248         b.option(ChannelOption.SO_KEEPALIVE, true);
249
250         customizeBootstrap(b);
251         setWorkerGroup(b);
252         setChannelFactory(b);
253
254         p.connect();
255         return p;
256     }
257
258     private void setChannelFactory(final Bootstrap b) {
259         // There is no way to detect if this was already set by
260         // customizeBootstrap()
261         try {
262             b.channel(NioSocketChannel.class);
263         } catch (final IllegalStateException e) {
264             LOG.trace("Not overriding channelFactory on bootstrap {}", b, e);
265         }
266     }
267
268     /**
269      * @deprecated Should only be used with {@link AbstractDispatcher#AbstractDispatcher()}
270      */
271     @Deprecated
272     @Override
273     public void close() {
274     }
275 }