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