Merge "Bug 809: Enhancements to the toaster example"
[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 io.netty.bootstrap.Bootstrap;
11 import io.netty.bootstrap.ServerBootstrap;
12 import io.netty.channel.ChannelFuture;
13 import io.netty.channel.ChannelInitializer;
14 import io.netty.channel.ChannelOption;
15 import io.netty.channel.EventLoopGroup;
16 import io.netty.channel.socket.SocketChannel;
17 import io.netty.channel.socket.nio.NioServerSocketChannel;
18 import io.netty.channel.socket.nio.NioSocketChannel;
19 import io.netty.util.concurrent.DefaultPromise;
20 import io.netty.util.concurrent.EventExecutor;
21 import io.netty.util.concurrent.Future;
22 import io.netty.util.concurrent.GlobalEventExecutor;
23 import io.netty.util.concurrent.Promise;
24
25 import java.io.Closeable;
26 import java.net.InetSocketAddress;
27
28 import org.slf4j.Logger;
29 import org.slf4j.LoggerFactory;
30
31 import com.google.common.base.Preconditions;
32
33 /**
34  * Dispatcher class for creating servers and clients. The idea is to first create servers and clients and the run the
35  * start method that will handle sockets in different thread.
36  */
37 public abstract class AbstractDispatcher<S extends ProtocolSession<?>, L extends SessionListener<?, ?, ?>> implements Closeable {
38
39     protected interface PipelineInitializer<S extends ProtocolSession<?>> {
40         /**
41          * Initializes channel by specifying the handlers in its pipeline. Handlers are protocol specific, therefore this
42          * method needs to be implemented in protocol specific Dispatchers.
43          *
44          * @param channel whose pipeline should be defined, also to be passed to {@link SessionNegotiatorFactory}
45          * @param promise to be passed to {@link SessionNegotiatorFactory}
46          */
47         void initializeChannel(SocketChannel channel, Promise<S> promise);
48     }
49
50
51     private static final Logger LOG = LoggerFactory.getLogger(AbstractDispatcher.class);
52
53     private final EventLoopGroup bossGroup;
54
55     private final EventLoopGroup workerGroup;
56
57     private final EventExecutor executor;
58
59     protected AbstractDispatcher(final EventLoopGroup bossGroup, final EventLoopGroup workerGroup) {
60         this(GlobalEventExecutor.INSTANCE, bossGroup, workerGroup);
61     }
62
63     protected AbstractDispatcher(final EventExecutor executor, final EventLoopGroup bossGroup, final EventLoopGroup workerGroup) {
64         this.bossGroup = Preconditions.checkNotNull(bossGroup);
65         this.workerGroup = Preconditions.checkNotNull(workerGroup);
66         this.executor = Preconditions.checkNotNull(executor);
67     }
68
69
70     /**
71      * Creates server. Each server needs factories to pass their instances to client sessions.
72      *
73      * @param address address to which the server should be bound
74      * @param initializer instance of PipelineInitializer used to initialize the channel pipeline
75      *
76      * @return ChannelFuture representing the binding process
77      */
78     protected ChannelFuture createServer(final InetSocketAddress address, final PipelineInitializer<S> initializer) {
79         final ServerBootstrap b = new ServerBootstrap();
80         b.childHandler(new ChannelInitializer<SocketChannel>() {
81
82             @Override
83             protected void initChannel(final SocketChannel ch) {
84                 initializer.initializeChannel(ch, new DefaultPromise<S>(executor));
85             }
86         });
87
88         b.option(ChannelOption.SO_BACKLOG, 128);
89         b.childOption(ChannelOption.SO_KEEPALIVE, true);
90         customizeBootstrap(b);
91
92         if (b.group() == null) {
93             b.group(bossGroup, workerGroup);
94         }
95         try {
96             b.channel(NioServerSocketChannel.class);
97         } catch (IllegalStateException e) {
98             LOG.trace("Not overriding channelFactory on bootstrap {}", b, e);
99         }
100
101         // Bind and start to accept incoming connections.
102         final ChannelFuture f = b.bind(address);
103         LOG.debug("Initiated server {} at {}.", f, address);
104         return f;
105     }
106
107     /**
108      * Customize a server bootstrap before the server is created. This allows
109      * subclasses to assign non-default server options before the server is
110      * created.
111      *
112      * @param b Server bootstrap
113      */
114     protected void customizeBootstrap(final ServerBootstrap b) {
115         // The default is a no-op
116     }
117
118     /**
119      * Creates a client.
120      *
121      * @param address remote address
122      * @param connectStrategy Reconnection strategy to be used when initial connection fails
123      *
124      * @return Future representing the connection process. Its result represents the combined success of TCP connection
125      *         as well as session negotiation.
126      */
127     protected Future<S> createClient(final InetSocketAddress address, final ReconnectStrategy strategy, final PipelineInitializer<S> initializer) {
128         final Bootstrap b = new Bootstrap();
129         final ProtocolSessionPromise<S> p = new ProtocolSessionPromise<S>(executor, address, strategy, b);
130         b.group(this.workerGroup).channel(NioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true).handler(
131                 new ChannelInitializer<SocketChannel>() {
132
133                     @Override
134                     protected void initChannel(final SocketChannel ch) {
135                         initializer.initializeChannel(ch, p);
136                     }
137                 });
138
139         customizeBootstrap(b);
140
141         p.connect();
142         LOG.debug("Client created.");
143         return p;
144     }
145
146     /**
147      * Customize a client bootstrap before the connection is attempted. This
148      * allows subclasses to assign non-default options before the client is
149      * created.
150      *
151      * @param b Client bootstrap
152      */
153     protected void customizeBootstrap(final Bootstrap b) {
154         // The default is a no-op
155     }
156
157     /**
158      * Creates a client.
159      *
160      * @param address remote address
161      * @param connectStrategyFactory Factory for creating reconnection strategy to be used when initial connection fails
162      * @param reestablishStrategy Reconnection strategy to be used when the already-established session fails
163      *
164      * @return Future representing the reconnection task. It will report completion based on reestablishStrategy, e.g.
165      *         success if it indicates no further attempts should be made and failure if it reports an error
166      */
167     protected Future<Void> createReconnectingClient(final InetSocketAddress address, final ReconnectStrategyFactory connectStrategyFactory,
168             final ReconnectStrategy reestablishStrategy, final PipelineInitializer<S> initializer) {
169
170         final ReconnectPromise<S, L> p = new ReconnectPromise<S, L>(GlobalEventExecutor.INSTANCE, this, address, connectStrategyFactory, reestablishStrategy, initializer);
171         p.connect();
172
173         return p;
174     }
175
176     /**
177      * @deprecated Should only be used with {@link AbstractDispatcher#AbstractDispatcher()}
178      */
179     @Deprecated
180     @Override
181     public void close() {
182         try {
183             this.workerGroup.shutdownGracefully();
184         } finally {
185             this.bossGroup.shutdownGracefully();
186         }
187     }
188
189 }