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