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.fasterxml.jackson.annotation.JsonInclude.Include;
12 import com.fasterxml.jackson.databind.DeserializationFeature;
13 import com.fasterxml.jackson.databind.ObjectMapper;
14 import com.google.common.util.concurrent.FutureCallback;
15 import com.google.common.util.concurrent.Futures;
16 import com.google.common.util.concurrent.ListenableFuture;
17 import com.google.common.util.concurrent.ThreadFactoryBuilder;
18 import io.netty.bootstrap.Bootstrap;
19 import io.netty.bootstrap.ServerBootstrap;
20 import io.netty.channel.AdaptiveRecvByteBufAllocator;
21 import io.netty.channel.Channel;
22 import io.netty.channel.ChannelFuture;
23 import io.netty.channel.ChannelInitializer;
24 import io.netty.channel.ChannelOption;
25 import io.netty.channel.EventLoopGroup;
26 import io.netty.channel.nio.NioEventLoopGroup;
27 import io.netty.channel.socket.SocketChannel;
28 import io.netty.channel.socket.nio.NioServerSocketChannel;
29 import io.netty.channel.socket.nio.NioSocketChannel;
30 import io.netty.handler.codec.string.StringEncoder;
31 import io.netty.handler.logging.LogLevel;
32 import io.netty.handler.logging.LoggingHandler;
33 import io.netty.handler.ssl.SslHandler;
34 import io.netty.handler.timeout.IdleStateHandler;
35 import io.netty.handler.timeout.ReadTimeoutHandler;
36 import io.netty.util.CharsetUtil;
37 import java.net.InetAddress;
38 import java.util.ArrayList;
39 import java.util.Arrays;
40 import java.util.Collection;
41 import java.util.List;
43 import java.util.Map.Entry;
45 import java.util.concurrent.ConcurrentHashMap;
46 import java.util.concurrent.ExecutorService;
47 import java.util.concurrent.Executors;
48 import java.util.concurrent.ScheduledExecutorService;
49 import java.util.concurrent.TimeUnit;
50 import java.util.concurrent.atomic.AtomicBoolean;
51 import javax.annotation.Nullable;
52 import javax.inject.Inject;
53 import javax.inject.Singleton;
54 import javax.net.ssl.SSLContext;
55 import javax.net.ssl.SSLEngine;
56 import javax.net.ssl.SSLEngineResult.HandshakeStatus;
57 import javax.net.ssl.SSLPeerUnverifiedException;
58 import org.apache.aries.blueprint.annotation.service.Reference;
59 import org.apache.aries.blueprint.annotation.service.Service;
60 import org.opendaylight.aaa.cert.api.ICertificateManager;
61 import org.opendaylight.ovsdb.lib.OvsdbClient;
62 import org.opendaylight.ovsdb.lib.OvsdbConnection;
63 import org.opendaylight.ovsdb.lib.OvsdbConnectionInfo.ConnectionType;
64 import org.opendaylight.ovsdb.lib.OvsdbConnectionInfo.SocketConnectionType;
65 import org.opendaylight.ovsdb.lib.OvsdbConnectionListener;
66 import org.opendaylight.ovsdb.lib.jsonrpc.ExceptionHandler;
67 import org.opendaylight.ovsdb.lib.jsonrpc.JsonRpcDecoder;
68 import org.opendaylight.ovsdb.lib.jsonrpc.JsonRpcEndpoint;
69 import org.slf4j.Logger;
70 import org.slf4j.LoggerFactory;
73 * OvsDBConnectionService provides OVSDB connection management functionality which includes
74 * both Active and Passive connections.
75 * From the Library perspective, Active OVSDB connections are those that are initiated from
76 * the Controller towards the ovsdb-manager.
77 * While Passive OVSDB connections are those that are initiated from the ovs towards
80 * <p>Applications that use OvsDBConnectionService can use the OvsDBConnection class' connect APIs
81 * to initiate Active connections and can listen to the asynchronous Passive connections via
82 * registerConnectionListener listener API.
84 * <p>The library is designed as Java modular component that can work in both OSGi and non-OSGi
85 * environment. Hence a single instance of the service will be active (via Service Registry in OSGi)
86 * and a Singleton object in a non-OSGi environment.
89 @Service(classes = OvsdbConnection.class)
90 public class OvsdbConnectionService implements AutoCloseable, OvsdbConnection {
91 private static final Logger LOG = LoggerFactory.getLogger(OvsdbConnectionService.class);
92 private static final int IDLE_READER_TIMEOUT = 30;
93 private static final int READ_TIMEOUT = 180;
94 private static final String OVSDB_RPC_TASK_TIMEOUT_PARAM = "ovsdb-rpc-task-timeout";
95 private static final String USE_SSL = "use-ssl";
96 private static final int RETRY_PERIOD = 100; // retry after 100 milliseconds
98 private static final ScheduledExecutorService EXECUTOR_SERVICE = Executors.newScheduledThreadPool(10,
99 new ThreadFactoryBuilder().setNameFormat("OVSDBPassiveConnServ-%d").build());
101 private static final ExecutorService CONNECTION_NOTIFIER_SERVICE = Executors
102 .newCachedThreadPool(new ThreadFactoryBuilder().setNameFormat("OVSDBConnNotifSer-%d").build());
104 private static final StalePassiveConnectionService STALE_PASSIVE_CONNECTION_SERVICE =
105 new StalePassiveConnectionService((client) -> {
106 notifyListenerForPassiveConnection(client);
110 private static final Set<OvsdbConnectionListener> CONNECTION_LISTENERS = ConcurrentHashMap.newKeySet();
111 private static final Map<OvsdbClient, Channel> CONNECTIONS = new ConcurrentHashMap<>();
112 private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper()
113 .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
114 .setSerializationInclusion(Include.NON_NULL);
116 private volatile boolean useSSL = false;
117 private final ICertificateManager certManagerSrv;
119 private volatile int jsonRpcDecoderMaxFrameLength = 100000;
120 private volatile Channel serverChannel;
122 private final AtomicBoolean singletonCreated = new AtomicBoolean(false);
123 private volatile String listenerIp = "0.0.0.0";
124 private volatile int listenerPort = 6640;
127 public OvsdbConnectionService(@Reference(filter = "type=default-certificate-manager")
128 final ICertificateManager certManagerSrv) {
129 this.certManagerSrv = certManagerSrv;
133 * If the SSL flag is enabled, the method internally will establish TLS communication using the default
134 * ODL certificateManager SSLContext and attributes.
137 public OvsdbClient connect(final InetAddress address, final int port) {
139 if (certManagerSrv == null) {
140 LOG.error("Certificate Manager service is not available cannot establish the SSL communication.");
143 return connectWithSsl(address, port, certManagerSrv);
145 return connectWithSsl(address, port, null /* SslContext */);
150 @SuppressWarnings("checkstyle:IllegalCatch")
151 public OvsdbClient connectWithSsl(final InetAddress address, final int port,
152 final ICertificateManager certificateManagerSrv) {
154 Bootstrap bootstrap = new Bootstrap();
155 bootstrap.group(new NioEventLoopGroup());
156 bootstrap.channel(NioSocketChannel.class);
157 bootstrap.option(ChannelOption.TCP_NODELAY, true);
158 bootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(65535, 65535, 65535));
160 bootstrap.handler(new ChannelInitializer<SocketChannel>() {
162 public void initChannel(final SocketChannel channel) throws Exception {
163 if (certificateManagerSrv != null && certificateManagerSrv.getServerContext() != null) {
164 SSLContext sslContext = certificateManagerSrv.getServerContext();
165 /* First add ssl handler if ssl context is given */
167 sslContext.createSSLEngine(address.toString(), port);
168 engine.setUseClientMode(true);
169 channel.pipeline().addLast("ssl", new SslHandler(engine));
171 channel.pipeline().addLast(
172 //new LoggingHandler(LogLevel.INFO),
173 new JsonRpcDecoder(jsonRpcDecoderMaxFrameLength),
174 new StringEncoder(CharsetUtil.UTF_8),
175 new IdleStateHandler(IDLE_READER_TIMEOUT, 0, 0),
176 new ReadTimeoutHandler(READ_TIMEOUT),
177 new ExceptionHandler(OvsdbConnectionService.this));
181 ChannelFuture future = bootstrap.connect(address, port).sync();
182 Channel channel = future.channel();
183 return getChannelClient(channel, ConnectionType.ACTIVE, SocketConnectionType.SSL);
184 } catch (InterruptedException e) {
185 LOG.warn("Failed to connect {}:{}", address, port, e);
186 } catch (Throwable throwable) {
187 // sync() re-throws exceptions declared as Throwable, so the compiler doesn't see them
188 LOG.error("Error while binding to address {}, port {}", address, port, throwable);
195 public void disconnect(final OvsdbClient client) {
196 if (client == null) {
199 Channel channel = CONNECTIONS.get(client);
200 if (channel != null) {
201 //It's an explicit disconnect from user, so no need to notify back
202 //to user about the disconnect.
203 client.setConnectionPublished(false);
204 channel.disconnect();
206 CONNECTIONS.remove(client);
210 public void registerConnectionListener(final OvsdbConnectionListener listener) {
211 LOG.info("registerConnectionListener: registering {}", listener.getClass().getSimpleName());
212 CONNECTION_LISTENERS.add(listener);
213 notifyAlreadyExistingConnectionsToListener(listener);
216 private void notifyAlreadyExistingConnectionsToListener(final OvsdbConnectionListener listener) {
217 for (final OvsdbClient client : getConnections()) {
218 CONNECTION_NOTIFIER_SERVICE.execute(() -> {
219 LOG.trace("Connection {} notified to listener {}", client.getConnectionInfo(), listener);
220 listener.connected(client);
226 public void unregisterConnectionListener(final OvsdbConnectionListener listener) {
227 CONNECTION_LISTENERS.remove(listener);
230 private static OvsdbClient getChannelClient(final Channel channel, final ConnectionType type,
231 final SocketConnectionType socketConnType) {
233 JsonRpcEndpoint endpoint = new JsonRpcEndpoint(OBJECT_MAPPER, channel);
234 channel.pipeline().addLast(endpoint);
236 OvsdbClientImpl client = new OvsdbClientImpl(endpoint, channel, type, socketConnType);
237 client.setConnectionPublished(true);
238 CONNECTIONS.put(client, channel);
239 channel.closeFuture().addListener(new ChannelConnectionHandler(client));
244 * Method that initiates the Passive OVSDB channel listening functionality.
245 * By default the ovsdb passive connection will listen in port 6640 which can
246 * be overridden using the ovsdb.listenPort system property.
249 public synchronized boolean startOvsdbManager() {
250 final int ovsdbListenerPort = this.listenerPort;
251 final String ovsdbListenerIp = this.listenerIp;
252 if (!singletonCreated.getAndSet(true)) {
253 LOG.info("startOvsdbManager: Starting");
254 new Thread(() -> ovsdbManager(ovsdbListenerIp, ovsdbListenerPort)).start();
262 * Method that initiates the Passive OVSDB channel listening functionality
263 * with ssl.By default the ovsdb passive connection will listen in port
264 * 6640 which can be overridden using the ovsdb.listenPort system property.
267 public synchronized boolean startOvsdbManagerWithSsl(final String ovsdbListenIp, final int ovsdbListenPort,
268 final ICertificateManager certificateManagerSrv,
269 final String[] protocols, final String[] cipherSuites) {
270 if (!singletonCreated.getAndSet(true)) {
271 new Thread(() -> ovsdbManagerWithSsl(ovsdbListenIp, ovsdbListenPort,
272 certificateManagerSrv, protocols, cipherSuites)).start();
280 public synchronized boolean restartOvsdbManagerWithSsl(final String ovsdbListenIp,
281 final int ovsdbListenPort,
282 final ICertificateManager certificateManagerSrv,
283 final String[] protocols,
284 final String[] cipherSuites) {
285 if (singletonCreated.getAndSet(false) && serverChannel != null) {
286 serverChannel.close();
287 LOG.info("Server channel closed");
289 serverChannel = null;
290 return startOvsdbManagerWithSsl(ovsdbListenIp, ovsdbListenPort,
291 certificateManagerSrv, protocols, cipherSuites);
295 * OVSDB Passive listening thread that uses Netty ServerBootstrap to open
296 * passive connection handle channel callbacks.
297 * If the SSL flag is enabled, the method internally will establish TLS communication using the default
298 * ODL certificateManager SSLContext and attributes.
300 private void ovsdbManager(final String ip, final int port) {
302 if (certManagerSrv == null) {
303 LOG.error("Certificate Manager service is not available cannot establish the SSL communication.");
306 ovsdbManagerWithSsl(ip, port, certManagerSrv, certManagerSrv.getTlsProtocols(),
307 certManagerSrv.getCipherSuites());
309 ovsdbManagerWithSsl(ip, port, null /* SslContext */, null, null);
314 * OVSDB Passive listening thread that uses Netty ServerBootstrap to open
315 * passive connection with Ssl and handle channel callbacks.
317 @SuppressWarnings("checkstyle:IllegalCatch")
318 private void ovsdbManagerWithSsl(final String ip, final int port, final ICertificateManager certificateManagerSrv,
319 final String[] protocols, final String[] cipherSuites) {
320 EventLoopGroup bossGroup = new NioEventLoopGroup();
321 EventLoopGroup workerGroup = new NioEventLoopGroup();
323 ServerBootstrap serverBootstrap = new ServerBootstrap();
324 serverBootstrap.group(bossGroup, workerGroup)
325 .channel(NioServerSocketChannel.class)
326 .option(ChannelOption.SO_BACKLOG, 100)
327 .handler(new LoggingHandler(LogLevel.INFO))
328 .childHandler(new ChannelInitializer<SocketChannel>() {
330 public void initChannel(final SocketChannel channel) throws Exception {
331 LOG.debug("New Passive channel created : {}", channel);
332 if (certificateManagerSrv != null && certificateManagerSrv.getServerContext() != null) {
333 /* Add SSL handler first if SSL context is provided */
334 SSLContext sslContext = certificateManagerSrv.getServerContext();
335 SSLEngine engine = sslContext.createSSLEngine();
336 engine.setUseClientMode(false); // work in a server mode
337 engine.setNeedClientAuth(true); // need client authentication
338 if (protocols != null && protocols.length > 0) {
339 //Set supported protocols
340 engine.setEnabledProtocols(protocols);
341 LOG.debug("Supported ssl protocols {}",
342 Arrays.toString(engine.getSupportedProtocols()));
343 LOG.debug("Enabled ssl protocols {}",
344 Arrays.toString(engine.getEnabledProtocols()));
346 if (cipherSuites != null && cipherSuites.length > 0) {
347 //Set supported cipher suites
348 engine.setEnabledCipherSuites(cipherSuites);
349 LOG.debug("Enabled cipher suites {}",
350 Arrays.toString(engine.getEnabledCipherSuites()));
352 channel.pipeline().addLast("ssl", new SslHandler(engine));
355 channel.pipeline().addLast(
356 new JsonRpcDecoder(jsonRpcDecoderMaxFrameLength),
357 new StringEncoder(CharsetUtil.UTF_8),
358 new IdleStateHandler(IDLE_READER_TIMEOUT, 0, 0),
359 new ReadTimeoutHandler(READ_TIMEOUT),
360 new ExceptionHandler(OvsdbConnectionService.this));
362 handleNewPassiveConnection(channel);
365 serverBootstrap.option(ChannelOption.TCP_NODELAY, true);
366 serverBootstrap.option(ChannelOption.RCVBUF_ALLOCATOR,
367 new AdaptiveRecvByteBufAllocator(65535, 65535, 65535));
369 ChannelFuture channelFuture = serverBootstrap.bind(ip, port).sync();
370 Channel serverListenChannel = channelFuture.channel();
371 serverChannel = serverListenChannel;
372 // Wait until the server socket is closed.
373 serverListenChannel.closeFuture().sync();
374 } catch (InterruptedException e) {
375 LOG.error("Thread interrupted", e);
376 } catch (Throwable throwable) {
377 // sync() re-throws exceptions declared as Throwable, so the compiler doesn't see them
378 LOG.error("Error while binding to address {}, port {}", ip, port, throwable);
381 // Shut down all event loops to terminate all threads.
382 bossGroup.shutdownGracefully();
383 workerGroup.shutdownGracefully();
387 private static void handleNewPassiveConnection(final OvsdbClient client) {
388 ListenableFuture<List<String>> echoFuture = client.echo();
389 LOG.debug("Send echo message to probe the OVSDB switch {}",client.getConnectionInfo());
390 Futures.addCallback(echoFuture, new FutureCallback<List<String>>() {
392 public void onSuccess(@Nullable final List<String> result) {
393 LOG.debug("Probe was successful to OVSDB switch {}",client.getConnectionInfo());
394 List<OvsdbClient> clientsFromSameNode = getPassiveClientsFromSameNode(client);
395 if (clientsFromSameNode.size() == 0) {
396 notifyListenerForPassiveConnection(client);
398 STALE_PASSIVE_CONNECTION_SERVICE.handleNewPassiveConnection(client, clientsFromSameNode);
403 public void onFailure(final Throwable failureException) {
404 LOG.error("Probe failed to OVSDB switch. Disconnecting the channel {}", client.getConnectionInfo());
407 }, CONNECTION_NOTIFIER_SERVICE);
410 private static void handleNewPassiveConnection(final Channel channel) {
411 if (!channel.isOpen()) {
412 LOG.warn("Channel {} is not open, skipped further processing of the connection.",channel);
415 SslHandler sslHandler = (SslHandler) channel.pipeline().get("ssl");
416 if (sslHandler != null) {
417 class HandleNewPassiveSslRunner implements Runnable {
418 private int retryTimes = 3;
420 private void retry() {
421 if (retryTimes > 0) {
422 EXECUTOR_SERVICE.schedule(this, RETRY_PERIOD, TimeUnit.MILLISECONDS);
424 LOG.debug("channel closed {}", channel);
425 channel.disconnect();
432 HandshakeStatus status = sslHandler.engine().getHandshakeStatus();
433 LOG.debug("Handshake status {}", status);
436 case NOT_HANDSHAKING:
437 if (sslHandler.engine().getSession().getCipherSuite()
438 .equals("SSL_NULL_WITH_NULL_NULL")) {
439 // Not begin handshake yet. Retry later.
440 LOG.debug("handshake not begin yet {}", status);
443 //Check if peer is trusted before notifying listeners
445 sslHandler.engine().getSession().getPeerCertificates();
446 //Handshake done. Notify listener.
447 OvsdbClient client = getChannelClient(channel, ConnectionType.PASSIVE,
448 SocketConnectionType.SSL);
449 handleNewPassiveConnection(client);
450 } catch (SSLPeerUnverifiedException e) {
451 //Trust manager is still checking peer certificate. Retry later
452 LOG.debug("Peer certifiacte is not verified yet {}", status);
460 //Handshake still ongoing. Retry later.
461 LOG.debug("handshake not done yet {}", status);
466 if (sslHandler.engine().getSession().getCipherSuite()
467 .equals("SSL_NULL_WITH_NULL_NULL")) {
468 /* peer not authenticated. No need to notify listener in this case. */
469 LOG.error("Ssl handshake fail. channel {}", channel);
470 channel.disconnect();
473 * peer is authenticated. Give some time to wait for completion.
474 * If status is still NEED_WRAP, client might already disconnect.
475 * This happens when the first time client connects to controller in two-way handshake.
476 * After obtaining controller certificate, client will disconnect and start
477 * new connection with controller certificate it obtained.
478 * In this case no need to do anything for the first connection attempt. Just skip
479 * since client will reconnect later.
481 LOG.debug("handshake not done yet {}", status);
487 LOG.error("unknown hadshake status {}", status);
492 EXECUTOR_SERVICE.schedule(new HandleNewPassiveSslRunner(),
493 RETRY_PERIOD, TimeUnit.MILLISECONDS);
495 EXECUTOR_SERVICE.execute(() -> {
496 OvsdbClient client = getChannelClient(channel, ConnectionType.PASSIVE,
497 SocketConnectionType.NON_SSL);
498 handleNewPassiveConnection(client);
503 public static void channelClosed(final OvsdbClient client) {
504 LOG.info("Connection closed {}", client.getConnectionInfo());
505 CONNECTIONS.remove(client);
506 if (client.isConnectionPublished()) {
507 for (OvsdbConnectionListener listener : CONNECTION_LISTENERS) {
508 listener.disconnected(client);
511 STALE_PASSIVE_CONNECTION_SERVICE.clientDisconnected(client);
515 public Collection<OvsdbClient> getConnections() {
516 return CONNECTIONS.keySet();
520 public void close() throws Exception {
521 LOG.info("OvsdbConnectionService closed");
522 JsonRpcEndpoint.close();
526 public OvsdbClient getClient(final Channel channel) {
527 for (Entry<OvsdbClient, Channel> entry : CONNECTIONS.entrySet()) {
528 OvsdbClient client = entry.getKey();
529 Channel ctx = entry.getValue();
530 if (ctx.equals(channel)) {
537 private static List<OvsdbClient> getPassiveClientsFromSameNode(final OvsdbClient ovsdbClient) {
538 List<OvsdbClient> passiveClients = new ArrayList<>();
539 for (OvsdbClient client : CONNECTIONS.keySet()) {
540 if (!client.equals(ovsdbClient)
541 && client.getConnectionInfo().getRemoteAddress()
542 .equals(ovsdbClient.getConnectionInfo().getRemoteAddress())
543 && client.getConnectionInfo().getType() == ConnectionType.PASSIVE) {
544 passiveClients.add(client);
547 return passiveClients;
550 public static void notifyListenerForPassiveConnection(final OvsdbClient client) {
551 client.setConnectionPublished(true);
552 for (final OvsdbConnectionListener listener : CONNECTION_LISTENERS) {
553 CONNECTION_NOTIFIER_SERVICE.execute(() -> {
554 LOG.trace("Connection {} notified to listener {}", client.getConnectionInfo(), listener);
555 listener.connected(client);
560 public void setOvsdbRpcTaskTimeout(final int timeout) {
561 JsonRpcEndpoint.setReaperInterval(timeout);
567 * @param flag boolean for using ssl
569 public void setUseSsl(final boolean flag) {
574 * Blueprint property setter method. Blueprint call this method and set the value of json rpc decoder
575 * max frame length to the value configured for config option (json-rpc-decoder-max-frame-length) in
576 * the configuration file. This option is only configured at the boot time of the controller. Any
577 * change at the run time will have no impact.
578 * @param maxFrameLength Max frame length (default : 100000)
580 public void setJsonRpcDecoderMaxFrameLength(final int maxFrameLength) {
581 jsonRpcDecoderMaxFrameLength = maxFrameLength;
582 LOG.info("Json Rpc Decoder Max Frame Length set to : {}", jsonRpcDecoderMaxFrameLength);
585 public void setOvsdbListenerIp(final String ip) {
586 LOG.info("OVSDB IP for listening connection is set to : {}", ip);
590 public void setOvsdbListenerPort(final int portNumber) {
591 LOG.info("OVSDB port for listening connection is set to : {}", portNumber);
592 listenerPort = portNumber;
595 public void updateConfigParameter(final Map<String, Object> configParameters) {
596 if (configParameters != null && !configParameters.isEmpty()) {
597 LOG.debug("Config parameters received : {}", configParameters.entrySet());
598 for (Map.Entry<String, Object> paramEntry : configParameters.entrySet()) {
599 if (paramEntry.getKey().equalsIgnoreCase(OVSDB_RPC_TASK_TIMEOUT_PARAM)) {
600 setOvsdbRpcTaskTimeout(Integer.parseInt((String)paramEntry.getValue()));
601 } else if (paramEntry.getKey().equalsIgnoreCase(USE_SSL)) {
602 useSSL = Boolean.parseBoolean(paramEntry.getValue().toString());