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