2 * Copyright (C) 2014 Red Hat, Inc.
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
8 * Authors : Madhu Venugopal
11 package org.opendaylight.ovsdb.lib.impl;
13 import io.netty.bootstrap.Bootstrap;
14 import io.netty.bootstrap.ServerBootstrap;
15 import io.netty.channel.AdaptiveRecvByteBufAllocator;
16 import io.netty.channel.Channel;
17 import io.netty.channel.ChannelFuture;
18 import io.netty.channel.ChannelInitializer;
19 import io.netty.channel.ChannelOption;
20 import io.netty.channel.EventLoopGroup;
21 import io.netty.channel.nio.NioEventLoopGroup;
22 import io.netty.channel.socket.SocketChannel;
23 import io.netty.channel.socket.nio.NioServerSocketChannel;
24 import io.netty.channel.socket.nio.NioSocketChannel;
25 import io.netty.handler.codec.string.StringEncoder;
26 import io.netty.handler.logging.LogLevel;
27 import io.netty.handler.logging.LoggingHandler;
28 import io.netty.util.CharsetUtil;
29 import io.netty.handler.ssl.SslHandler;
31 import javax.net.ssl.SSLContext;
32 import javax.net.ssl.SSLEngine;
34 import java.net.InetAddress;
35 import java.util.Collection;
38 import java.util.concurrent.ExecutorService;
39 import java.util.concurrent.Executors;
41 import org.opendaylight.ovsdb.lib.OvsdbClient;
42 import org.opendaylight.ovsdb.lib.OvsdbConnection;
43 import org.opendaylight.ovsdb.lib.OvsdbConnectionInfo.ConnectionType;
44 import org.opendaylight.ovsdb.lib.OvsdbConnectionListener;
45 import org.opendaylight.ovsdb.lib.jsonrpc.ExceptionHandler;
46 import org.opendaylight.ovsdb.lib.jsonrpc.JsonRpcDecoder;
47 import org.opendaylight.ovsdb.lib.jsonrpc.JsonRpcEndpoint;
48 import org.opendaylight.ovsdb.lib.jsonrpc.JsonRpcServiceBinderHandler;
49 import org.opendaylight.ovsdb.lib.message.OvsdbRPC;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
53 import com.fasterxml.jackson.annotation.JsonInclude.Include;
54 import com.fasterxml.jackson.databind.DeserializationFeature;
55 import com.fasterxml.jackson.databind.ObjectMapper;
56 import com.google.common.collect.Maps;
57 import com.google.common.collect.Sets;
60 * OvsDBConnectionService provides OVSDB connection management functionality which includes
61 * both Active and Passive connections.
62 * From the Library perspective, Active OVSDB connections are those that are initiated from
63 * the Controller towards the ovsdb-manager.
64 * While Passive OVSDB connections are those that are initiated from the ovs towards
67 * Applications that use OvsDBConnectionService can use the OvsDBConnection class' connect APIs
68 * to initiate Active connections and can listen to the asynchronous Passive connections via
69 * registerConnectionListener listener API.
71 * The library is designed as Java modular component that can work in both OSGi and non-OSGi
72 * environment. Hence a single instance of the service will be active (via Service Registry in OSGi)
73 * and a Singleton object in a non-OSGi environment.
75 public class OvsdbConnectionService implements OvsdbConnection {
76 private static final Logger logger = LoggerFactory.getLogger(OvsdbConnectionService.class);
77 private final static int NUM_THREADS = 3;
79 // Singleton Service object that can be used in Non-OSGi environment
80 private static Set<OvsdbConnectionListener> connectionListeners = Sets.newHashSet();
81 private static Map<OvsdbClient, Channel> connections = Maps.newHashMap();
82 private static OvsdbConnection connectionService;
83 private volatile static boolean singletonCreated = false;
85 public static OvsdbConnection getService() {
86 if (connectionService == null) {
87 connectionService = new OvsdbConnectionService();
89 return connectionService;
92 public OvsdbClient connect(final InetAddress address, final int port) {
93 return connectWithSsl(address, port, null /* SslContext */);
96 public OvsdbClient connectWithSsl(final InetAddress address, final int port,
97 final SSLContext sslContext) {
99 Bootstrap bootstrap = new Bootstrap();
100 bootstrap.group(new NioEventLoopGroup());
101 bootstrap.channel(NioSocketChannel.class);
102 bootstrap.option(ChannelOption.TCP_NODELAY, true);
103 bootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(65535, 65535, 65535));
105 bootstrap.handler(new ChannelInitializer<SocketChannel>() {
107 public void initChannel(SocketChannel channel) throws Exception {
108 if (sslContext != null) {
109 /* First add ssl handler if ssl context is given */
111 sslContext.createSSLEngine(address.toString(), port);
112 engine.setUseClientMode(true);
113 channel.pipeline().addLast("ssl", new SslHandler(engine));
115 channel.pipeline().addLast(
116 //new LoggingHandler(LogLevel.INFO),
117 new JsonRpcDecoder(100000),
118 new StringEncoder(CharsetUtil.UTF_8),
119 new ExceptionHandler());
123 ChannelFuture future = bootstrap.connect(address, port).sync();
124 Channel channel = future.channel();
125 OvsdbClient client = getChannelClient(channel, ConnectionType.ACTIVE, Executors.newFixedThreadPool(NUM_THREADS));
127 } catch (InterruptedException e) {
128 System.out.println("Thread was interrupted during connect");
134 public void disconnect(OvsdbClient client) {
135 if (client == null) return;
136 Channel channel = connections.get(client);
137 if (channel != null) {
138 channel.disconnect();
140 connections.remove(client);
144 public void registerConnectionListener(OvsdbConnectionListener listener) {
145 connectionListeners.add(listener);
149 public void unregisterConnectionListener(OvsdbConnectionListener listener) {
150 connectionListeners.remove(listener);
153 private static OvsdbClient getChannelClient(Channel channel, ConnectionType type,
154 ExecutorService executorService) {
155 ObjectMapper objectMapper = new ObjectMapper();
156 objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
157 objectMapper.setSerializationInclusion(Include.NON_NULL);
159 JsonRpcEndpoint factory = new JsonRpcEndpoint(objectMapper, channel);
160 JsonRpcServiceBinderHandler binderHandler = new JsonRpcServiceBinderHandler(factory);
161 binderHandler.setContext(channel);
162 channel.pipeline().addLast(binderHandler);
164 OvsdbRPC rpc = factory.getClient(channel, OvsdbRPC.class);
165 OvsdbClientImpl client = new OvsdbClientImpl(rpc, channel, type, executorService);
166 connections.put(client, channel);
167 ChannelFuture closeFuture = channel.closeFuture();
168 closeFuture.addListener(new ChannelConnectionHandler(client));
173 * Method that initiates the Passive OVSDB channel listening functionality.
174 * By default the ovsdb passive connection will listen in port 6640 which can
175 * be overridden using the ovsdb.listenPort system property.
179 public boolean startOvsdbManager(final int ovsdbListenPort) {
180 if (!singletonCreated) {
184 ovsdbManager(ovsdbListenPort);
187 singletonCreated = true;
195 * Method that initiates the Passive OVSDB channel listening functionality
196 * with ssl.By default the ovsdb passive connection will listen in port
197 * 6640 which can be overridden using the ovsdb.listenPort system property.
201 public boolean startOvsdbManagerWithSsl(final int ovsdbListenPort,
202 final SSLContext sslContext) {
203 if (!singletonCreated) {
207 ovsdbManagerWithSsl(ovsdbListenPort, sslContext);
210 singletonCreated = true;
218 * OVSDB Passive listening thread that uses Netty ServerBootstrap to open
219 * passive connection handle channel callbacks.
221 private static void ovsdbManager(int port) {
222 ovsdbManagerWithSsl(port, null /* SslContext */);
226 * OVSDB Passive listening thread that uses Netty ServerBootstrap to open
227 * passive connection with Ssl and handle channel callbacks.
229 private static void ovsdbManagerWithSsl(int port, final SSLContext sslContext) {
230 EventLoopGroup bossGroup = new NioEventLoopGroup();
231 EventLoopGroup workerGroup = new NioEventLoopGroup();
233 ServerBootstrap b = new ServerBootstrap();
234 b.group(bossGroup, workerGroup)
235 .channel(NioServerSocketChannel.class)
236 .option(ChannelOption.SO_BACKLOG, 100)
237 .handler(new LoggingHandler(LogLevel.INFO))
238 .childHandler(new ChannelInitializer<SocketChannel>() {
240 public void initChannel(SocketChannel channel) throws Exception {
241 logger.debug("New Passive channel created : "+ channel.toString());
242 if (sslContext != null) {
243 /* Add SSL handler first if SSL context is provided */
244 SSLEngine engine = sslContext.createSSLEngine();
245 engine.setUseClientMode(false); // work in a server mode
246 engine.setNeedClientAuth(true); // need client authentication
247 channel.pipeline().addLast("ssl", new SslHandler(engine));
250 channel.pipeline().addLast(
251 new JsonRpcDecoder(100000),
252 new StringEncoder(CharsetUtil.UTF_8),
253 new ExceptionHandler());
255 handleNewPassiveConnection(channel);
258 b.option(ChannelOption.TCP_NODELAY, true);
259 b.option(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(65535, 65535, 65535));
261 ChannelFuture f = b.bind(port).sync();
262 Channel serverListenChannel = f.channel();
263 // Wait until the server socket is closed.
264 serverListenChannel.closeFuture().sync();
265 } catch (InterruptedException e) {
266 logger.error("Thread interrupted", e);
268 // Shut down all event loops to terminate all threads.
269 bossGroup.shutdownGracefully();
270 workerGroup.shutdownGracefully();
274 private static ExecutorService executorService = Executors.newFixedThreadPool(10);
275 private static void handleNewPassiveConnection(final Channel channel) {
276 executorService.execute(new Runnable() {
279 OvsdbClient client = getChannelClient(channel, ConnectionType.PASSIVE, Executors.newFixedThreadPool(NUM_THREADS));
280 for (OvsdbConnectionListener listener : connectionListeners) {
281 listener.connected(client);
287 public static void channelClosed(final OvsdbClient client) {
288 logger.info("Connection closed {}", client.getConnectionInfo().toString());
289 connections.remove(client);
290 for (OvsdbConnectionListener listener : connectionListeners) {
291 listener.disconnected(client);
295 public Collection<OvsdbClient> getConnections() {
296 return connections.keySet();