0c26354ea453557c1d6973d2b4d931040c0f93d6
[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.ThreadConfiguration;
25 import org.slf4j.Logger;
26 import org.slf4j.LoggerFactory;
27
28 import com.google.common.util.concurrent.ListenableFuture;
29 import com.google.common.util.concurrent.SettableFuture;
30
31 /**
32  * Class implementing server over TCP / TLS for handling incoming connections.
33  *
34  * @author michal.polkorab
35  */
36 public class TcpHandler implements ServerFacade {
37     /*
38      * High/low write watermarks, in KiB.
39      */
40     private static final int DEFAULT_WRITE_HIGH_WATERMARK = 64;
41     private static final int DEFAULT_WRITE_LOW_WATERMARK = 32;
42     /*
43      * Write spin count. This tells netty to immediately retry a non-blocking
44      * write this many times before moving on to selecting.
45      */
46     private static final int DEFAULT_WRITE_SPIN_COUNT = 16;
47
48     private static final Logger LOGGER = LoggerFactory.getLogger(TcpHandler.class);
49
50     private int port;
51     private String address;
52     private final InetAddress startupAddress;
53     private NioEventLoopGroup workerGroup;
54     private NioEventLoopGroup bossGroup;
55     private final SettableFuture<Boolean> isOnlineFuture;
56     private ThreadConfiguration threadConfig;
57
58     private TcpChannelInitializer channelInitializer;
59
60     /**
61      * Constructor of TCPHandler that listens on selected port.
62      *
63      * @param port listening port of TCPHandler server
64      */
65     public TcpHandler(final int port) {
66         this(null, port);
67     }
68
69     /**
70      * Constructor of TCPHandler that listens on selected address and port.
71      * @param address listening address of TCPHandler server
72      * @param port listening port of TCPHandler server
73      */
74     public TcpHandler(final InetAddress address, final int port) {
75         this.port = port;
76         this.startupAddress = address;
77         isOnlineFuture = SettableFuture.create();
78     }
79
80     /**
81      * Starts server on selected port.
82      */
83     @Override
84     public void run() {
85         if (threadConfig != null) {
86             bossGroup = new NioEventLoopGroup(threadConfig.getBossThreadCount());
87             workerGroup = new NioEventLoopGroup(threadConfig.getWorkerThreadCount());
88         } else {
89             bossGroup = new NioEventLoopGroup();
90             workerGroup = new NioEventLoopGroup();
91         }
92
93         /*
94          * We generally do not perform IO-unrelated tasks, so we want to have
95          * all outstanding tasks completed before the executing thread goes
96          * back into select.
97          *
98          * Any other setting means netty will measure the time it spent selecting
99          * and spend roughly proportional time executing tasks.
100          */
101         workerGroup.setIoRatio(100);
102
103         final ChannelFuture f;
104         try {
105             ServerBootstrap b = new ServerBootstrap();
106             b.group(bossGroup, workerGroup)
107                     .channel(NioServerSocketChannel.class)
108                     .handler(new LoggingHandler(LogLevel.DEBUG))
109                     .childHandler(channelInitializer)
110                     .option(ChannelOption.SO_BACKLOG, 128)
111                     .option(ChannelOption.SO_REUSEADDR, true)
112                     .childOption(ChannelOption.SO_KEEPALIVE, true)
113                     .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
114                     .childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, DEFAULT_WRITE_HIGH_WATERMARK * 1024)
115                     .childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, DEFAULT_WRITE_LOW_WATERMARK * 1024)
116                     .childOption(ChannelOption.WRITE_SPIN_COUNT, DEFAULT_WRITE_SPIN_COUNT);
117
118             if (startupAddress != null) {
119                 f = b.bind(startupAddress.getHostAddress(), port).sync();
120             } else {
121                 f = b.bind(port).sync();
122             }
123         } catch (InterruptedException e) {
124             LOGGER.error("Interrupted while binding port {}", port, e);
125             return;
126         }
127
128         try {
129             InetSocketAddress isa = (InetSocketAddress) f.channel().localAddress();
130             address = isa.getHostString();
131
132             // Update port, as it may have been specified as 0
133             this.port = isa.getPort();
134
135             LOGGER.debug("address from tcphandler: {}", address);
136             isOnlineFuture.set(true);
137             LOGGER.info("Switch listener started and ready to accept incoming tcp/tls connections on port: {}", port);
138             f.channel().closeFuture().sync();
139         } catch (InterruptedException e) {
140             LOGGER.error("Interrupted while waiting for port {} shutdown", port, e);
141         } finally {
142             shutdown();
143         }
144     }
145
146     /**
147      * Shuts down {@link TcpHandler}}
148      */
149     @Override
150     public ListenableFuture<Boolean> shutdown() {
151         final SettableFuture<Boolean> result = SettableFuture.create();
152         workerGroup.shutdownGracefully();
153         // boss will shutdown as soon, as worker is down
154         bossGroup.shutdownGracefully().addListener(new GenericFutureListener<io.netty.util.concurrent.Future<Object>>() {
155
156             @Override
157             public void operationComplete(
158                     final io.netty.util.concurrent.Future<Object> downResult) throws Exception {
159                 result.set(downResult.isSuccess());
160                 if (downResult.cause() != null) {
161                     result.setException(downResult.cause());
162                 }
163             }
164
165         });
166         return result;
167     }
168
169     /**
170      *
171      * @return number of connected clients / channels
172      */
173     public int getNumberOfConnections() {
174         return channelInitializer.size();
175     }
176
177     @Override
178     public ListenableFuture<Boolean> getIsOnlineFuture() {
179         return isOnlineFuture;
180     }
181
182     /**
183      * @return the port
184      */
185     public int getPort() {
186         return port;
187     }
188
189     /**
190      * @return the address
191      */
192     public String getAddress() {
193         return address;
194     }
195
196     /**
197      * @param channelInitializer
198      */
199     public void setChannelInitializer(TcpChannelInitializer channelInitializer) {
200         this.channelInitializer = channelInitializer;
201     }
202
203     @Override
204     public void setThreadConfig(ThreadConfiguration threadConfig) {
205         this.threadConfig = threadConfig;
206     }
207 }