Re-added config.version to config-module-archetype.
[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 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;
33
34 /**
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.
37  */
38 public abstract class AbstractDispatcher<S extends ProtocolSession<?>, L extends SessionListener<?, ?, ?>> implements Closeable {
39
40
41     protected interface ChannelPipelineInitializer<CH extends Channel, S extends ProtocolSession<?>> {
42         /**
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.
45          *
46          * @param channel whose pipeline should be defined, also to be passed to {@link SessionNegotiatorFactory}
47          * @param promise to be passed to {@link SessionNegotiatorFactory}
48          */
49         void initializeChannel(CH channel, Promise<S> promise);
50     }
51
52     protected interface PipelineInitializer<S extends ProtocolSession<?>> extends ChannelPipelineInitializer<SocketChannel, S> {
53
54     }
55
56
57     private static final Logger LOG = LoggerFactory.getLogger(AbstractDispatcher.class);
58
59     private final EventLoopGroup bossGroup;
60
61     private final EventLoopGroup workerGroup;
62
63     private final EventExecutor executor;
64
65     protected AbstractDispatcher(final EventLoopGroup bossGroup, final EventLoopGroup workerGroup) {
66         this(GlobalEventExecutor.INSTANCE, bossGroup, workerGroup);
67     }
68
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);
73     }
74
75
76     /**
77      * Creates server. Each server needs factories to pass their instances to client sessions.
78      *
79      * @param address address to which the server should be bound
80      * @param initializer instance of PipelineInitializer used to initialize the channel pipeline
81      *
82      * @return ChannelFuture representing the binding process
83      */
84     protected ChannelFuture createServer(final InetSocketAddress address, final PipelineInitializer<S> initializer) {
85         return createServer(address, NioServerSocketChannel.class, initializer);
86     }
87
88     /**
89      * Creates server. Each server needs factories to pass their instances to client sessions.
90      *
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
94      *
95      * @return ChannelFuture representing the binding process
96      */
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>() {
101
102             @Override
103             protected void initChannel(final CH ch) {
104                 initializer.initializeChannel(ch, new DefaultPromise<S>(executor));
105             }
106         });
107
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);
112         }
113         customizeBootstrap(b);
114
115         if (b.group() == null) {
116             b.group(bossGroup, workerGroup);
117         }
118         try {
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);
123         }
124
125         // Bind and start to accept incoming connections.
126         final ChannelFuture f = b.bind(address);
127         LOG.debug("Initiated server {} at {}.", f, address);
128         return f;
129     }
130
131     /**
132      * Customize a server bootstrap before the server is created. This allows
133      * subclasses to assign non-default server options before the server is
134      * created.
135      *
136      * @param b Server bootstrap
137      */
138     protected void customizeBootstrap(final ServerBootstrap b) {
139         // The default is a no-op
140     }
141
142     /**
143      * Creates a client.
144      *
145      * @param address remote address
146      * @param connectStrategy Reconnection strategy to be used when initial connection fails
147      *
148      * @return Future representing the connection process. Its result represents the combined success of TCP connection
149      *         as well as session negotiation.
150      */
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>() {
156
157                     @Override
158                     protected void initChannel(final SocketChannel ch) {
159                         initializer.initializeChannel(ch, p);
160                     }
161                 });
162
163         customizeBootstrap(b);
164
165         p.connect();
166         LOG.debug("Client created.");
167         return p;
168     }
169
170     /**
171      * Customize a client bootstrap before the connection is attempted. This
172      * allows subclasses to assign non-default options before the client is
173      * created.
174      *
175      * @param b Client bootstrap
176      */
177     protected void customizeBootstrap(final Bootstrap b) {
178         // The default is a no-op
179     }
180
181     /**
182      * Creates a client.
183      *
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
187      *
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
190      */
191     protected Future<Void> createReconnectingClient(final InetSocketAddress address, final ReconnectStrategyFactory connectStrategyFactory,
192             final ReconnectStrategy reestablishStrategy, final PipelineInitializer<S> initializer) {
193
194         final ReconnectPromise<S, L> p = new ReconnectPromise<S, L>(GlobalEventExecutor.INSTANCE, this, address, connectStrategyFactory, reestablishStrategy, initializer);
195         p.connect();
196
197         return p;
198     }
199
200     /**
201      * @deprecated Should only be used with {@link AbstractDispatcher#AbstractDispatcher()}
202      */
203     @Deprecated
204     @Override
205     public void close() {
206         try {
207             this.workerGroup.shutdownGracefully();
208         } finally {
209             this.bossGroup.shutdownGracefully();
210         }
211     }
212
213 }