2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.protocol.framework;
10 import java.io.Closeable;
11 import java.net.InetSocketAddress;
12 import java.net.SocketAddress;
14 import org.slf4j.Logger;
15 import org.slf4j.LoggerFactory;
17 import com.google.common.base.Preconditions;
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;
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.
43 public abstract class AbstractDispatcher<S extends ProtocolSession<?>, L extends SessionListener<?, ?, ?>> implements Closeable {
46 protected interface ChannelPipelineInitializer<CH extends Channel, S extends ProtocolSession<?>> {
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.
51 * @param channel whose pipeline should be defined, also to be passed to {@link SessionNegotiatorFactory}
52 * @param promise to be passed to {@link SessionNegotiatorFactory}
54 void initializeChannel(CH channel, Promise<S> promise);
57 protected interface PipelineInitializer<S extends ProtocolSession<?>> extends ChannelPipelineInitializer<SocketChannel, S> {
62 private static final Logger LOG = LoggerFactory.getLogger(AbstractDispatcher.class);
64 private final EventLoopGroup bossGroup;
66 private final EventLoopGroup workerGroup;
68 private final EventExecutor executor;
70 protected AbstractDispatcher(final EventLoopGroup bossGroup, final EventLoopGroup workerGroup) {
71 this(GlobalEventExecutor.INSTANCE, bossGroup, workerGroup);
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);
82 * Creates server. Each server needs factories to pass their instances to client sessions.
84 * @param address address to which the server should be bound
85 * @param initializer instance of PipelineInitializer used to initialize the channel pipeline
87 * @return ChannelFuture representing the binding process
89 protected ChannelFuture createServer(final InetSocketAddress address, final PipelineInitializer<S> initializer) {
90 return createServer(address, NioServerSocketChannel.class, initializer);
94 * Creates server. Each server needs factories to pass their instances to client sessions.
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
100 * @return ChannelFuture representing the binding process
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>() {
108 protected void initChannel(final CH ch) {
109 initializer.initializeChannel(ch, new DefaultPromise<S>(executor));
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);
119 b.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
120 customizeBootstrap(b);
122 if (b.group() == null) {
123 b.group(bossGroup, workerGroup);
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);
132 // Bind and start to accept incoming connections.
133 final ChannelFuture f = b.bind(address);
134 LOG.debug("Initiated server {} at {}.", f, address);
139 * Customize a server bootstrap before the server is created. This allows
140 * subclasses to assign non-default server options before the server is
143 * @param b Server bootstrap
145 protected void customizeBootstrap(final ServerBootstrap b) {
146 // The default is a no-op
152 * @param address remote address
153 * @param connectStrategy Reconnection strategy to be used when initial connection fails
155 * @return Future representing the connection process. Its result represents the combined success of TCP connection
156 * as well as session negotiation.
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>() {
164 protected void initChannel(final SocketChannel ch) {
165 initializer.initializeChannel(ch, p);
169 customizeBootstrap(b);
171 setChannelFactory(b);
174 LOG.debug("Client created.");
178 private void setWorkerGroup(final Bootstrap b) {
179 if (b.group() == null) {
180 b.group(workerGroup);
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.
188 * @param address remote address
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);
194 new ChannelInitializer<SocketChannel>() {
196 protected void initChannel(final SocketChannel ch) {
197 initializer.initializeChannel(ch, p);
202 LOG.debug("Client created.");
207 * Customize a client bootstrap before the connection is attempted. This
208 * allows subclasses to assign non-default options before the client is
211 * @param b Client bootstrap
213 protected void customizeBootstrap(final Bootstrap b) {
214 // The default is a no-op
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.
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
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
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);
237 * Creates a reconnecting client.
239 * @param address remote address
240 * @param connectStrategyFactory Factory for creating reconnection strategy for every reconnect attempt
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.
245 protected Future<Void> createReconnectingClient(final InetSocketAddress address, final ReconnectStrategyFactory connectStrategyFactory,
246 final PipelineInitializer<S> initializer) {
247 final Bootstrap b = new Bootstrap();
249 final ReconnectPromise<S, L> p = new ReconnectPromise<>(GlobalEventExecutor.INSTANCE, this, address, connectStrategyFactory, b, initializer);
251 b.option(ChannelOption.SO_KEEPALIVE, true);
253 customizeBootstrap(b);
255 setChannelFactory(b);
261 private void setChannelFactory(final Bootstrap b) {
262 // There is no way to detect if this was already set by
263 // customizeBootstrap()
265 b.channel(NioSocketChannel.class);
266 } catch (final IllegalStateException e) {
267 LOG.trace("Not overriding channelFactory on bootstrap {}", b, e);
272 * @deprecated Should only be used with {@link AbstractDispatcher#AbstractDispatcher()}
276 public void close() {
278 this.workerGroup.shutdownGracefully();
280 this.bossGroup.shutdownGracefully();