Use switch expression in FramingMechanismHandlerFactory
[netconf.git] / netconf / netconf-netty-util / src / main / java / org / opendaylight / netconf / nettyutil / AbstractNetconfDispatcher.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.netconf.nettyutil;
9
10 import static java.util.Objects.requireNonNull;
11
12 import io.netty.bootstrap.Bootstrap;
13 import io.netty.bootstrap.ServerBootstrap;
14 import io.netty.buffer.PooledByteBufAllocator;
15 import io.netty.channel.Channel;
16 import io.netty.channel.ChannelFuture;
17 import io.netty.channel.ChannelInitializer;
18 import io.netty.channel.ChannelOption;
19 import io.netty.channel.EventLoopGroup;
20 import io.netty.channel.ServerChannel;
21 import io.netty.channel.local.LocalServerChannel;
22 import io.netty.channel.socket.SocketChannel;
23 import io.netty.channel.socket.nio.NioServerSocketChannel;
24 import io.netty.channel.socket.nio.NioSocketChannel;
25 import io.netty.util.concurrent.DefaultPromise;
26 import io.netty.util.concurrent.EventExecutor;
27 import io.netty.util.concurrent.Future;
28 import io.netty.util.concurrent.GlobalEventExecutor;
29 import io.netty.util.concurrent.Promise;
30 import java.net.InetSocketAddress;
31 import java.net.SocketAddress;
32 import org.opendaylight.netconf.api.NetconfSession;
33 import org.opendaylight.netconf.api.NetconfSessionListener;
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 @Deprecated
42 public abstract class AbstractNetconfDispatcher<S extends NetconfSession, L extends NetconfSessionListener<? super S>> {
43     protected interface ChannelPipelineInitializer<C extends Channel, S extends NetconfSession> {
44         /**
45          * Initializes channel by specifying the handlers in its pipeline. Handlers are protocol specific, therefore
46          * this method needs to be implemented in protocol specific Dispatchers.
47          *
48          * @param channel whose pipeline should be defined, also to be passed to {@link NetconfSessionNegotiatorFactory}
49          * @param promise to be passed to {@link NetconfSessionNegotiatorFactory}
50          */
51         void initializeChannel(C channel, Promise<S> promise);
52     }
53
54     protected interface PipelineInitializer<S extends NetconfSession>
55         extends ChannelPipelineInitializer<SocketChannel, S> {
56
57     }
58
59     private static final Logger LOG = LoggerFactory.getLogger(AbstractNetconfDispatcher.class);
60
61     private final EventLoopGroup bossGroup;
62
63     private final EventLoopGroup workerGroup;
64
65     private final EventExecutor executor;
66
67     protected AbstractNetconfDispatcher(final EventLoopGroup bossGroup, final EventLoopGroup workerGroup) {
68         this(GlobalEventExecutor.INSTANCE, bossGroup, workerGroup);
69     }
70
71     protected AbstractNetconfDispatcher(final EventExecutor executor, final EventLoopGroup bossGroup,
72             final EventLoopGroup workerGroup) {
73         this.bossGroup = requireNonNull(bossGroup);
74         this.workerGroup = requireNonNull(workerGroup);
75         this.executor = requireNonNull(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 <C extends Channel> ChannelFuture createServer(final SocketAddress address,
101             final Class<? extends ServerChannel> channelClass, final ChannelPipelineInitializer<C, S> initializer) {
102         final ServerBootstrap b = new ServerBootstrap();
103         b.childHandler(new ChannelInitializer<C>() {
104
105             @Override
106             protected void initChannel(final C ch) {
107                 initializer.initializeChannel(ch, new DefaultPromise<>(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             b.childOption(ChannelOption.TCP_NODELAY , true);
116         }
117         b.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
118         customizeBootstrap(b);
119
120         if (b.group() == null) {
121             b.group(bossGroup, workerGroup);
122         }
123         try {
124             b.channel(channelClass);
125         } catch (final IllegalStateException e) {
126             // FIXME: if this is ok, document why
127             LOG.trace("Not overriding channelFactory on bootstrap {}", b, e);
128         }
129
130         // Bind and start to accept incoming connections.
131         final ChannelFuture f = b.bind(address);
132         LOG.debug("Initiated server {} at {}.", f, address);
133         return f;
134     }
135
136     /**
137      * Customize a server bootstrap before the server is created. This allows
138      * subclasses to assign non-default server options before the server is
139      * created.
140      *
141      * @param bootstrap Server bootstrap
142      */
143     protected void customizeBootstrap(final ServerBootstrap bootstrap) {
144         // The default is a no-op
145     }
146
147     /**
148      * Customize a client bootstrap before the connection is attempted. This
149      * allows subclasses to assign non-default options before the client is
150      * created.
151      *
152      * @param bootstrap Client bootstrap
153      */
154     protected void customizeBootstrap(final Bootstrap bootstrap) {
155         // The default is a no-op
156     }
157
158     /**
159      * Creates a client.
160      *
161      * @param address remote address
162      * @param strategy Reconnection strategy to be used when initial connection fails
163      *
164      * @return Future representing the connection process. Its result represents the combined success of TCP connection
165      *         as well as session negotiation.
166      */
167     protected Future<S> createClient(final InetSocketAddress address, final ReconnectStrategy strategy,
168             final PipelineInitializer<S> initializer) {
169         final Bootstrap b = new Bootstrap();
170         final NetconfSessionPromise<S> p = new NetconfSessionPromise<>(executor, address, strategy, b);
171         b.option(ChannelOption.SO_KEEPALIVE, true).handler(
172                 new ChannelInitializer<SocketChannel>() {
173                     @Override
174                     protected void initChannel(final SocketChannel ch) {
175                         initializer.initializeChannel(ch, p);
176                     }
177                 });
178
179         customizeBootstrap(b);
180         setWorkerGroup(b);
181         setChannelFactory(b);
182
183         p.connect();
184         LOG.debug("Client created.");
185         return p;
186     }
187
188     /**
189      * Create a client but use a pre-configured bootstrap.
190      * This method however replaces the ChannelInitializer in the bootstrap. All other configuration is preserved.
191      *
192      * @param address remote address
193      */
194     protected Future<S> createClient(final InetSocketAddress address, final ReconnectStrategy strategy,
195             final Bootstrap bootstrap, final PipelineInitializer<S> initializer) {
196         final NetconfSessionPromise<S> p = new NetconfSessionPromise<>(executor, address, strategy, bootstrap);
197
198         bootstrap.handler(
199                 new ChannelInitializer<SocketChannel>() {
200                     @Override
201                     protected void initChannel(final SocketChannel ch) {
202                         initializer.initializeChannel(ch, p);
203                     }
204                 });
205
206         p.connect();
207         LOG.debug("Client created.");
208         return p;
209     }
210
211     /**
212      * Creates a reconnecting client.
213      *
214      * @param address remote address
215      * @param connectStrategyFactory Factory for creating reconnection strategy for every reconnect attempt
216      * @return Future representing the reconnection task. It will report completion based on reestablishStrategy, e.g.
217      *         success is never reported, only failure when it runs out of reconnection attempts.
218      */
219     protected ReconnectFuture createReconnectingClient(final InetSocketAddress address,
220             final ReconnectStrategyFactory connectStrategyFactory, final PipelineInitializer<S> initializer) {
221         final Bootstrap b = new Bootstrap();
222
223         final ReconnectPromise<S, L> p = new ReconnectPromise<>(GlobalEventExecutor.INSTANCE, this, address,
224                 connectStrategyFactory, b, initializer);
225
226         b.option(ChannelOption.SO_KEEPALIVE, true);
227
228         customizeBootstrap(b);
229         setWorkerGroup(b);
230         setChannelFactory(b);
231
232         p.connect();
233         return p;
234     }
235
236     private static void setChannelFactory(final Bootstrap bootstrap) {
237         // There is no way to detect if this was already set by
238         // customizeBootstrap()
239         try {
240             bootstrap.channel(NioSocketChannel.class);
241         } catch (final IllegalStateException e) {
242             LOG.trace("Not overriding channelFactory on bootstrap {}", bootstrap, e);
243         }
244     }
245
246     private void setWorkerGroup(final Bootstrap bootstrap) {
247         if (bootstrap.group() == null) {
248             bootstrap.group(workerGroup);
249         }
250     }
251 }