TLS support
[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.impl.connection.ServerFacade;
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 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
57     private PublishingChannelInitializer channelInitializer;
58
59     /**
60      * Constructor of TCPHandler that listens on selected port.
61      *
62      * @param port listening port of TCPHandler server
63      */
64     public TcpHandler(final int port) {
65         this(null, port);
66     }
67
68     /**
69      * Constructor of TCPHandler that listens on selected address and port.
70      * @param address listening address of TCPHandler server
71      * @param port listening port of TCPHandler server
72      */
73     public TcpHandler(final InetAddress address, final int port) {
74         this.port = port;
75         this.startupAddress = address;
76         isOnlineFuture = SettableFuture.create();
77     }
78
79     /**
80      * Starts server on selected port.
81      */
82     @Override
83     public void run() {
84         bossGroup = new NioEventLoopGroup();
85         workerGroup = new NioEventLoopGroup();
86
87         /*
88          * We generally do not perform IO-unrelated tasks, so we want to have
89          * all outstanding tasks completed before the executing thread goes
90          * back into select.
91          *
92          * Any other setting means netty will measure the time it spent selecting
93          * and spend roughly proportional time executing tasks.
94          */
95         workerGroup.setIoRatio(100);
96
97         final ChannelFuture f;
98         try {
99             ServerBootstrap b = new ServerBootstrap();
100             b.group(bossGroup, workerGroup)
101                     .channel(NioServerSocketChannel.class)
102                     .handler(new LoggingHandler(LogLevel.DEBUG))
103                     .childHandler(channelInitializer)
104                     .option(ChannelOption.SO_BACKLOG, 128)
105                     .option(ChannelOption.SO_REUSEADDR, true)
106                     .childOption(ChannelOption.SO_KEEPALIVE, true)
107                     .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
108                     .childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, DEFAULT_WRITE_HIGH_WATERMARK * 1024)
109                     .childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, DEFAULT_WRITE_LOW_WATERMARK * 1024)
110                     .childOption(ChannelOption.WRITE_SPIN_COUNT, DEFAULT_WRITE_SPIN_COUNT);
111
112             if (startupAddress != null) {
113                 f = b.bind(startupAddress.getHostAddress(), port).sync();
114             } else {
115                 f = b.bind(port).sync();
116             }
117         } catch (InterruptedException e) {
118             LOGGER.error("Interrupted while binding port {}", port, e);
119             return;
120         }
121
122         try {
123             InetSocketAddress isa = (InetSocketAddress) f.channel().localAddress();
124             address = isa.getHostString();
125
126             // Update port, as it may have been specified as 0
127             this.port = isa.getPort();
128
129             LOGGER.debug("address from tcphandler: {}", address);
130             isOnlineFuture.set(true);
131             LOGGER.info("Switch listener started and ready to accept incoming connections on port: {}", port);
132             f.channel().closeFuture().sync();
133         } catch (InterruptedException e) {
134             LOGGER.error("Interrupted while waiting for port {} shutdown", port, e);
135         } finally {
136             shutdown();
137         }
138     }
139
140     /**
141      * Shuts down {@link TcpHandler}}
142      */
143     @Override
144     public ListenableFuture<Boolean> shutdown() {
145         final SettableFuture<Boolean> result = SettableFuture.create();
146         workerGroup.shutdownGracefully();
147         // boss will shutdown as soon, as worker is down
148         bossGroup.shutdownGracefully().addListener(new GenericFutureListener<io.netty.util.concurrent.Future<Object>>() {
149
150             @Override
151             public void operationComplete(
152                     final io.netty.util.concurrent.Future<Object> downResult) throws Exception {
153                 result.set(downResult.isSuccess());
154                 if (downResult.cause() != null) {
155                     result.setException(downResult.cause());
156                 }
157             }
158
159         });
160         return result;
161     }
162
163     /**
164      *
165      * @return number of connected clients / channels
166      */
167     public int getNumberOfConnections() {
168         return channelInitializer.size();
169     }
170
171     @Override
172     public ListenableFuture<Boolean> getIsOnlineFuture() {
173         return isOnlineFuture;
174     }
175
176     /**
177      * @return the port
178      */
179     public int getPort() {
180         return port;
181     }
182
183     /**
184      * @return the address
185      */
186     public String getAddress() {
187         return address;
188     }
189
190     /**
191      * @param channelInitializer
192      */
193     public void setChannelInitializer(PublishingChannelInitializer channelInitializer) {
194         this.channelInitializer = channelInitializer;
195     }
196
197 }