2 * Copyright (c) 2013 Pantheon Technologies s.r.o. and others. All rights reserved.
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
9 package org.opendaylight.openflowjava.protocol.impl.core;
11 import io.netty.bootstrap.ServerBootstrap;
12 import io.netty.channel.ChannelFuture;
13 import io.netty.channel.ChannelOption;
14 import io.netty.channel.nio.NioEventLoopGroup;
15 import io.netty.channel.socket.nio.NioServerSocketChannel;
16 import io.netty.handler.logging.LogLevel;
17 import io.netty.handler.logging.LoggingHandler;
18 import io.netty.util.concurrent.GenericFutureListener;
20 import java.net.InetAddress;
21 import java.net.InetSocketAddress;
23 import org.opendaylight.openflowjava.protocol.api.connection.SwitchConnectionHandler;
24 import org.opendaylight.openflowjava.protocol.impl.connection.ServerFacade;
25 import org.opendaylight.openflowjava.protocol.impl.deserialization.DeserializationFactory;
26 import org.opendaylight.openflowjava.protocol.impl.serialization.SerializationFactory;
27 import org.slf4j.Logger;
28 import org.slf4j.LoggerFactory;
30 import com.google.common.util.concurrent.ListenableFuture;
31 import com.google.common.util.concurrent.SettableFuture;
34 * Class implementing server over TCP for handling incoming connections.
36 * @author michal.polkorab
38 public class TcpHandler implements ServerFacade {
40 * High/low write watermarks, in KiB.
42 private static final int DEFAULT_WRITE_HIGH_WATERMARK = 64;
43 private static final int DEFAULT_WRITE_LOW_WATERMARK = 32;
45 * Write spin count. This tells netty to immediately retry a non-blocking
46 * write this many times before moving on to selecting.
48 private static final int DEFAULT_WRITE_SPIN_COUNT = 16;
50 private static final Logger LOGGER = LoggerFactory.getLogger(TcpHandler.class);
53 private String address;
54 private final InetAddress startupAddress;
55 private NioEventLoopGroup workerGroup;
56 private NioEventLoopGroup bossGroup;
57 private final SettableFuture<Boolean> isOnlineFuture;
59 private final PublishingChannelInitializer channelInitializer;
62 * Enum used for storing names of used components (in pipeline).
64 public static enum COMPONENT_NAMES {
67 * Detects switch idle state
71 * Detects TLS connections
75 * Component for handling TLS frames
79 * Decodes incoming messages into message frames
83 * Detects version of incoming OpenFlow Protocol message
87 * Transforms OpenFlow Protocol byte messages into POJOs
91 * Transforms POJOs into OpenFlow Protocol byte messages
95 * Delegates translated POJOs into MessageConsumer
97 DELEGATING_INBOUND_HANDLER,
102 * Constructor of TCPHandler that listens on selected port.
104 * @param port listening port of TCPHandler server
106 public TcpHandler(final int port) {
111 * Constructor of TCPHandler that listens on selected address and port.
112 * @param address listening address of TCPHandler server
113 * @param port listening port of TCPHandler server
115 public TcpHandler(final InetAddress address, final int port) {
117 this.startupAddress = address;
118 channelInitializer = new PublishingChannelInitializer();
119 isOnlineFuture = SettableFuture.create();
123 * Starts server on selected port.
127 bossGroup = new NioEventLoopGroup();
128 workerGroup = new NioEventLoopGroup();
131 * We generally do not perform IO-unrelated tasks, so we want to have
132 * all outstanding tasks completed before the executing thread goes
135 * Any other setting means netty will measure the time it spent selecting
136 * and spend roughly proportional time executing tasks.
138 workerGroup.setIoRatio(100);
140 final ChannelFuture f;
142 ServerBootstrap b = new ServerBootstrap();
143 b.group(bossGroup, workerGroup)
144 .channel(NioServerSocketChannel.class)
145 .handler(new LoggingHandler(LogLevel.DEBUG))
146 .childHandler(channelInitializer)
147 .option(ChannelOption.SO_BACKLOG, 128)
148 .option(ChannelOption.SO_REUSEADDR, true)
149 .childOption(ChannelOption.SO_KEEPALIVE, true)
150 .childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, DEFAULT_WRITE_HIGH_WATERMARK * 1024)
151 .childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, DEFAULT_WRITE_LOW_WATERMARK * 1024)
152 .childOption(ChannelOption.WRITE_SPIN_COUNT, DEFAULT_WRITE_SPIN_COUNT);
154 if (startupAddress != null) {
155 f = b.bind(startupAddress.getHostAddress(), port).sync();
157 f = b.bind(port).sync();
159 } catch (InterruptedException e) {
160 LOGGER.error("Interrupted while binding port {}", port, e);
165 InetSocketAddress isa = (InetSocketAddress) f.channel().localAddress();
166 address = isa.getHostString();
168 // Update port, as it may have been specified as 0
169 this.port = isa.getPort();
171 LOGGER.debug("address from tcphandler: {}", address);
172 isOnlineFuture.set(true);
173 LOGGER.info("Switch listener started and ready to accept incoming connections on port: {}", port);
174 f.channel().closeFuture().sync();
175 } catch (InterruptedException e) {
176 LOGGER.error("Interrupted while waiting for port {} shutdown", port, e);
183 * Shuts down {@link TcpHandler}}
186 public ListenableFuture<Boolean> shutdown() {
187 final SettableFuture<Boolean> result = SettableFuture.create();
188 workerGroup.shutdownGracefully();
189 // boss will shutdown as soon, as worker is down
190 bossGroup.shutdownGracefully().addListener(new GenericFutureListener<io.netty.util.concurrent.Future<Object>>() {
193 public void operationComplete(
194 final io.netty.util.concurrent.Future<Object> downResult) throws Exception {
195 result.set(downResult.isSuccess());
196 if (downResult.cause() != null) {
197 result.setException(downResult.cause());
207 * @return number of connected clients / channels
209 public int getNumberOfConnections() {
210 return channelInitializer.size();
214 * @return channelInitializer providing channels
216 public PublishingChannelInitializer getChannelInitializer() {
217 return channelInitializer;
221 public ListenableFuture<Boolean> getIsOnlineFuture() {
222 return isOnlineFuture;
228 public int getPort() {
233 * @return the address
235 public String getAddress() {
240 * @param switchConnectionHandler
242 public void setSwitchConnectionHandler(
243 final SwitchConnectionHandler switchConnectionHandler) {
244 channelInitializer.setSwitchConnectionHandler(switchConnectionHandler);
248 * @param switchIdleTimeout in milliseconds
250 public void setSwitchIdleTimeout(final long switchIdleTimeout) {
251 channelInitializer.setSwitchIdleTimeout(switchIdleTimeout);
255 * @param tlsSupported
257 public void setEncryption(final boolean tlsSupported) {
258 channelInitializer.setEncryption(tlsSupported);
262 * @param sf serialization factory
264 public void setSerializationFactory(final SerializationFactory sf) {
265 channelInitializer.setSerializationFactory(sf);
271 public void setDeserializationFactory(final DeserializationFactory factory) {
272 channelInitializer.setDeserializationFactory(factory);