2 * Copyright © 2014, 2017 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.google.common.util.concurrent.FutureCallback;
12 import com.google.common.util.concurrent.Futures;
13 import com.google.common.util.concurrent.ListenableFuture;
14 import com.google.common.util.concurrent.ThreadFactoryBuilder;
15 import io.netty.bootstrap.Bootstrap;
16 import io.netty.bootstrap.ServerBootstrap;
17 import io.netty.channel.AdaptiveRecvByteBufAllocator;
18 import io.netty.channel.Channel;
19 import io.netty.channel.ChannelFuture;
20 import io.netty.channel.ChannelInitializer;
21 import io.netty.channel.ChannelOption;
22 import io.netty.channel.EventLoopGroup;
23 import io.netty.channel.nio.NioEventLoopGroup;
24 import io.netty.channel.socket.SocketChannel;
25 import io.netty.channel.socket.nio.NioServerSocketChannel;
26 import io.netty.channel.socket.nio.NioSocketChannel;
27 import io.netty.handler.codec.string.StringEncoder;
28 import io.netty.handler.logging.LogLevel;
29 import io.netty.handler.logging.LoggingHandler;
30 import io.netty.handler.ssl.SslHandler;
31 import io.netty.handler.timeout.IdleStateHandler;
32 import io.netty.handler.timeout.ReadTimeoutHandler;
33 import io.netty.util.CharsetUtil;
34 import java.net.InetAddress;
35 import java.util.ArrayList;
36 import java.util.Arrays;
37 import java.util.Collection;
38 import java.util.List;
40 import java.util.Map.Entry;
42 import java.util.concurrent.ConcurrentHashMap;
43 import java.util.concurrent.ExecutorService;
44 import java.util.concurrent.Executors;
45 import java.util.concurrent.ScheduledExecutorService;
46 import java.util.concurrent.TimeUnit;
47 import java.util.concurrent.atomic.AtomicBoolean;
48 import javax.annotation.Nullable;
49 import javax.inject.Inject;
50 import javax.inject.Singleton;
51 import javax.net.ssl.SSLContext;
52 import javax.net.ssl.SSLEngine;
53 import javax.net.ssl.SSLEngineResult.HandshakeStatus;
54 import javax.net.ssl.SSLPeerUnverifiedException;
55 import org.apache.aries.blueprint.annotation.service.Reference;
56 import org.apache.aries.blueprint.annotation.service.Service;
57 import org.opendaylight.aaa.cert.api.ICertificateManager;
58 import org.opendaylight.ovsdb.lib.OvsdbClient;
59 import org.opendaylight.ovsdb.lib.OvsdbConnection;
60 import org.opendaylight.ovsdb.lib.OvsdbConnectionInfo.ConnectionType;
61 import org.opendaylight.ovsdb.lib.OvsdbConnectionInfo.SocketConnectionType;
62 import org.opendaylight.ovsdb.lib.OvsdbConnectionListener;
63 import org.opendaylight.ovsdb.lib.jsonrpc.ExceptionHandler;
64 import org.opendaylight.ovsdb.lib.jsonrpc.JsonRpcDecoder;
65 import org.opendaylight.ovsdb.lib.jsonrpc.JsonRpcEndpoint;
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.
86 @Service(classes = OvsdbConnection.class)
87 public class OvsdbConnectionService implements AutoCloseable, OvsdbConnection {
88 private static final Logger LOG = LoggerFactory.getLogger(OvsdbConnectionService.class);
89 private static final int IDLE_READER_TIMEOUT = 30;
90 private static final int READ_TIMEOUT = 180;
91 private static final String OVSDB_RPC_TASK_TIMEOUT_PARAM = "ovsdb-rpc-task-timeout";
92 private static final String USE_SSL = "use-ssl";
93 private static final int RETRY_PERIOD = 100; // retry after 100 milliseconds
95 private static final ScheduledExecutorService EXECUTOR_SERVICE = Executors.newScheduledThreadPool(10,
96 new ThreadFactoryBuilder().setNameFormat("OVSDBPassiveConnServ-%d").build());
98 private static final ExecutorService CONNECTION_NOTIFIER_SERVICE = Executors
99 .newCachedThreadPool(new ThreadFactoryBuilder().setNameFormat("OVSDBConnNotifSer-%d").build());
101 private static final StalePassiveConnectionService STALE_PASSIVE_CONNECTION_SERVICE =
102 new StalePassiveConnectionService((client) -> {
103 notifyListenerForPassiveConnection(client);
107 private static final Set<OvsdbConnectionListener> CONNECTION_LISTENERS = ConcurrentHashMap.newKeySet();
108 private static final Map<OvsdbClient, Channel> CONNECTIONS = new ConcurrentHashMap<>();
110 private volatile boolean useSSL = false;
111 private final ICertificateManager certManagerSrv;
113 private volatile int jsonRpcDecoderMaxFrameLength = 100000;
114 private volatile Channel serverChannel;
116 private final AtomicBoolean singletonCreated = new AtomicBoolean(false);
117 private volatile String listenerIp = "0.0.0.0";
118 private volatile int listenerPort = 6640;
121 public OvsdbConnectionService(@Reference(filter = "type=default-certificate-manager")
122 final ICertificateManager certManagerSrv) {
123 this.certManagerSrv = certManagerSrv;
127 * If the SSL flag is enabled, the method internally will establish TLS communication using the default
128 * ODL certificateManager SSLContext and attributes.
131 public OvsdbClient connect(final InetAddress address, final int port) {
133 if (certManagerSrv == null) {
134 LOG.error("Certificate Manager service is not available cannot establish the SSL communication.");
137 return connectWithSsl(address, port, certManagerSrv);
139 return connectWithSsl(address, port, null /* SslContext */);
144 @SuppressWarnings("checkstyle:IllegalCatch")
145 public OvsdbClient connectWithSsl(final InetAddress address, final int port,
146 final ICertificateManager certificateManagerSrv) {
148 Bootstrap bootstrap = new Bootstrap();
149 bootstrap.group(new NioEventLoopGroup());
150 bootstrap.channel(NioSocketChannel.class);
151 bootstrap.option(ChannelOption.TCP_NODELAY, true);
152 bootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(65535, 65535, 65535));
154 bootstrap.handler(new ChannelInitializer<SocketChannel>() {
156 public void initChannel(final SocketChannel channel) throws Exception {
157 if (certificateManagerSrv != null && certificateManagerSrv.getServerContext() != null) {
158 SSLContext sslContext = certificateManagerSrv.getServerContext();
159 /* First add ssl handler if ssl context is given */
161 sslContext.createSSLEngine(address.toString(), port);
162 engine.setUseClientMode(true);
163 channel.pipeline().addLast("ssl", new SslHandler(engine));
165 channel.pipeline().addLast(
166 //new LoggingHandler(LogLevel.INFO),
167 new JsonRpcDecoder(jsonRpcDecoderMaxFrameLength),
168 new StringEncoder(CharsetUtil.UTF_8),
169 new IdleStateHandler(IDLE_READER_TIMEOUT, 0, 0),
170 new ReadTimeoutHandler(READ_TIMEOUT),
171 new ExceptionHandler(OvsdbConnectionService.this));
175 ChannelFuture future = bootstrap.connect(address, port).sync();
176 Channel channel = future.channel();
177 return getChannelClient(channel, ConnectionType.ACTIVE, SocketConnectionType.SSL);
178 } catch (InterruptedException e) {
179 LOG.warn("Failed to connect {}:{}", address, port, e);
180 } catch (Throwable throwable) {
181 // sync() re-throws exceptions declared as Throwable, so the compiler doesn't see them
182 LOG.error("Error while binding to address {}, port {}", address, port, throwable);
189 public void disconnect(final OvsdbClient client) {
190 if (client == null) {
193 Channel channel = CONNECTIONS.get(client);
194 if (channel != null) {
195 //It's an explicit disconnect from user, so no need to notify back
196 //to user about the disconnect.
197 client.setConnectionPublished(false);
198 channel.disconnect();
200 CONNECTIONS.remove(client);
204 public void registerConnectionListener(final OvsdbConnectionListener listener) {
205 LOG.info("registerConnectionListener: registering {}", listener.getClass().getSimpleName());
206 CONNECTION_LISTENERS.add(listener);
207 notifyAlreadyExistingConnectionsToListener(listener);
210 private void notifyAlreadyExistingConnectionsToListener(final OvsdbConnectionListener listener) {
211 for (final OvsdbClient client : getConnections()) {
212 CONNECTION_NOTIFIER_SERVICE.execute(() -> {
213 LOG.trace("Connection {} notified to listener {}", client.getConnectionInfo(), listener);
214 listener.connected(client);
220 public void unregisterConnectionListener(final OvsdbConnectionListener listener) {
221 CONNECTION_LISTENERS.remove(listener);
224 private static OvsdbClient getChannelClient(final Channel channel, final ConnectionType type,
225 final SocketConnectionType socketConnType) {
227 JsonRpcEndpoint endpoint = new JsonRpcEndpoint(channel);
228 channel.pipeline().addLast(endpoint);
230 OvsdbClientImpl client = new OvsdbClientImpl(endpoint, channel, type, socketConnType);
231 client.setConnectionPublished(true);
232 CONNECTIONS.put(client, channel);
233 channel.closeFuture().addListener(new ChannelConnectionHandler(client));
238 * Method that initiates the Passive OVSDB channel listening functionality.
239 * By default the ovsdb passive connection will listen in port 6640 which can
240 * be overridden using the ovsdb.listenPort system property.
243 public synchronized boolean startOvsdbManager() {
244 final int ovsdbListenerPort = this.listenerPort;
245 final String ovsdbListenerIp = this.listenerIp;
246 if (!singletonCreated.getAndSet(true)) {
247 LOG.info("startOvsdbManager: Starting");
248 new Thread(() -> ovsdbManager(ovsdbListenerIp, ovsdbListenerPort)).start();
256 * Method that initiates the Passive OVSDB channel listening functionality
257 * with ssl.By default the ovsdb passive connection will listen in port
258 * 6640 which can be overridden using the ovsdb.listenPort system property.
261 public synchronized boolean startOvsdbManagerWithSsl(final String ovsdbListenIp, final int ovsdbListenPort,
262 final ICertificateManager certificateManagerSrv,
263 final String[] protocols, final String[] cipherSuites) {
264 if (!singletonCreated.getAndSet(true)) {
265 new Thread(() -> ovsdbManagerWithSsl(ovsdbListenIp, ovsdbListenPort,
266 certificateManagerSrv, protocols, cipherSuites)).start();
274 public synchronized boolean restartOvsdbManagerWithSsl(final String ovsdbListenIp,
275 final int ovsdbListenPort,
276 final ICertificateManager certificateManagerSrv,
277 final String[] protocols,
278 final String[] cipherSuites) {
279 if (singletonCreated.getAndSet(false) && serverChannel != null) {
280 serverChannel.close();
281 LOG.info("Server channel closed");
283 serverChannel = null;
284 return startOvsdbManagerWithSsl(ovsdbListenIp, ovsdbListenPort,
285 certificateManagerSrv, protocols, cipherSuites);
289 * OVSDB Passive listening thread that uses Netty ServerBootstrap to open
290 * passive connection handle channel callbacks.
291 * If the SSL flag is enabled, the method internally will establish TLS communication using the default
292 * ODL certificateManager SSLContext and attributes.
294 private void ovsdbManager(final String ip, final int port) {
296 if (certManagerSrv == null) {
297 LOG.error("Certificate Manager service is not available cannot establish the SSL communication.");
300 ovsdbManagerWithSsl(ip, port, certManagerSrv, certManagerSrv.getTlsProtocols(),
301 certManagerSrv.getCipherSuites());
303 ovsdbManagerWithSsl(ip, port, null /* SslContext */, null, null);
308 * OVSDB Passive listening thread that uses Netty ServerBootstrap to open
309 * passive connection with Ssl and handle channel callbacks.
311 @SuppressWarnings("checkstyle:IllegalCatch")
312 private void ovsdbManagerWithSsl(final String ip, final int port, final ICertificateManager certificateManagerSrv,
313 final String[] protocols, final String[] cipherSuites) {
314 EventLoopGroup bossGroup = new NioEventLoopGroup();
315 EventLoopGroup workerGroup = new NioEventLoopGroup();
317 ServerBootstrap serverBootstrap = new ServerBootstrap();
318 serverBootstrap.group(bossGroup, workerGroup)
319 .channel(NioServerSocketChannel.class)
320 .option(ChannelOption.SO_BACKLOG, 100)
321 .handler(new LoggingHandler(LogLevel.INFO))
322 .childHandler(new ChannelInitializer<SocketChannel>() {
324 public void initChannel(final SocketChannel channel) throws Exception {
325 LOG.debug("New Passive channel created : {}", channel);
326 if (certificateManagerSrv != null && certificateManagerSrv.getServerContext() != null) {
327 /* Add SSL handler first if SSL context is provided */
328 SSLContext sslContext = certificateManagerSrv.getServerContext();
329 SSLEngine engine = sslContext.createSSLEngine();
330 engine.setUseClientMode(false); // work in a server mode
331 engine.setNeedClientAuth(true); // need client authentication
332 if (protocols != null && protocols.length > 0) {
333 //Set supported protocols
334 engine.setEnabledProtocols(protocols);
335 LOG.debug("Supported ssl protocols {}",
336 Arrays.toString(engine.getSupportedProtocols()));
337 LOG.debug("Enabled ssl protocols {}",
338 Arrays.toString(engine.getEnabledProtocols()));
340 if (cipherSuites != null && cipherSuites.length > 0) {
341 //Set supported cipher suites
342 engine.setEnabledCipherSuites(cipherSuites);
343 LOG.debug("Enabled cipher suites {}",
344 Arrays.toString(engine.getEnabledCipherSuites()));
346 channel.pipeline().addLast("ssl", new SslHandler(engine));
349 channel.pipeline().addLast(
350 new JsonRpcDecoder(jsonRpcDecoderMaxFrameLength),
351 new StringEncoder(CharsetUtil.UTF_8),
352 new IdleStateHandler(IDLE_READER_TIMEOUT, 0, 0),
353 new ReadTimeoutHandler(READ_TIMEOUT),
354 new ExceptionHandler(OvsdbConnectionService.this));
356 handleNewPassiveConnection(channel);
359 serverBootstrap.option(ChannelOption.TCP_NODELAY, true);
360 serverBootstrap.option(ChannelOption.RCVBUF_ALLOCATOR,
361 new AdaptiveRecvByteBufAllocator(65535, 65535, 65535));
363 ChannelFuture channelFuture = serverBootstrap.bind(ip, port).sync();
364 Channel serverListenChannel = channelFuture.channel();
365 serverChannel = serverListenChannel;
366 // Wait until the server socket is closed.
367 serverListenChannel.closeFuture().sync();
368 } catch (InterruptedException e) {
369 LOG.error("Thread interrupted", e);
370 } catch (Throwable throwable) {
371 // sync() re-throws exceptions declared as Throwable, so the compiler doesn't see them
372 LOG.error("Error while binding to address {}, port {}", ip, port, throwable);
375 // Shut down all event loops to terminate all threads.
376 bossGroup.shutdownGracefully();
377 workerGroup.shutdownGracefully();
381 private static void handleNewPassiveConnection(final OvsdbClient client) {
382 ListenableFuture<List<String>> echoFuture = client.echo();
383 LOG.debug("Send echo message to probe the OVSDB switch {}",client.getConnectionInfo());
384 Futures.addCallback(echoFuture, new FutureCallback<List<String>>() {
386 public void onSuccess(@Nullable final List<String> result) {
387 LOG.debug("Probe was successful to OVSDB switch {}",client.getConnectionInfo());
388 List<OvsdbClient> clientsFromSameNode = getPassiveClientsFromSameNode(client);
389 if (clientsFromSameNode.size() == 0) {
390 notifyListenerForPassiveConnection(client);
392 STALE_PASSIVE_CONNECTION_SERVICE.handleNewPassiveConnection(client, clientsFromSameNode);
397 public void onFailure(final Throwable failureException) {
398 LOG.error("Probe failed to OVSDB switch. Disconnecting the channel {}", client.getConnectionInfo());
401 }, CONNECTION_NOTIFIER_SERVICE);
404 private static void handleNewPassiveConnection(final Channel channel) {
405 if (!channel.isOpen()) {
406 LOG.warn("Channel {} is not open, skipped further processing of the connection.",channel);
409 SslHandler sslHandler = (SslHandler) channel.pipeline().get("ssl");
410 if (sslHandler != null) {
411 class HandleNewPassiveSslRunner implements Runnable {
412 private int retryTimes = 3;
414 private void retry() {
415 if (retryTimes > 0) {
416 EXECUTOR_SERVICE.schedule(this, RETRY_PERIOD, TimeUnit.MILLISECONDS);
418 LOG.debug("channel closed {}", channel);
419 channel.disconnect();
426 HandshakeStatus status = sslHandler.engine().getHandshakeStatus();
427 LOG.debug("Handshake status {}", status);
430 case NOT_HANDSHAKING:
431 if (sslHandler.engine().getSession().getCipherSuite()
432 .equals("SSL_NULL_WITH_NULL_NULL")) {
433 // Not begin handshake yet. Retry later.
434 LOG.debug("handshake not begin yet {}", status);
437 //Check if peer is trusted before notifying listeners
439 sslHandler.engine().getSession().getPeerCertificates();
440 //Handshake done. Notify listener.
441 OvsdbClient client = getChannelClient(channel, ConnectionType.PASSIVE,
442 SocketConnectionType.SSL);
443 handleNewPassiveConnection(client);
444 } catch (SSLPeerUnverifiedException e) {
445 //Trust manager is still checking peer certificate. Retry later
446 LOG.debug("Peer certifiacte is not verified yet {}", status);
454 //Handshake still ongoing. Retry later.
455 LOG.debug("handshake not done yet {}", status);
460 if (sslHandler.engine().getSession().getCipherSuite()
461 .equals("SSL_NULL_WITH_NULL_NULL")) {
462 /* peer not authenticated. No need to notify listener in this case. */
463 LOG.error("Ssl handshake fail. channel {}", channel);
464 channel.disconnect();
467 * peer is authenticated. Give some time to wait for completion.
468 * If status is still NEED_WRAP, client might already disconnect.
469 * This happens when the first time client connects to controller in two-way handshake.
470 * After obtaining controller certificate, client will disconnect and start
471 * new connection with controller certificate it obtained.
472 * In this case no need to do anything for the first connection attempt. Just skip
473 * since client will reconnect later.
475 LOG.debug("handshake not done yet {}", status);
481 LOG.error("unknown hadshake status {}", status);
486 EXECUTOR_SERVICE.schedule(new HandleNewPassiveSslRunner(),
487 RETRY_PERIOD, TimeUnit.MILLISECONDS);
489 EXECUTOR_SERVICE.execute(() -> {
490 OvsdbClient client = getChannelClient(channel, ConnectionType.PASSIVE,
491 SocketConnectionType.NON_SSL);
492 handleNewPassiveConnection(client);
497 public static void channelClosed(final OvsdbClient client) {
498 LOG.info("Connection closed {}", client.getConnectionInfo());
499 CONNECTIONS.remove(client);
500 if (client.isConnectionPublished()) {
501 for (OvsdbConnectionListener listener : CONNECTION_LISTENERS) {
502 listener.disconnected(client);
505 STALE_PASSIVE_CONNECTION_SERVICE.clientDisconnected(client);
509 public Collection<OvsdbClient> getConnections() {
510 return CONNECTIONS.keySet();
514 public void close() throws Exception {
515 LOG.info("OvsdbConnectionService closed");
516 JsonRpcEndpoint.close();
520 public OvsdbClient getClient(final Channel channel) {
521 for (Entry<OvsdbClient, Channel> entry : CONNECTIONS.entrySet()) {
522 OvsdbClient client = entry.getKey();
523 Channel ctx = entry.getValue();
524 if (ctx.equals(channel)) {
531 private static List<OvsdbClient> getPassiveClientsFromSameNode(final OvsdbClient ovsdbClient) {
532 List<OvsdbClient> passiveClients = new ArrayList<>();
533 for (OvsdbClient client : CONNECTIONS.keySet()) {
534 if (!client.equals(ovsdbClient)
535 && client.getConnectionInfo().getRemoteAddress()
536 .equals(ovsdbClient.getConnectionInfo().getRemoteAddress())
537 && client.getConnectionInfo().getType() == ConnectionType.PASSIVE) {
538 passiveClients.add(client);
541 return passiveClients;
544 public static void notifyListenerForPassiveConnection(final OvsdbClient client) {
545 client.setConnectionPublished(true);
546 for (final OvsdbConnectionListener listener : CONNECTION_LISTENERS) {
547 CONNECTION_NOTIFIER_SERVICE.execute(() -> {
548 LOG.trace("Connection {} notified to listener {}", client.getConnectionInfo(), listener);
549 listener.connected(client);
554 public void setOvsdbRpcTaskTimeout(final int timeout) {
555 JsonRpcEndpoint.setReaperInterval(timeout);
561 * @param flag boolean for using ssl
563 public void setUseSsl(final boolean flag) {
568 * Blueprint property setter method. Blueprint call this method and set the value of json rpc decoder
569 * max frame length to the value configured for config option (json-rpc-decoder-max-frame-length) in
570 * the configuration file. This option is only configured at the boot time of the controller. Any
571 * change at the run time will have no impact.
572 * @param maxFrameLength Max frame length (default : 100000)
574 public void setJsonRpcDecoderMaxFrameLength(final int maxFrameLength) {
575 jsonRpcDecoderMaxFrameLength = maxFrameLength;
576 LOG.info("Json Rpc Decoder Max Frame Length set to : {}", jsonRpcDecoderMaxFrameLength);
579 public void setOvsdbListenerIp(final String ip) {
580 LOG.info("OVSDB IP for listening connection is set to : {}", ip);
584 public void setOvsdbListenerPort(final int portNumber) {
585 LOG.info("OVSDB port for listening connection is set to : {}", portNumber);
586 listenerPort = portNumber;
589 public void updateConfigParameter(final Map<String, Object> configParameters) {
590 if (configParameters != null && !configParameters.isEmpty()) {
591 LOG.debug("Config parameters received : {}", configParameters.entrySet());
592 for (Map.Entry<String, Object> paramEntry : configParameters.entrySet()) {
593 if (paramEntry.getKey().equalsIgnoreCase(OVSDB_RPC_TASK_TIMEOUT_PARAM)) {
594 setOvsdbRpcTaskTimeout(Integer.parseInt((String)paramEntry.getValue()));
595 } else if (paramEntry.getKey().equalsIgnoreCase(USE_SSL)) {
596 useSSL = Boolean.parseBoolean(paramEntry.getValue().toString());