2b5f6792c3638c40690ebd2fea2a163f4eb865cb
[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.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;
19
20 import java.net.InetAddress;
21 import java.net.InetSocketAddress;
22
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.serialization.SerializationFactory;
26 import org.opendaylight.openflowjava.protocol.impl.deserialization.DeserializationFactory;
27 import org.slf4j.Logger;
28 import org.slf4j.LoggerFactory;
29
30 import com.google.common.util.concurrent.ListenableFuture;
31 import com.google.common.util.concurrent.SettableFuture;
32
33 /**
34  * Class implementing server over TCP for handling incoming connections.
35  *
36  * @author michal.polkorab
37  */
38 public class TcpHandler implements ServerFacade {
39
40     private int port;
41     private String address;
42     private InetAddress startupAddress;
43     private NioEventLoopGroup workerGroup;
44     private NioEventLoopGroup bossGroup;
45     private static final Logger LOGGER = LoggerFactory.getLogger(TcpHandler.class);
46     private SettableFuture<Boolean> isOnlineFuture;
47     
48     
49     private PublishingChannelInitializer channelInitializer;
50
51     /**
52      * Enum used for storing names of used components (in pipeline).
53      */
54     public static enum COMPONENT_NAMES {
55
56         /**
57          * Detects switch idle state
58          */
59         IDLE_HANDLER,
60         /**
61          * Detects TLS connections
62          */
63         TLS_DETECTOR,
64         /**
65          * Component for handling TLS frames
66          */
67         SSL_HANDLER,
68         /**
69          * Decodes incoming messages into message frames
70          */
71         OF_FRAME_DECODER,
72         /**
73          * Detects version of incoming OpenFlow Protocol message
74          */
75         OF_VERSION_DETECTOR,
76         /**
77          * Transforms OpenFlow Protocol byte messages into POJOs
78          */
79         OF_DECODER,
80         /**
81          * Transforms POJOs into OpenFlow Protocol byte messages
82          */
83         OF_ENCODER,
84         /**
85          * Delegates translated POJOs into MessageConsumer
86          */
87         DELEGATING_INBOUND_HANDLER,
88     }
89     
90
91     /**
92      * Constructor of TCPHandler that listens on selected port.
93      *
94      * @param port listening port of TCPHandler server
95      */
96     public TcpHandler(int port) {
97         this(null, port);
98     }
99     
100     /**
101      * Constructor of TCPHandler that listens on selected address and port.
102      * @param address listening address of TCPHandler server
103      * @param port listening port of TCPHandler server
104      */
105     public TcpHandler(InetAddress address, int port) {
106         this.port = port;
107         this.startupAddress = address;
108         channelInitializer = new PublishingChannelInitializer();
109         isOnlineFuture = SettableFuture.create();
110     }
111
112     /**
113      * Starts server on selected port.
114      */
115     @Override
116     public void run() {
117         bossGroup = new NioEventLoopGroup();
118         workerGroup = new NioEventLoopGroup();
119         try {
120             ServerBootstrap b = new ServerBootstrap();
121             b.group(bossGroup, workerGroup)
122                     .channel(NioServerSocketChannel.class)
123                     .handler(new LoggingHandler(LogLevel.DEBUG))
124                     .childHandler(channelInitializer)
125                     .option(ChannelOption.SO_BACKLOG, 128)
126                     .option(ChannelOption.SO_REUSEADDR, true)
127                     .childOption(ChannelOption.SO_KEEPALIVE, true);
128
129             ChannelFuture f;
130             if (startupAddress != null) {
131                 f = b.bind(startupAddress.getHostAddress(), port).sync();
132             } else {
133                 f = b.bind(port).sync();
134             }
135             
136             InetSocketAddress isa = (InetSocketAddress) f.channel().localAddress();
137             address = isa.getHostString();
138             LOGGER.debug("address from tcphandler: " + address);
139             port = isa.getPort();
140             isOnlineFuture.set(true);
141             LOGGER.info("Switch listener started and ready to accept incoming connections on port: " + port);
142             f.channel().closeFuture().sync();
143         } catch (InterruptedException ex) {
144             LOGGER.error(ex.getMessage(), ex);
145         } finally {
146             shutdown();
147         }
148     }
149
150     /**
151      * Shuts down {@link TcpHandler}}
152      */
153     @Override
154     public ListenableFuture<Boolean> shutdown() {
155         final SettableFuture<Boolean> result = SettableFuture.create();
156         workerGroup.shutdownGracefully();
157         // boss will shutdown as soon, as worker is down
158         bossGroup.shutdownGracefully().addListener(new GenericFutureListener<io.netty.util.concurrent.Future<Object>>() {
159
160             @Override
161             public void operationComplete(
162                     io.netty.util.concurrent.Future<Object> downResult) throws Exception {
163                 result.set(downResult.isSuccess());
164                 if (downResult.cause() != null) {
165                     result.setException(downResult.cause());
166                 }
167             }
168             
169         });
170         return result;
171     }
172     
173     /**
174      * 
175      * @return number of connected clients / channels
176      */
177     public int getNumberOfConnections() {
178         return channelInitializer.size();
179     }
180     
181     /**
182      * @return channelInitializer providing channels
183      */
184     public PublishingChannelInitializer getChannelInitializer() {
185         return channelInitializer;
186     }
187     
188     @Override
189     public ListenableFuture<Boolean> getIsOnlineFuture() {
190         return isOnlineFuture;
191     }
192     
193     /**
194      * @return the port
195      */
196     public int getPort() {
197         return port;
198     }
199     
200     /**
201      * @return the address
202      */
203     public String getAddress() {
204         return address;
205     }
206
207     /**
208      * @param switchConnectionHandler
209      */
210     public void setSwitchConnectionHandler(
211             SwitchConnectionHandler switchConnectionHandler) {
212         channelInitializer.setSwitchConnectionHandler(switchConnectionHandler);
213     }
214     
215     /**
216      * @param switchIdleTimeout in milliseconds
217      */
218     public void setSwitchIdleTimeout(long switchIdleTimeout) {
219         channelInitializer.setSwitchIdleTimeout(switchIdleTimeout);
220     }
221
222     /**
223      * @param tlsSupported
224      */
225     public void setEncryption(boolean tlsSupported) {
226         channelInitializer.setEncryption(tlsSupported);
227     }
228
229     /**
230      * @param sf serialization factory
231      */
232     public void setSerializationFactory(SerializationFactory sf) {
233         channelInitializer.setSerializationFactory(sf);
234     }
235
236     /**
237      * @param factory
238      */
239     public void setDeserializationFactory(DeserializationFactory factory) {
240         channelInitializer.setDeserializationFactory(factory);
241     }
242
243 }