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.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;
21 import java.net.InetAddress;
22 import java.net.InetSocketAddress;
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;
31 import com.google.common.util.concurrent.ListenableFuture;
32 import com.google.common.util.concurrent.SettableFuture;
35 * Class implementing server over TCP for handling incoming connections.
37 * @author michal.polkorab
39 public class TcpHandler implements ServerFacade {
41 * High/low write watermarks, in KiB.
43 private static final int DEFAULT_WRITE_HIGH_WATERMARK = 64;
44 private static final int DEFAULT_WRITE_LOW_WATERMARK = 32;
46 * Write spin count. This tells netty to immediately retry a non-blocking
47 * write this many times before moving on to selecting.
49 private static final int DEFAULT_WRITE_SPIN_COUNT = 16;
51 private static final Logger LOGGER = LoggerFactory.getLogger(TcpHandler.class);
54 private String address;
55 private final InetAddress startupAddress;
56 private NioEventLoopGroup workerGroup;
57 private NioEventLoopGroup bossGroup;
58 private final SettableFuture<Boolean> isOnlineFuture;
60 private final PublishingChannelInitializer channelInitializer;
63 * Enum used for storing names of used components (in pipeline).
65 public static enum COMPONENT_NAMES {
68 * Detects switch idle state
72 * Detects TLS connections
76 * Component for handling TLS frames
80 * Decodes incoming messages into message frames
84 * Detects version of incoming OpenFlow Protocol message
88 * Transforms OpenFlow Protocol byte messages into POJOs
92 * Transforms POJOs into OpenFlow Protocol byte messages
96 * Delegates translated POJOs into MessageConsumer
98 DELEGATING_INBOUND_HANDLER,
103 * Constructor of TCPHandler that listens on selected port.
105 * @param port listening port of TCPHandler server
107 public TcpHandler(final int port) {
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
116 public TcpHandler(final InetAddress address, final int port) {
118 this.startupAddress = address;
119 channelInitializer = new PublishingChannelInitializer();
120 isOnlineFuture = SettableFuture.create();
124 * Starts server on selected port.
128 bossGroup = new NioEventLoopGroup();
129 workerGroup = new NioEventLoopGroup();
132 * We generally do not perform IO-unrelated tasks, so we want to have
133 * all outstanding tasks completed before the executing thread goes
136 * Any other setting means netty will measure the time it spent selecting
137 * and spend roughly proportional time executing tasks.
139 workerGroup.setIoRatio(100);
141 final ChannelFuture f;
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);
156 if (startupAddress != null) {
157 f = b.bind(startupAddress.getHostAddress(), port).sync();
159 f = b.bind(port).sync();
161 } catch (InterruptedException e) {
162 LOGGER.error("Interrupted while binding port {}", port, e);
167 InetSocketAddress isa = (InetSocketAddress) f.channel().localAddress();
168 address = isa.getHostString();
170 // Update port, as it may have been specified as 0
171 this.port = isa.getPort();
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);
185 * Shuts down {@link TcpHandler}}
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>>() {
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());
209 * @return number of connected clients / channels
211 public int getNumberOfConnections() {
212 return channelInitializer.size();
216 * @return channelInitializer providing channels
218 public PublishingChannelInitializer getChannelInitializer() {
219 return channelInitializer;
223 public ListenableFuture<Boolean> getIsOnlineFuture() {
224 return isOnlineFuture;
230 public int getPort() {
235 * @return the address
237 public String getAddress() {
242 * @param switchConnectionHandler
244 public void setSwitchConnectionHandler(
245 final SwitchConnectionHandler switchConnectionHandler) {
246 channelInitializer.setSwitchConnectionHandler(switchConnectionHandler);
250 * @param switchIdleTimeout in milliseconds
252 public void setSwitchIdleTimeout(final long switchIdleTimeout) {
253 channelInitializer.setSwitchIdleTimeout(switchIdleTimeout);
257 * @param tlsSupported
259 public void setEncryption(final boolean tlsSupported) {
260 channelInitializer.setEncryption(tlsSupported);
264 * @param sf serialization factory
266 public void setSerializationFactory(final SerializationFactory sf) {
267 channelInitializer.setSerializationFactory(sf);
273 public void setDeserializationFactory(final DeserializationFactory factory) {
274 channelInitializer.setDeserializationFactory(factory);