Draft implementation of integration tests
[openflowjava.git] / openflow-protocol-impl / src / main / java / org / opendaylight / openflowjava / protocol / impl / core / TcpHandler.java
1 /* Copyright (C)2013 Pantheon Technologies, s.r.o. All rights reserved. */
2 package org.opendaylight.openflowjava.protocol.impl.core;
3
4 import io.netty.bootstrap.ServerBootstrap;
5 import io.netty.channel.ChannelFuture;
6 import io.netty.channel.ChannelOption;
7 import io.netty.channel.nio.NioEventLoopGroup;
8 import io.netty.channel.socket.nio.NioServerSocketChannel;
9 import io.netty.handler.logging.LogLevel;
10 import io.netty.handler.logging.LoggingHandler;
11 import io.netty.util.concurrent.GenericFutureListener;
12
13 import java.net.InetAddress;
14 import java.net.InetSocketAddress;
15
16 import org.opendaylight.openflowjava.protocol.impl.connection.ServerFacade;
17 import org.slf4j.Logger;
18 import org.slf4j.LoggerFactory;
19
20 import com.google.common.util.concurrent.ListenableFuture;
21 import com.google.common.util.concurrent.SettableFuture;
22
23 /**
24  * Class implementing server over TCP for handling incoming connections.
25  *
26  * @author michal.polkorab
27  */
28 public class TcpHandler implements ServerFacade {
29
30     private int port;
31     private String address;
32     private InetAddress startupAddress;
33     private NioEventLoopGroup workerGroup;
34     private NioEventLoopGroup bossGroup;
35     private static final Logger LOGGER = LoggerFactory.getLogger(TcpHandler.class);
36     private SettableFuture<Boolean> isOnlineFuture;
37     
38     
39     private PublishingChannelInitializer channelInitializer;
40
41     /**
42      * Enum used for storing names of used components (in pipeline).
43      */
44     public static enum COMPONENT_NAMES {
45
46         /**
47          * First component in pipeline - detecting TLS connections
48          */
49         TLS_DETECTOR,
50         /**
51          * Component for handling TLS frames
52          */
53         SSL_HANDLER,
54         /**
55          * Decodes incoming messages into message frames
56          */
57         OF_FRAME_DECODER,
58         /**
59          * Detects version of incoming OpenFlow Protocol message
60          */
61         OF_VERSION_DETECTOR,
62         /**
63          * Transforms OpenFlow Protocol byte messages into POJOs
64          */
65         OF_DECODER,
66         /**
67          * Transforms POJOs into OpenFlow Protocol byte messages
68          */
69         OF_ENCODER,
70         /**
71          * Delegates translated POJOs into MessageConsumer
72          */
73         DELEGATING_INBOUND_HANDLER,
74     }
75     
76
77     /**
78      * Constructor of TCPHandler that listens on selected port.
79      *
80      * @param port listening port of TCPHandler server
81      */
82     public TcpHandler(int port) {
83         this(null, port);
84     }
85     
86     /**
87      * Constructor of TCPHandler that listens on selected address and port.
88      * @param address listening address of TCPHandler server
89      * @param port listening port of TCPHandler server
90      */
91     public TcpHandler(InetAddress address, int port) {
92         this.port = port;
93         this.startupAddress = address;
94         channelInitializer = new PublishingChannelInitializer();
95         isOnlineFuture = SettableFuture.create();
96     }
97
98     /**
99      * Starts server on selected port.
100      */
101     @Override
102     public void run() {
103         LOGGER.info("Switch ");
104         bossGroup = new NioEventLoopGroup();
105         workerGroup = new NioEventLoopGroup();
106         try {
107             ServerBootstrap b = new ServerBootstrap();
108             b.group(bossGroup, workerGroup)
109                     .channel(NioServerSocketChannel.class)
110                     .handler(new LoggingHandler(LogLevel.DEBUG))
111                     .childHandler(channelInitializer)
112                     .option(ChannelOption.SO_BACKLOG, 128)
113                     .childOption(ChannelOption.SO_KEEPALIVE, true);
114
115             ChannelFuture f;
116             if (startupAddress != null) {
117                 f = b.bind(startupAddress.getHostAddress(), port).sync();
118             } else {
119                 f = b.bind(port).sync();
120             }
121             
122             InetSocketAddress isa = (InetSocketAddress) f.channel().localAddress();
123             address = isa.getHostString();
124             LOGGER.debug("address from tcphandler: " + address);
125             port = isa.getPort();
126             isOnlineFuture.set(true);
127             LOGGER.info("Switch listener started and ready to accept incoming connections on port: " + port);
128             f.channel().closeFuture().sync();
129         } catch (InterruptedException ex) {
130             LOGGER.error(ex.getMessage(), ex);
131         } finally {
132             shutdown();
133         }
134     }
135
136     /**
137      * Shuts down {@link TcpHandler}}
138      */
139     @Override
140     public ListenableFuture<Boolean> shutdown() {
141         final SettableFuture<Boolean> result = SettableFuture.create();
142         workerGroup.shutdownGracefully();
143         // boss will shutdown as soon, as worker is down
144         bossGroup.shutdownGracefully().addListener(new GenericFutureListener<io.netty.util.concurrent.Future<Object>>() {
145
146             @Override
147             public void operationComplete(
148                     io.netty.util.concurrent.Future<Object> downResult) throws Exception {
149                 result.set(downResult.isSuccess());
150                 result.setException(downResult.cause());
151             }
152             
153         });
154         return result;
155     }
156     
157     /**
158      * 
159      * @return number of connected clients / channels
160      */
161     public int getNumberOfConnections() {
162         return channelInitializer.size();
163     }
164     
165     /**
166      * @return channelInitializer providing channels
167      */
168     public PublishingChannelInitializer getChannelInitializer() {
169         return channelInitializer;
170     }
171     
172     /**
173      * Sets and starts TCPHandler.
174      *
175      * @param args
176      * @throws Exception
177      */
178     public static void main(String[] args) throws Exception {
179         int port;
180         if (args.length > 0) {
181             port = Integer.parseInt(args[0]);
182         } else {
183             port = 6633;
184         }
185         new Thread(new TcpHandler(port)).start();
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 }