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.channel.Channel;
14 import io.netty.channel.ChannelFuture;
15 import io.netty.channel.ChannelInitializer;
16 import io.netty.channel.ChannelOption;
17 import io.netty.channel.EventLoopGroup;
18 import io.netty.channel.ServerChannel;
19 import io.netty.channel.local.LocalServerChannel;
20 import io.netty.channel.socket.SocketChannel;
21 import io.netty.channel.socket.nio.NioServerSocketChannel;
22 import io.netty.channel.socket.nio.NioSocketChannel;
23 import io.netty.util.concurrent.DefaultPromise;
24 import io.netty.util.concurrent.EventExecutor;
25 import io.netty.util.concurrent.Future;
26 import io.netty.util.concurrent.GlobalEventExecutor;
27 import io.netty.util.concurrent.Promise;
28 import java.io.Closeable;
29 import java.net.InetSocketAddress;
30 import java.net.SocketAddress;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
35 * Dispatcher class for creating servers and clients. The idea is to first create servers and clients and the run the
36 * start method that will handle sockets in different thread.
38 public abstract class AbstractDispatcher<S extends ProtocolSession<?>, L extends SessionListener<?, ?, ?>> implements Closeable {
41 protected interface ChannelPipelineInitializer<CH extends Channel, S extends ProtocolSession<?>> {
43 * Initializes channel by specifying the handlers in its pipeline. Handlers are protocol specific, therefore this
44 * method needs to be implemented in protocol specific Dispatchers.
46 * @param channel whose pipeline should be defined, also to be passed to {@link SessionNegotiatorFactory}
47 * @param promise to be passed to {@link SessionNegotiatorFactory}
49 void initializeChannel(CH channel, Promise<S> promise);
52 protected interface PipelineInitializer<S extends ProtocolSession<?>> extends ChannelPipelineInitializer<SocketChannel, S> {
57 private static final Logger LOG = LoggerFactory.getLogger(AbstractDispatcher.class);
59 private final EventLoopGroup bossGroup;
61 private final EventLoopGroup workerGroup;
63 private final EventExecutor executor;
65 protected AbstractDispatcher(final EventLoopGroup bossGroup, final EventLoopGroup workerGroup) {
66 this(GlobalEventExecutor.INSTANCE, bossGroup, workerGroup);
69 protected AbstractDispatcher(final EventExecutor executor, final EventLoopGroup bossGroup, final EventLoopGroup workerGroup) {
70 this.bossGroup = Preconditions.checkNotNull(bossGroup);
71 this.workerGroup = Preconditions.checkNotNull(workerGroup);
72 this.executor = Preconditions.checkNotNull(executor);
77 * Creates server. Each server needs factories to pass their instances to client sessions.
79 * @param address address to which the server should be bound
80 * @param initializer instance of PipelineInitializer used to initialize the channel pipeline
82 * @return ChannelFuture representing the binding process
84 protected ChannelFuture createServer(final InetSocketAddress address, final PipelineInitializer<S> initializer) {
85 return createServer(address, NioServerSocketChannel.class, initializer);
89 * Creates server. Each server needs factories to pass their instances to client sessions.
91 * @param address address to which the server should be bound
92 * @param channelClass The {@link Class} which is used to create {@link Channel} instances from.
93 * @param initializer instance of PipelineInitializer used to initialize the channel pipeline
95 * @return ChannelFuture representing the binding process
97 protected <CH extends Channel> ChannelFuture createServer(SocketAddress address, Class<? extends ServerChannel> channelClass,
98 final ChannelPipelineInitializer<CH, S> initializer) {
99 final ServerBootstrap b = new ServerBootstrap();
100 b.childHandler(new ChannelInitializer<CH>() {
103 protected void initChannel(final CH ch) {
104 initializer.initializeChannel(ch, new DefaultPromise<S>(executor));
108 b.option(ChannelOption.SO_BACKLOG, 128);
109 if (LocalServerChannel.class.equals(channelClass) == false) {
110 // makes no sense for LocalServer and produces warning
111 b.childOption(ChannelOption.SO_KEEPALIVE, true);
113 customizeBootstrap(b);
115 if (b.group() == null) {
116 b.group(bossGroup, workerGroup);
119 b.channel(channelClass);
120 } catch (IllegalStateException e) {
121 // FIXME: if this is ok, document why
122 LOG.trace("Not overriding channelFactory on bootstrap {}", b, e);
125 // Bind and start to accept incoming connections.
126 final ChannelFuture f = b.bind(address);
127 LOG.debug("Initiated server {} at {}.", f, address);
132 * Customize a server bootstrap before the server is created. This allows
133 * subclasses to assign non-default server options before the server is
136 * @param b Server bootstrap
138 protected void customizeBootstrap(final ServerBootstrap b) {
139 // The default is a no-op
145 * @param address remote address
146 * @param connectStrategy Reconnection strategy to be used when initial connection fails
148 * @return Future representing the connection process. Its result represents the combined success of TCP connection
149 * as well as session negotiation.
151 protected Future<S> createClient(final InetSocketAddress address, final ReconnectStrategy strategy, final PipelineInitializer<S> initializer) {
152 final Bootstrap b = new Bootstrap();
153 final ProtocolSessionPromise<S> p = new ProtocolSessionPromise<S>(executor, address, strategy, b);
154 b.group(this.workerGroup).channel(NioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true).handler(
155 new ChannelInitializer<SocketChannel>() {
158 protected void initChannel(final SocketChannel ch) {
159 initializer.initializeChannel(ch, p);
163 customizeBootstrap(b);
166 LOG.debug("Client created.");
171 * Customize a client bootstrap before the connection is attempted. This
172 * allows subclasses to assign non-default options before the client is
175 * @param b Client bootstrap
177 protected void customizeBootstrap(final Bootstrap b) {
178 // The default is a no-op
184 * @param address remote address
185 * @param connectStrategyFactory Factory for creating reconnection strategy to be used when initial connection fails
186 * @param reestablishStrategy Reconnection strategy to be used when the already-established session fails
188 * @return Future representing the reconnection task. It will report completion based on reestablishStrategy, e.g.
189 * success if it indicates no further attempts should be made and failure if it reports an error
191 protected Future<Void> createReconnectingClient(final InetSocketAddress address, final ReconnectStrategyFactory connectStrategyFactory,
192 final ReconnectStrategy reestablishStrategy, final PipelineInitializer<S> initializer) {
194 final ReconnectPromise<S, L> p = new ReconnectPromise<S, L>(GlobalEventExecutor.INSTANCE, this, address, connectStrategyFactory, reestablishStrategy, initializer);
201 * @deprecated Should only be used with {@link AbstractDispatcher#AbstractDispatcher()}
205 public void close() {
207 this.workerGroup.shutdownGracefully();
209 this.bossGroup.shutdownGracefully();