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 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;
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.
40 public abstract class AbstractDispatcher<S extends ProtocolSession<?>, L extends SessionListener<?, ?, ?>> implements Closeable {
43 protected interface ChannelPipelineInitializer<CH extends Channel, S extends ProtocolSession<?>> {
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.
48 * @param channel whose pipeline should be defined, also to be passed to {@link SessionNegotiatorFactory}
49 * @param promise to be passed to {@link SessionNegotiatorFactory}
51 void initializeChannel(CH channel, Promise<S> promise);
54 protected interface PipelineInitializer<S extends ProtocolSession<?>> extends ChannelPipelineInitializer<SocketChannel, S> {
59 private static final Logger LOG = LoggerFactory.getLogger(AbstractDispatcher.class);
61 private final EventLoopGroup bossGroup;
63 private final EventLoopGroup workerGroup;
65 private final EventExecutor executor;
67 protected AbstractDispatcher(final EventLoopGroup bossGroup, final EventLoopGroup workerGroup) {
68 this(GlobalEventExecutor.INSTANCE, bossGroup, workerGroup);
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);
79 * Creates server. Each server needs factories to pass their instances to client sessions.
81 * @param address address to which the server should be bound
82 * @param initializer instance of PipelineInitializer used to initialize the channel pipeline
84 * @return ChannelFuture representing the binding process
86 protected ChannelFuture createServer(final InetSocketAddress address, final PipelineInitializer<S> initializer) {
87 return createServer(address, NioServerSocketChannel.class, initializer);
91 * Creates server. Each server needs factories to pass their instances to client sessions.
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
97 * @return ChannelFuture representing the binding process
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>() {
105 protected void initChannel(final CH ch) {
106 initializer.initializeChannel(ch, new DefaultPromise<>(executor));
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);
116 b.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
117 customizeBootstrap(b);
119 if (b.group() == null) {
120 b.group(bossGroup, workerGroup);
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);
129 // Bind and start to accept incoming connections.
130 final ChannelFuture f = b.bind(address);
131 LOG.debug("Initiated server {} at {}.", f, address);
136 * Customize a server bootstrap before the server is created. This allows
137 * subclasses to assign non-default server options before the server is
140 * @param b Server bootstrap
142 protected void customizeBootstrap(final ServerBootstrap b) {
143 // The default is a no-op
149 * @param address remote address
150 * @param strategy Reconnection strategy to be used when initial connection fails
152 * @return Future representing the connection process. Its result represents the combined success of TCP connection
153 * as well as session negotiation.
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>() {
161 protected void initChannel(final SocketChannel ch) {
162 initializer.initializeChannel(ch, p);
166 customizeBootstrap(b);
168 setChannelFactory(b);
171 LOG.debug("Client created.");
175 private void setWorkerGroup(final Bootstrap b) {
176 if (b.group() == null) {
177 b.group(workerGroup);
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.
185 * @param address remote address
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);
191 new ChannelInitializer<SocketChannel>() {
193 protected void initChannel(final SocketChannel ch) {
194 initializer.initializeChannel(ch, p);
199 LOG.debug("Client created.");
204 * Customize a client bootstrap before the connection is attempted. This
205 * allows subclasses to assign non-default options before the client is
208 * @param b Client bootstrap
210 protected void customizeBootstrap(final Bootstrap b) {
211 // The default is a no-op
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.
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
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
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);
234 * Creates a reconnecting client.
236 * @param address remote address
237 * @param connectStrategyFactory Factory for creating reconnection strategy for every reconnect attempt
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.
242 protected Future<Void> createReconnectingClient(final InetSocketAddress address, final ReconnectStrategyFactory connectStrategyFactory,
243 final PipelineInitializer<S> initializer) {
244 final Bootstrap b = new Bootstrap();
246 final ReconnectPromise<S, L> p = new ReconnectPromise<>(GlobalEventExecutor.INSTANCE, this, address, connectStrategyFactory, b, initializer);
248 b.option(ChannelOption.SO_KEEPALIVE, true);
250 customizeBootstrap(b);
252 setChannelFactory(b);
258 private void setChannelFactory(final Bootstrap b) {
259 // There is no way to detect if this was already set by
260 // customizeBootstrap()
262 b.channel(NioSocketChannel.class);
263 } catch (final IllegalStateException e) {
264 LOG.trace("Not overriding channelFactory on bootstrap {}", b, e);
269 * @deprecated Should only be used with AbstractDispatcher#AbstractDispatcher()
273 public void close() {