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