2 * Copyright (c) 2014, 2015 Red Hat, Inc. and others. All rights reserved.
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
9 package org.opendaylight.ovsdb.lib.impl;
11 import com.fasterxml.jackson.annotation.JsonInclude.Include;
12 import com.fasterxml.jackson.databind.DeserializationFeature;
13 import com.fasterxml.jackson.databind.ObjectMapper;
14 import com.google.common.collect.Maps;
15 import com.google.common.collect.Sets;
16 import com.google.common.util.concurrent.FutureCallback;
17 import com.google.common.util.concurrent.Futures;
18 import com.google.common.util.concurrent.ListenableFuture;
19 import com.google.common.util.concurrent.ThreadFactoryBuilder;
20 import io.netty.bootstrap.Bootstrap;
21 import io.netty.bootstrap.ServerBootstrap;
22 import io.netty.channel.AdaptiveRecvByteBufAllocator;
23 import io.netty.channel.Channel;
24 import io.netty.channel.ChannelFuture;
25 import io.netty.channel.ChannelInitializer;
26 import io.netty.channel.ChannelOption;
27 import io.netty.channel.EventLoopGroup;
28 import io.netty.channel.nio.NioEventLoopGroup;
29 import io.netty.channel.socket.SocketChannel;
30 import io.netty.channel.socket.nio.NioServerSocketChannel;
31 import io.netty.channel.socket.nio.NioSocketChannel;
32 import io.netty.handler.codec.string.StringEncoder;
33 import io.netty.handler.logging.LogLevel;
34 import io.netty.handler.logging.LoggingHandler;
35 import io.netty.handler.ssl.SslHandler;
36 import io.netty.handler.timeout.IdleStateHandler;
37 import io.netty.handler.timeout.ReadTimeoutHandler;
38 import io.netty.util.CharsetUtil;
39 import java.net.InetAddress;
40 import java.util.ArrayList;
41 import java.util.Arrays;
42 import java.util.Collection;
43 import java.util.List;
46 import java.util.concurrent.ExecutorService;
47 import java.util.concurrent.Executors;
48 import java.util.concurrent.ScheduledExecutorService;
49 import java.util.concurrent.ThreadFactory;
50 import java.util.concurrent.TimeUnit;
51 import javax.annotation.Nullable;
52 import javax.net.ssl.SSLContext;
53 import javax.net.ssl.SSLEngine;
54 import javax.net.ssl.SSLEngineResult.HandshakeStatus;
55 import javax.net.ssl.SSLPeerUnverifiedException;
56 import org.opendaylight.ovsdb.lib.OvsdbClient;
57 import org.opendaylight.ovsdb.lib.OvsdbConnection;
58 import org.opendaylight.ovsdb.lib.OvsdbConnectionInfo.ConnectionType;
59 import org.opendaylight.ovsdb.lib.OvsdbConnectionInfo.SocketConnectionType;
60 import org.opendaylight.ovsdb.lib.OvsdbConnectionListener;
61 import org.opendaylight.ovsdb.lib.jsonrpc.ExceptionHandler;
62 import org.opendaylight.ovsdb.lib.jsonrpc.JsonRpcDecoder;
63 import org.opendaylight.ovsdb.lib.jsonrpc.JsonRpcEndpoint;
64 import org.opendaylight.ovsdb.lib.jsonrpc.JsonRpcServiceBinderHandler;
65 import org.opendaylight.ovsdb.lib.message.OvsdbRPC;
66 import org.slf4j.Logger;
67 import org.slf4j.LoggerFactory;
70 * OvsDBConnectionService provides OVSDB connection management functionality which includes
71 * both Active and Passive connections.
72 * From the Library perspective, Active OVSDB connections are those that are initiated from
73 * the Controller towards the ovsdb-manager.
74 * While Passive OVSDB connections are those that are initiated from the ovs towards
77 * <p>Applications that use OvsDBConnectionService can use the OvsDBConnection class' connect APIs
78 * to initiate Active connections and can listen to the asynchronous Passive connections via
79 * registerConnectionListener listener API.
81 * <p>The library is designed as Java modular component that can work in both OSGi and non-OSGi
82 * environment. Hence a single instance of the service will be active (via Service Registry in OSGi)
83 * and a Singleton object in a non-OSGi environment.
85 public class OvsdbConnectionService implements AutoCloseable, OvsdbConnection {
86 private static final Logger LOG = LoggerFactory.getLogger(OvsdbConnectionService.class);
88 private static ThreadFactory passiveConnectionThreadFactory = new ThreadFactoryBuilder()
89 .setNameFormat("OVSDBPassiveConnServ-%d").build();
90 private static ScheduledExecutorService executorService
91 = Executors.newScheduledThreadPool(10, passiveConnectionThreadFactory);
93 private static ThreadFactory connectionNotifierThreadFactory = new ThreadFactoryBuilder()
94 .setNameFormat("OVSDBConnNotifSer-%d").build();
95 private static ExecutorService connectionNotifierService
96 = Executors.newCachedThreadPool(connectionNotifierThreadFactory);
98 private static Set<OvsdbConnectionListener> connectionListeners = Sets.newHashSet();
99 private static Map<OvsdbClient, Channel> connections = Maps.newHashMap();
100 private static OvsdbConnection connectionService;
101 private static volatile boolean singletonCreated = false;
102 private static final int IDLE_READER_TIMEOUT = 30;
103 private static final int READ_TIMEOUT = 180;
105 private static final StalePassiveConnectionService STALE_PASSIVE_CONNECTION_SERVICE =
106 new StalePassiveConnectionService(executorService);
108 private static int retryPeriod = 100; // retry after 100 milliseconds
111 public static OvsdbConnection getService() {
112 if (connectionService == null) {
113 connectionService = new OvsdbConnectionService();
115 return connectionService;
119 public OvsdbClient connect(final InetAddress address, final int port) {
120 return connectWithSsl(address, port, null /* SslContext */);
124 public OvsdbClient connectWithSsl(final InetAddress address, final int port,
125 final SSLContext sslContext) {
127 Bootstrap bootstrap = new Bootstrap();
128 bootstrap.group(new NioEventLoopGroup());
129 bootstrap.channel(NioSocketChannel.class);
130 bootstrap.option(ChannelOption.TCP_NODELAY, true);
131 bootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(65535, 65535, 65535));
133 bootstrap.handler(new ChannelInitializer<SocketChannel>() {
135 public void initChannel(SocketChannel channel) throws Exception {
136 if (sslContext != null) {
137 /* First add ssl handler if ssl context is given */
139 sslContext.createSSLEngine(address.toString(), port);
140 engine.setUseClientMode(true);
141 channel.pipeline().addLast("ssl", new SslHandler(engine));
143 channel.pipeline().addLast(
144 //new LoggingHandler(LogLevel.INFO),
145 new JsonRpcDecoder(100000),
146 new StringEncoder(CharsetUtil.UTF_8),
147 new IdleStateHandler(IDLE_READER_TIMEOUT, 0, 0),
148 new ReadTimeoutHandler(READ_TIMEOUT),
149 new ExceptionHandler());
153 ChannelFuture future = bootstrap.connect(address, port).sync();
154 Channel channel = future.channel();
155 return getChannelClient(channel, ConnectionType.ACTIVE, SocketConnectionType.SSL);
156 } catch (InterruptedException e) {
157 LOG.warn("Failed to connect {}:{}", address, port, e);
163 public void disconnect(OvsdbClient client) {
164 if (client == null) {
167 Channel channel = connections.get(client);
168 if (channel != null) {
169 channel.disconnect();
171 connections.remove(client);
175 public void registerConnectionListener(OvsdbConnectionListener listener) {
176 LOG.info("registerConnectionListener: registering {}", listener.getClass().getSimpleName());
177 connectionListeners.add(listener);
181 public void unregisterConnectionListener(OvsdbConnectionListener listener) {
182 connectionListeners.remove(listener);
185 private static OvsdbClient getChannelClient(Channel channel, ConnectionType type,
186 SocketConnectionType socketConnType) {
187 ObjectMapper objectMapper = new ObjectMapper();
188 objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
189 objectMapper.setSerializationInclusion(Include.NON_NULL);
191 JsonRpcEndpoint factory = new JsonRpcEndpoint(objectMapper, channel);
192 JsonRpcServiceBinderHandler binderHandler = new JsonRpcServiceBinderHandler(factory);
193 binderHandler.setContext(channel);
194 channel.pipeline().addLast(binderHandler);
196 OvsdbRPC rpc = factory.getClient(channel, OvsdbRPC.class);
197 OvsdbClientImpl client = new OvsdbClientImpl(rpc, channel, type, socketConnType);
198 client.setConnectionPublished(true);
199 connections.put(client, channel);
200 ChannelFuture closeFuture = channel.closeFuture();
201 closeFuture.addListener(new ChannelConnectionHandler(client));
206 * Method that initiates the Passive OVSDB channel listening functionality.
207 * By default the ovsdb passive connection will listen in port 6640 which can
208 * be overridden using the ovsdb.listenPort system property.
211 public synchronized boolean startOvsdbManager(final int ovsdbListenPort) {
212 if (!singletonCreated) {
213 LOG.info("startOvsdbManager: Starting");
217 ovsdbManager(ovsdbListenPort);
220 singletonCreated = true;
228 * Method that initiates the Passive OVSDB channel listening functionality
229 * with ssl.By default the ovsdb passive connection will listen in port
230 * 6640 which can be overridden using the ovsdb.listenPort system property.
233 public synchronized boolean startOvsdbManagerWithSsl(final int ovsdbListenPort,
234 final SSLContext sslContext) {
235 if (!singletonCreated) {
239 ovsdbManagerWithSsl(ovsdbListenPort, sslContext);
242 singletonCreated = true;
250 * OVSDB Passive listening thread that uses Netty ServerBootstrap to open
251 * passive connection handle channel callbacks.
253 private static void ovsdbManager(int port) {
254 ovsdbManagerWithSsl(port, null /* SslContext */);
258 * OVSDB Passive listening thread that uses Netty ServerBootstrap to open
259 * passive connection with Ssl and handle channel callbacks.
261 private static void ovsdbManagerWithSsl(int port, final SSLContext sslContext) {
262 EventLoopGroup bossGroup = new NioEventLoopGroup();
263 EventLoopGroup workerGroup = new NioEventLoopGroup();
265 ServerBootstrap serverBootstrap = new ServerBootstrap();
266 serverBootstrap.group(bossGroup, workerGroup)
267 .channel(NioServerSocketChannel.class)
268 .option(ChannelOption.SO_BACKLOG, 100)
269 .handler(new LoggingHandler(LogLevel.INFO))
270 .childHandler(new ChannelInitializer<SocketChannel>() {
272 public void initChannel(SocketChannel channel) throws Exception {
273 LOG.debug("New Passive channel created : {}", channel);
274 if (sslContext != null) {
275 /* Add SSL handler first if SSL context is provided */
276 SSLEngine engine = sslContext.createSSLEngine();
277 engine.setUseClientMode(false); // work in a server mode
278 engine.setNeedClientAuth(true); // need client authentication
279 //Disable SSLv3 and enable all other supported protocols
280 String[] protocols = {"SSLv2Hello", "TLSv1", "TLSv1.1", "TLSv1.2"};
281 LOG.debug("Set enable protocols {}", Arrays.toString(protocols));
282 engine.setEnabledProtocols(protocols);
283 LOG.debug("Supported ssl protocols {}",
284 Arrays.toString(engine.getSupportedProtocols()));
285 LOG.debug("Enabled ssl protocols {}",
286 Arrays.toString(engine.getEnabledProtocols()));
288 String[] cipherSuites = {"TLS_RSA_WITH_AES_128_CBC_SHA"};
289 LOG.debug("Set enable cipher cuites {}", Arrays.toString(cipherSuites));
290 engine.setEnabledCipherSuites(cipherSuites);
291 LOG.debug("Enabled cipher suites {}",
292 Arrays.toString(engine.getEnabledCipherSuites()));
293 channel.pipeline().addLast("ssl", new SslHandler(engine));
296 channel.pipeline().addLast(
297 new JsonRpcDecoder(100000),
298 new StringEncoder(CharsetUtil.UTF_8),
299 new IdleStateHandler(IDLE_READER_TIMEOUT, 0, 0),
300 new ReadTimeoutHandler(READ_TIMEOUT),
301 new ExceptionHandler());
303 handleNewPassiveConnection(channel);
306 serverBootstrap.option(ChannelOption.TCP_NODELAY, true);
307 serverBootstrap.option(ChannelOption.RCVBUF_ALLOCATOR,
308 new AdaptiveRecvByteBufAllocator(65535, 65535, 65535));
310 ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
311 Channel serverListenChannel = channelFuture.channel();
312 // Wait until the server socket is closed.
313 serverListenChannel.closeFuture().sync();
314 } catch (InterruptedException e) {
315 LOG.error("Thread interrupted", e);
317 // Shut down all event loops to terminate all threads.
318 bossGroup.shutdownGracefully();
319 workerGroup.shutdownGracefully();
323 private static void handleNewPassiveConnection(OvsdbClient client) {
324 ListenableFuture<List<String>> echoFuture = client.echo();
325 LOG.debug("Send echo message to probe the OVSDB switch {}",client.getConnectionInfo());
326 Futures.addCallback(echoFuture, new FutureCallback<List<String>>() {
328 public void onSuccess(@Nullable List<String> result) {
329 LOG.debug("Probe was successful to OVSDB switch {}",client.getConnectionInfo());
330 List<OvsdbClient> clientsFromSameNode = getPassiveClientsFromSameNode(client);
331 if (clientsFromSameNode.size() == 0) {
332 notifyListenerForPassiveConnection(client);
334 STALE_PASSIVE_CONNECTION_SERVICE.handleNewPassiveConnection(client, clientsFromSameNode);
339 public void onFailure(Throwable failureException) {
340 LOG.error("Probe failed to OVSDB switch. Disconnecting the channel {}", client.getConnectionInfo());
343 }, connectionNotifierService);
346 private static void handleNewPassiveConnection(final Channel channel) {
347 if (!channel.isOpen()) {
348 LOG.warn("Channel {} is not open, skipped further processing of the connection.",channel);
351 SslHandler sslHandler = (SslHandler) channel.pipeline().get("ssl");
352 if (sslHandler != null) {
353 class HandleNewPassiveSslRunner implements Runnable {
354 public SslHandler sslHandler;
355 public final Channel channel;
356 private int retryTimes;
358 HandleNewPassiveSslRunner(Channel channel, SslHandler sslHandler) {
359 this.channel = channel;
360 this.sslHandler = sslHandler;
366 HandshakeStatus status = sslHandler.engine().getHandshakeStatus();
367 LOG.debug("Handshake status {}", status);
370 case NOT_HANDSHAKING:
371 if (sslHandler.engine().getSession().getCipherSuite()
372 .equals("SSL_NULL_WITH_NULL_NULL")) {
373 // Not begin handshake yet. Retry later.
374 LOG.debug("handshake not begin yet {}", status);
375 executorService.schedule(this, retryPeriod, TimeUnit.MILLISECONDS);
377 //Check if peer is trusted before notifying listeners
379 sslHandler.engine().getSession().getPeerCertificates();
380 //Handshake done. Notify listener.
381 OvsdbClient client = getChannelClient(channel, ConnectionType.PASSIVE,
382 SocketConnectionType.SSL);
383 handleNewPassiveConnection(client);
384 } catch (SSLPeerUnverifiedException e) {
385 //Trust manager is still checking peer certificate. Retry later
386 LOG.debug("Peer certifiacte is not verified yet {}", status);
387 executorService.schedule(this, retryPeriod, TimeUnit.MILLISECONDS);
394 //Handshake still ongoing. Retry later.
395 LOG.debug("handshake not done yet {}", status);
396 executorService.schedule(this, retryPeriod, TimeUnit.MILLISECONDS);
400 if (sslHandler.engine().getSession().getCipherSuite()
401 .equals("SSL_NULL_WITH_NULL_NULL")) {
402 /* peer not authenticated. No need to notify listener in this case. */
403 LOG.error("Ssl handshake fail. channel {}", channel);
406 * peer is authenticated. Give some time to wait for completion.
407 * If status is still NEED_WRAP, client might already disconnect.
408 * This happens when the first time client connects to controller in two-way handshake.
409 * After obtaining controller certificate, client will disconnect and start
410 * new connection with controller certificate it obtained.
411 * In this case no need to do anything for the first connection attempt. Just skip
412 * since client will reconnect later.
414 LOG.debug("handshake not done yet {}", status);
415 if (retryTimes > 0) {
416 executorService.schedule(this, retryPeriod, TimeUnit.MILLISECONDS);
418 LOG.debug("channel closed {}", channel);
425 LOG.error("unknown hadshake status {}", status);
430 executorService.schedule(new HandleNewPassiveSslRunner(channel, sslHandler),
431 retryPeriod, TimeUnit.MILLISECONDS);
433 executorService.execute(new Runnable() {
436 OvsdbClient client = getChannelClient(channel, ConnectionType.PASSIVE,
437 SocketConnectionType.NON_SSL);
438 handleNewPassiveConnection(client);
444 public static void channelClosed(final OvsdbClient client) {
445 LOG.info("Connection closed {}", client.getConnectionInfo().toString());
446 connections.remove(client);
447 if (client.isConnectionPublished()) {
448 for (OvsdbConnectionListener listener : connectionListeners) {
449 listener.disconnected(client);
452 STALE_PASSIVE_CONNECTION_SERVICE.clientDisconnected(client);
456 public Collection<OvsdbClient> getConnections() {
457 return connections.keySet();
461 public void close() throws Exception {
462 LOG.info("OvsdbConnectionService closed");
466 public OvsdbClient getClient(Channel channel) {
467 for (OvsdbClient client : connections.keySet()) {
468 Channel ctx = connections.get(client);
469 if (ctx.equals(channel)) {
476 private static List<OvsdbClient> getPassiveClientsFromSameNode(OvsdbClient ovsdbClient) {
477 List<OvsdbClient> passiveClients = new ArrayList<>();
478 for (OvsdbClient client : connections.keySet()) {
479 if (!client.equals(ovsdbClient)
480 && client.getConnectionInfo().getRemoteAddress()
481 .equals(ovsdbClient.getConnectionInfo().getRemoteAddress())
482 && client.getConnectionInfo().getType() == ConnectionType.PASSIVE) {
483 passiveClients.add(client);
486 return passiveClients;
489 public static void notifyListenerForPassiveConnection(final OvsdbClient client) {
490 client.setConnectionPublished(true);
491 for (final OvsdbConnectionListener listener : connectionListeners) {
492 connectionNotifierService.submit(new Runnable() {
495 LOG.trace("Connection {} notified to listener {}", client.getConnectionInfo(), listener);
496 listener.connected(client);