Started using pooled buffers
[openflowjava.git] / openflow-protocol-impl / src / main / java / org / opendaylight / openflowjava / protocol / impl / core / TcpHandler.java
1 /*
2  * Copyright (c) 2013 Pantheon Technologies s.r.o. 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
9 package org.opendaylight.openflowjava.protocol.impl.core;
10
11 import io.netty.bootstrap.ServerBootstrap;
12 import io.netty.buffer.PooledByteBufAllocator;
13 import io.netty.channel.ChannelFuture;
14 import io.netty.channel.ChannelOption;
15 import io.netty.channel.nio.NioEventLoopGroup;
16 import io.netty.channel.socket.nio.NioServerSocketChannel;
17 import io.netty.handler.logging.LogLevel;
18 import io.netty.handler.logging.LoggingHandler;
19 import io.netty.util.concurrent.GenericFutureListener;
20
21 import java.net.InetAddress;
22 import java.net.InetSocketAddress;
23
24 import org.opendaylight.openflowjava.protocol.api.connection.SwitchConnectionHandler;
25 import org.opendaylight.openflowjava.protocol.impl.connection.ServerFacade;
26 import org.opendaylight.openflowjava.protocol.impl.deserialization.DeserializationFactory;
27 import org.opendaylight.openflowjava.protocol.impl.serialization.SerializationFactory;
28 import org.slf4j.Logger;
29 import org.slf4j.LoggerFactory;
30
31 import com.google.common.util.concurrent.ListenableFuture;
32 import com.google.common.util.concurrent.SettableFuture;
33
34 /**
35  * Class implementing server over TCP for handling incoming connections.
36  *
37  * @author michal.polkorab
38  */
39 public class TcpHandler implements ServerFacade {
40     /*
41      * High/low write watermarks, in KiB.
42      */
43     private static final int DEFAULT_WRITE_HIGH_WATERMARK = 64;
44     private static final int DEFAULT_WRITE_LOW_WATERMARK = 32;
45     /*
46      * Write spin count. This tells netty to immediately retry a non-blocking
47      * write this many times before moving on to selecting.
48      */
49     private static final int DEFAULT_WRITE_SPIN_COUNT = 16;
50
51     private static final Logger LOGGER = LoggerFactory.getLogger(TcpHandler.class);
52
53     private int port;
54     private String address;
55     private final InetAddress startupAddress;
56     private NioEventLoopGroup workerGroup;
57     private NioEventLoopGroup bossGroup;
58     private final SettableFuture<Boolean> isOnlineFuture;
59
60     private final PublishingChannelInitializer channelInitializer;
61
62     /**
63      * Enum used for storing names of used components (in pipeline).
64      */
65     public static enum COMPONENT_NAMES {
66
67         /**
68          * Detects switch idle state
69          */
70         IDLE_HANDLER,
71         /**
72          * Detects TLS connections
73          */
74         TLS_DETECTOR,
75         /**
76          * Component for handling TLS frames
77          */
78         SSL_HANDLER,
79         /**
80          * Decodes incoming messages into message frames
81          */
82         OF_FRAME_DECODER,
83         /**
84          * Detects version of incoming OpenFlow Protocol message
85          */
86         OF_VERSION_DETECTOR,
87         /**
88          * Transforms OpenFlow Protocol byte messages into POJOs
89          */
90         OF_DECODER,
91         /**
92          * Transforms POJOs into OpenFlow Protocol byte messages
93          */
94         OF_ENCODER,
95         /**
96          * Delegates translated POJOs into MessageConsumer
97          */
98         DELEGATING_INBOUND_HANDLER,
99     }
100
101
102     /**
103      * Constructor of TCPHandler that listens on selected port.
104      *
105      * @param port listening port of TCPHandler server
106      */
107     public TcpHandler(final int port) {
108         this(null, port);
109     }
110
111     /**
112      * Constructor of TCPHandler that listens on selected address and port.
113      * @param address listening address of TCPHandler server
114      * @param port listening port of TCPHandler server
115      */
116     public TcpHandler(final InetAddress address, final int port) {
117         this.port = port;
118         this.startupAddress = address;
119         channelInitializer = new PublishingChannelInitializer();
120         isOnlineFuture = SettableFuture.create();
121     }
122
123     /**
124      * Starts server on selected port.
125      */
126     @Override
127     public void run() {
128         bossGroup = new NioEventLoopGroup();
129         workerGroup = new NioEventLoopGroup();
130
131         /*
132          * We generally do not perform IO-unrelated tasks, so we want to have
133          * all outstanding tasks completed before the executing thread goes
134          * back into select.
135          *
136          * Any other setting means netty will measure the time it spent selecting
137          * and spend roughly proportional time executing tasks.
138          */
139         workerGroup.setIoRatio(100);
140
141         final ChannelFuture f;
142         try {
143             ServerBootstrap b = new ServerBootstrap();
144             b.group(bossGroup, workerGroup)
145                     .channel(NioServerSocketChannel.class)
146                     .handler(new LoggingHandler(LogLevel.DEBUG))
147                     .childHandler(channelInitializer)
148                     .option(ChannelOption.SO_BACKLOG, 128)
149                     .option(ChannelOption.SO_REUSEADDR, true)
150                     .childOption(ChannelOption.SO_KEEPALIVE, true)
151                     .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
152                     .childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, DEFAULT_WRITE_HIGH_WATERMARK * 1024)
153                     .childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, DEFAULT_WRITE_LOW_WATERMARK * 1024)
154                     .childOption(ChannelOption.WRITE_SPIN_COUNT, DEFAULT_WRITE_SPIN_COUNT);
155
156             if (startupAddress != null) {
157                 f = b.bind(startupAddress.getHostAddress(), port).sync();
158             } else {
159                 f = b.bind(port).sync();
160             }
161         } catch (InterruptedException e) {
162             LOGGER.error("Interrupted while binding port {}", port, e);
163             return;
164         }
165
166         try {
167             InetSocketAddress isa = (InetSocketAddress) f.channel().localAddress();
168             address = isa.getHostString();
169
170             // Update port, as it may have been specified as 0
171             this.port = isa.getPort();
172
173             LOGGER.debug("address from tcphandler: {}", address);
174             isOnlineFuture.set(true);
175             LOGGER.info("Switch listener started and ready to accept incoming connections on port: {}", port);
176             f.channel().closeFuture().sync();
177         } catch (InterruptedException e) {
178             LOGGER.error("Interrupted while waiting for port {} shutdown", port, e);
179         } finally {
180             shutdown();
181         }
182     }
183
184     /**
185      * Shuts down {@link TcpHandler}}
186      */
187     @Override
188     public ListenableFuture<Boolean> shutdown() {
189         final SettableFuture<Boolean> result = SettableFuture.create();
190         workerGroup.shutdownGracefully();
191         // boss will shutdown as soon, as worker is down
192         bossGroup.shutdownGracefully().addListener(new GenericFutureListener<io.netty.util.concurrent.Future<Object>>() {
193
194             @Override
195             public void operationComplete(
196                     final io.netty.util.concurrent.Future<Object> downResult) throws Exception {
197                 result.set(downResult.isSuccess());
198                 if (downResult.cause() != null) {
199                     result.setException(downResult.cause());
200                 }
201             }
202
203         });
204         return result;
205     }
206
207     /**
208      *
209      * @return number of connected clients / channels
210      */
211     public int getNumberOfConnections() {
212         return channelInitializer.size();
213     }
214
215     /**
216      * @return channelInitializer providing channels
217      */
218     public PublishingChannelInitializer getChannelInitializer() {
219         return channelInitializer;
220     }
221
222     @Override
223     public ListenableFuture<Boolean> getIsOnlineFuture() {
224         return isOnlineFuture;
225     }
226
227     /**
228      * @return the port
229      */
230     public int getPort() {
231         return port;
232     }
233
234     /**
235      * @return the address
236      */
237     public String getAddress() {
238         return address;
239     }
240
241     /**
242      * @param switchConnectionHandler
243      */
244     public void setSwitchConnectionHandler(
245             final SwitchConnectionHandler switchConnectionHandler) {
246         channelInitializer.setSwitchConnectionHandler(switchConnectionHandler);
247     }
248
249     /**
250      * @param switchIdleTimeout in milliseconds
251      */
252     public void setSwitchIdleTimeout(final long switchIdleTimeout) {
253         channelInitializer.setSwitchIdleTimeout(switchIdleTimeout);
254     }
255
256     /**
257      * @param tlsSupported
258      */
259     public void setEncryption(final boolean tlsSupported) {
260         channelInitializer.setEncryption(tlsSupported);
261     }
262
263     /**
264      * @param sf serialization factory
265      */
266     public void setSerializationFactory(final SerializationFactory sf) {
267         channelInitializer.setSerializationFactory(sf);
268     }
269
270     /**
271      * @param factory
272      */
273     public void setDeserializationFactory(final DeserializationFactory factory) {
274         channelInitializer.setDeserializationFactory(factory);
275     }
276
277 }