Merge "Initial message bus implementation"
[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         }
118         b.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
119         customizeBootstrap(b);
120
121         if (b.group() == null) {
122             b.group(bossGroup, workerGroup);
123         }
124         try {
125             b.channel(channelClass);
126         } catch (IllegalStateException e) {
127             // FIXME: if this is ok, document why
128             LOG.trace("Not overriding channelFactory on bootstrap {}", b, e);
129         }
130
131         // Bind and start to accept incoming connections.
132         final ChannelFuture f = b.bind(address);
133         LOG.debug("Initiated server {} at {}.", f, address);
134         return f;
135     }
136
137     /**
138      * Customize a server bootstrap before the server is created. This allows
139      * subclasses to assign non-default server options before the server is
140      * created.
141      *
142      * @param b Server bootstrap
143      */
144     protected void customizeBootstrap(final ServerBootstrap b) {
145         // The default is a no-op
146     }
147
148     /**
149      * Creates a client.
150      *
151      * @param address remote address
152      * @param connectStrategy Reconnection strategy to be used when initial connection fails
153      *
154      * @return Future representing the connection process. Its result represents the combined success of TCP connection
155      *         as well as session negotiation.
156      */
157     protected Future<S> createClient(final InetSocketAddress address, final ReconnectStrategy strategy, final PipelineInitializer<S> initializer) {
158         final Bootstrap b = new Bootstrap();
159         final ProtocolSessionPromise<S> p = new ProtocolSessionPromise<>(executor, address, strategy, b);
160         b.option(ChannelOption.SO_KEEPALIVE, true).handler(
161                 new ChannelInitializer<SocketChannel>() {
162                     @Override
163                     protected void initChannel(final SocketChannel ch) {
164                         initializer.initializeChannel(ch, p);
165                     }
166                 });
167
168         customizeBootstrap(b);
169         setWorkerGroup(b);
170         setChannelFactory(b);
171
172         p.connect();
173         LOG.debug("Client created.");
174         return p;
175     }
176
177     private void setWorkerGroup(final Bootstrap b) {
178         if (b.group() == null) {
179             b.group(workerGroup);
180         }
181     }
182
183     /**
184      * Create a client but use a pre-configured bootstrap.
185      * This method however replaces the ChannelInitializer in the bootstrap. All other configuration is preserved.
186      *
187      * @param address remote address
188      */
189     protected Future<S> createClient(final InetSocketAddress address, final ReconnectStrategy strategy, final Bootstrap bootstrap, final PipelineInitializer<S> initializer) {
190         final ProtocolSessionPromise<S> p = new ProtocolSessionPromise<>(executor, address, strategy, bootstrap);
191
192         bootstrap.handler(
193                 new ChannelInitializer<SocketChannel>() {
194                     @Override
195                     protected void initChannel(final SocketChannel ch) {
196                         initializer.initializeChannel(ch, p);
197                     }
198                 });
199
200         p.connect();
201         LOG.debug("Client created.");
202         return p;
203     }
204
205     /**
206      * Customize a client bootstrap before the connection is attempted. This
207      * allows subclasses to assign non-default options before the client is
208      * created.
209      *
210      * @param b Client bootstrap
211      */
212     protected void customizeBootstrap(final Bootstrap b) {
213         // The default is a no-op
214     }
215
216     /**
217      *
218      * @deprecated use {@link org.opendaylight.protocol.framework.AbstractDispatcher#createReconnectingClient(java.net.InetSocketAddress, ReconnectStrategyFactory, org.opendaylight.protocol.framework.AbstractDispatcher.PipelineInitializer)} with only one reconnectStrategyFactory instead.
219      *
220      * Creates a client.
221      *
222      * @param address remote address
223      * @param connectStrategyFactory Factory for creating reconnection strategy to be used when initial connection fails
224      * @param reestablishStrategy Reconnection strategy to be used when the already-established session fails
225      *
226      * @return Future representing the reconnection task. It will report completion based on reestablishStrategy, e.g.
227      *         success if it indicates no further attempts should be made and failure if it reports an error
228      */
229     @Deprecated
230     protected Future<Void> createReconnectingClient(final InetSocketAddress address, final ReconnectStrategyFactory connectStrategyFactory,
231             final ReconnectStrategy reestablishStrategy, final PipelineInitializer<S> initializer) {
232         return createReconnectingClient(address, connectStrategyFactory, initializer);
233     }
234
235     /**
236      * Creates a reconnecting client.
237      *
238      * @param address remote address
239      * @param connectStrategyFactory Factory for creating reconnection strategy for every reconnect attempt
240      *
241      * @return Future representing the reconnection task. It will report completion based on reestablishStrategy, e.g.
242      *         success is never reported, only failure when it runs out of reconnection attempts.
243      */
244     protected Future<Void> createReconnectingClient(final InetSocketAddress address, final ReconnectStrategyFactory connectStrategyFactory,
245             final PipelineInitializer<S> initializer) {
246         final Bootstrap b = new Bootstrap();
247
248         final ReconnectPromise<S, L> p = new ReconnectPromise<>(GlobalEventExecutor.INSTANCE, this, address, connectStrategyFactory, b, initializer);
249
250         b.option(ChannelOption.SO_KEEPALIVE, true);
251
252         customizeBootstrap(b);
253         setWorkerGroup(b);
254         setChannelFactory(b);
255
256         p.connect();
257         return p;
258     }
259
260     private void setChannelFactory(final Bootstrap b) {
261         // There is no way to detect if this was already set by
262         // customizeBootstrap()
263         try {
264             b.channel(NioSocketChannel.class);
265         } catch (final IllegalStateException e) {
266             LOG.trace("Not overriding channelFactory on bootstrap {}", b, e);
267         }
268     }
269
270     /**
271      * @deprecated Should only be used with {@link AbstractDispatcher#AbstractDispatcher()}
272      */
273     @Deprecated
274     @Override
275     public void close() {
276         try {
277             this.workerGroup.shutdownGracefully();
278         } finally {
279             this.bossGroup.shutdownGracefully();
280         }
281     }
282 }