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