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.net.ssl.SSLContext;
54 import javax.net.ssl.SSLEngine;
55 import javax.net.ssl.SSLEngineResult.HandshakeStatus;
56 import javax.net.ssl.SSLPeerUnverifiedException;
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.opendaylight.ovsdb.lib.jsonrpc.JsonRpcServiceBinderHandler;
67 import org.opendaylight.ovsdb.lib.message.OvsdbRPC;
68 import org.slf4j.Logger;
69 import org.slf4j.LoggerFactory;
72 * OvsDBConnectionService provides OVSDB connection management functionality which includes
73 * both Active and Passive connections.
74 * From the Library perspective, Active OVSDB connections are those that are initiated from
75 * the Controller towards the ovsdb-manager.
76 * While Passive OVSDB connections are those that are initiated from the ovs towards
79 * <p>Applications that use OvsDBConnectionService can use the OvsDBConnection class' connect APIs
80 * to initiate Active connections and can listen to the asynchronous Passive connections via
81 * registerConnectionListener listener API.
83 * <p>The library is designed as Java modular component that can work in both OSGi and non-OSGi
84 * environment. Hence a single instance of the service will be active (via Service Registry in OSGi)
85 * and a Singleton object in a non-OSGi environment.
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(ICertificateManager certManagerSrv) {
122 this.certManagerSrv = certManagerSrv;
126 * If the SSL flag is enabled, the method internally will establish TLS communication using the default
127 * ODL certificateManager SSLContext and attributes.
130 public OvsdbClient connect(final InetAddress address, final int port) {
132 if (certManagerSrv == null) {
133 LOG.error("Certificate Manager service is not available cannot establish the SSL communication.");
136 return connectWithSsl(address, port, certManagerSrv);
138 return connectWithSsl(address, port, null /* SslContext */);
143 public OvsdbClient connectWithSsl(final InetAddress address, final int port,
144 final ICertificateManager certificateManagerSrv) {
146 Bootstrap bootstrap = new Bootstrap();
147 bootstrap.group(new NioEventLoopGroup());
148 bootstrap.channel(NioSocketChannel.class);
149 bootstrap.option(ChannelOption.TCP_NODELAY, true);
150 bootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(65535, 65535, 65535));
152 bootstrap.handler(new ChannelInitializer<SocketChannel>() {
154 public void initChannel(SocketChannel channel) throws Exception {
155 if (certificateManagerSrv != null && certificateManagerSrv.getServerContext() != null) {
156 SSLContext sslContext = certificateManagerSrv.getServerContext();
157 /* First add ssl handler if ssl context is given */
159 sslContext.createSSLEngine(address.toString(), port);
160 engine.setUseClientMode(true);
161 channel.pipeline().addLast("ssl", new SslHandler(engine));
163 channel.pipeline().addLast(
164 //new LoggingHandler(LogLevel.INFO),
165 new JsonRpcDecoder(jsonRpcDecoderMaxFrameLength),
166 new StringEncoder(CharsetUtil.UTF_8),
167 new IdleStateHandler(IDLE_READER_TIMEOUT, 0, 0),
168 new ReadTimeoutHandler(READ_TIMEOUT),
169 new ExceptionHandler(OvsdbConnectionService.this));
173 ChannelFuture future = bootstrap.connect(address, port).sync();
174 Channel channel = future.channel();
175 return getChannelClient(channel, ConnectionType.ACTIVE, SocketConnectionType.SSL);
176 } catch (InterruptedException e) {
177 LOG.warn("Failed to connect {}:{}", address, port, e);
183 public void disconnect(OvsdbClient client) {
184 if (client == null) {
187 Channel channel = CONNECTIONS.get(client);
188 if (channel != null) {
189 //It's an explicit disconnect from user, so no need to notify back
190 //to user about the disconnect.
191 client.setConnectionPublished(false);
192 channel.disconnect();
194 CONNECTIONS.remove(client);
198 public void registerConnectionListener(OvsdbConnectionListener listener) {
199 LOG.info("registerConnectionListener: registering {}", listener.getClass().getSimpleName());
200 CONNECTION_LISTENERS.add(listener);
201 notifyAlreadyExistingConnectionsToListener(listener);
204 private void notifyAlreadyExistingConnectionsToListener(final OvsdbConnectionListener listener) {
205 for (final OvsdbClient client : getConnections()) {
206 CONNECTION_NOTIFIER_SERVICE.execute(() -> {
207 LOG.trace("Connection {} notified to listener {}", client.getConnectionInfo(), listener);
208 listener.connected(client);
214 public void unregisterConnectionListener(OvsdbConnectionListener listener) {
215 CONNECTION_LISTENERS.remove(listener);
218 private static OvsdbClient getChannelClient(Channel channel, ConnectionType type,
219 SocketConnectionType socketConnType) {
220 ObjectMapper objectMapper = new ObjectMapper();
221 objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
222 objectMapper.setSerializationInclusion(Include.NON_NULL);
224 JsonRpcEndpoint factory = new JsonRpcEndpoint(objectMapper, channel);
225 JsonRpcServiceBinderHandler binderHandler = new JsonRpcServiceBinderHandler(factory);
226 binderHandler.setContext(channel);
227 channel.pipeline().addLast(binderHandler);
229 OvsdbRPC rpc = factory.getClient(channel, OvsdbRPC.class);
230 OvsdbClientImpl client = new OvsdbClientImpl(rpc, channel, type, socketConnType);
231 client.setConnectionPublished(true);
232 CONNECTIONS.put(client, channel);
233 ChannelFuture closeFuture = channel.closeFuture();
234 closeFuture.addListener(new ChannelConnectionHandler(client));
239 * Method that initiates the Passive OVSDB channel listening functionality.
240 * By default the ovsdb passive connection will listen in port 6640 which can
241 * be overridden using the ovsdb.listenPort system property.
244 public synchronized boolean startOvsdbManager() {
245 final int ovsdbListenerPort = this.listenerPort;
246 final String ovsdbListenerIp = this.listenerIp;
247 if (!singletonCreated.getAndSet(true)) {
248 LOG.info("startOvsdbManager: Starting");
249 new Thread(() -> ovsdbManager(ovsdbListenerIp, ovsdbListenerPort)).start();
257 * Method that initiates the Passive OVSDB channel listening functionality
258 * with ssl.By default the ovsdb passive connection will listen in port
259 * 6640 which can be overridden using the ovsdb.listenPort system property.
262 public synchronized boolean startOvsdbManagerWithSsl(final String ovsdbListenIp, final int ovsdbListenPort,
263 final ICertificateManager certificateManagerSrv,
264 String[] protocols, String[] cipherSuites) {
265 if (!singletonCreated.getAndSet(true)) {
266 new Thread(() -> ovsdbManagerWithSsl(ovsdbListenIp, ovsdbListenPort,
267 certificateManagerSrv, protocols, cipherSuites)).start();
275 public synchronized boolean restartOvsdbManagerWithSsl(final String ovsdbListenIp,
276 final int ovsdbListenPort,
277 final ICertificateManager certificateManagerSrv,
278 final String[] protocols,
279 final String[] cipherSuites) {
280 if (singletonCreated.getAndSet(false) && serverChannel != null) {
281 serverChannel.close();
282 LOG.info("Server channel closed");
284 serverChannel = null;
285 return startOvsdbManagerWithSsl(ovsdbListenIp, ovsdbListenPort,
286 certificateManagerSrv, protocols, cipherSuites);
290 * OVSDB Passive listening thread that uses Netty ServerBootstrap to open
291 * passive connection handle channel callbacks.
292 * If the SSL flag is enabled, the method internally will establish TLS communication using the default
293 * ODL certificateManager SSLContext and attributes.
295 private void ovsdbManager(String ip, int port) {
297 if (certManagerSrv == null) {
298 LOG.error("Certificate Manager service is not available cannot establish the SSL communication.");
301 ovsdbManagerWithSsl(ip, port, certManagerSrv, certManagerSrv.getTlsProtocols(),
302 certManagerSrv.getCipherSuites());
304 ovsdbManagerWithSsl(ip, port, null /* SslContext */, null, null);
309 * OVSDB Passive listening thread that uses Netty ServerBootstrap to open
310 * passive connection with Ssl and handle channel callbacks.
312 private void ovsdbManagerWithSsl(String ip, 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(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);
371 // Shut down all event loops to terminate all threads.
372 bossGroup.shutdownGracefully();
373 workerGroup.shutdownGracefully();
377 private static void handleNewPassiveConnection(OvsdbClient client) {
378 ListenableFuture<List<String>> echoFuture = client.echo();
379 LOG.debug("Send echo message to probe the OVSDB switch {}",client.getConnectionInfo());
380 Futures.addCallback(echoFuture, new FutureCallback<List<String>>() {
382 public void onSuccess(@Nullable List<String> result) {
383 LOG.debug("Probe was successful to OVSDB switch {}",client.getConnectionInfo());
384 List<OvsdbClient> clientsFromSameNode = getPassiveClientsFromSameNode(client);
385 if (clientsFromSameNode.size() == 0) {
386 notifyListenerForPassiveConnection(client);
388 STALE_PASSIVE_CONNECTION_SERVICE.handleNewPassiveConnection(client, clientsFromSameNode);
393 public void onFailure(Throwable failureException) {
394 LOG.error("Probe failed to OVSDB switch. Disconnecting the channel {}", client.getConnectionInfo());
397 }, CONNECTION_NOTIFIER_SERVICE);
400 private static void handleNewPassiveConnection(final Channel channel) {
401 if (!channel.isOpen()) {
402 LOG.warn("Channel {} is not open, skipped further processing of the connection.",channel);
405 SslHandler sslHandler = (SslHandler) channel.pipeline().get("ssl");
406 if (sslHandler != null) {
407 class HandleNewPassiveSslRunner implements Runnable {
408 private int retryTimes = 3;
410 private void retry() {
411 if (retryTimes > 0) {
412 EXECUTOR_SERVICE.schedule(this, RETRY_PERIOD, TimeUnit.MILLISECONDS);
414 LOG.debug("channel closed {}", channel);
415 channel.disconnect();
422 HandshakeStatus status = sslHandler.engine().getHandshakeStatus();
423 LOG.debug("Handshake status {}", status);
426 case NOT_HANDSHAKING:
427 if (sslHandler.engine().getSession().getCipherSuite()
428 .equals("SSL_NULL_WITH_NULL_NULL")) {
429 // Not begin handshake yet. Retry later.
430 LOG.debug("handshake not begin yet {}", status);
433 //Check if peer is trusted before notifying listeners
435 sslHandler.engine().getSession().getPeerCertificates();
436 //Handshake done. Notify listener.
437 OvsdbClient client = getChannelClient(channel, ConnectionType.PASSIVE,
438 SocketConnectionType.SSL);
439 handleNewPassiveConnection(client);
440 } catch (SSLPeerUnverifiedException e) {
441 //Trust manager is still checking peer certificate. Retry later
442 LOG.debug("Peer certifiacte is not verified yet {}", status);
450 //Handshake still ongoing. Retry later.
451 LOG.debug("handshake not done yet {}", status);
456 if (sslHandler.engine().getSession().getCipherSuite()
457 .equals("SSL_NULL_WITH_NULL_NULL")) {
458 /* peer not authenticated. No need to notify listener in this case. */
459 LOG.error("Ssl handshake fail. channel {}", channel);
460 channel.disconnect();
463 * peer is authenticated. Give some time to wait for completion.
464 * If status is still NEED_WRAP, client might already disconnect.
465 * This happens when the first time client connects to controller in two-way handshake.
466 * After obtaining controller certificate, client will disconnect and start
467 * new connection with controller certificate it obtained.
468 * In this case no need to do anything for the first connection attempt. Just skip
469 * since client will reconnect later.
471 LOG.debug("handshake not done yet {}", status);
477 LOG.error("unknown hadshake status {}", status);
482 EXECUTOR_SERVICE.schedule(new HandleNewPassiveSslRunner(),
483 RETRY_PERIOD, TimeUnit.MILLISECONDS);
485 EXECUTOR_SERVICE.execute(() -> {
486 OvsdbClient client = getChannelClient(channel, ConnectionType.PASSIVE,
487 SocketConnectionType.NON_SSL);
488 handleNewPassiveConnection(client);
493 public static void channelClosed(final OvsdbClient client) {
494 LOG.info("Connection closed {}", client.getConnectionInfo().toString());
495 CONNECTIONS.remove(client);
496 if (client.isConnectionPublished()) {
497 for (OvsdbConnectionListener listener : CONNECTION_LISTENERS) {
498 listener.disconnected(client);
501 STALE_PASSIVE_CONNECTION_SERVICE.clientDisconnected(client);
505 public Collection<OvsdbClient> getConnections() {
506 return CONNECTIONS.keySet();
510 public void close() throws Exception {
511 LOG.info("OvsdbConnectionService closed");
512 JsonRpcEndpoint.close();
516 public OvsdbClient getClient(Channel channel) {
517 for (Entry<OvsdbClient, Channel> entry : CONNECTIONS.entrySet()) {
518 OvsdbClient client = entry.getKey();
519 Channel ctx = entry.getValue();
520 if (ctx.equals(channel)) {
527 private static List<OvsdbClient> getPassiveClientsFromSameNode(OvsdbClient ovsdbClient) {
528 List<OvsdbClient> passiveClients = new ArrayList<>();
529 for (OvsdbClient client : CONNECTIONS.keySet()) {
530 if (!client.equals(ovsdbClient)
531 && client.getConnectionInfo().getRemoteAddress()
532 .equals(ovsdbClient.getConnectionInfo().getRemoteAddress())
533 && client.getConnectionInfo().getType() == ConnectionType.PASSIVE) {
534 passiveClients.add(client);
537 return passiveClients;
540 public static void notifyListenerForPassiveConnection(final OvsdbClient client) {
541 client.setConnectionPublished(true);
542 for (final OvsdbConnectionListener listener : CONNECTION_LISTENERS) {
543 CONNECTION_NOTIFIER_SERVICE.execute(() -> {
544 LOG.trace("Connection {} notified to listener {}", client.getConnectionInfo(), listener);
545 listener.connected(client);
550 public void setOvsdbRpcTaskTimeout(int timeout) {
551 JsonRpcEndpoint.setReaperInterval(timeout);
557 * @param flag boolean for using ssl
559 public void setUseSsl(boolean flag) {
564 * Blueprint property setter method. Blueprint call this method and set the value of json rpc decoder
565 * max frame length to the value configured for config option (json-rpc-decoder-max-frame-length) in
566 * the configuration file. This option is only configured at the boot time of the controller. Any
567 * change at the run time will have no impact.
568 * @param maxFrameLength Max frame length (default : 100000)
570 public void setJsonRpcDecoderMaxFrameLength(int maxFrameLength) {
571 jsonRpcDecoderMaxFrameLength = maxFrameLength;
572 LOG.info("Json Rpc Decoder Max Frame Length set to : {}", jsonRpcDecoderMaxFrameLength);
575 public void setOvsdbListenerIp(String ip) {
576 LOG.info("OVSDB IP for listening connection is set to : {}", ip);
580 public void setOvsdbListenerPort(int portNumber) {
581 LOG.info("OVSDB port for listening connection is set to : {}", portNumber);
582 listenerPort = portNumber;
585 public void updateConfigParameter(Map<String, Object> configParameters) {
586 if (configParameters != null && !configParameters.isEmpty()) {
587 LOG.debug("Config parameters received : {}", configParameters.entrySet());
588 for (Map.Entry<String, Object> paramEntry : configParameters.entrySet()) {
589 if (paramEntry.getKey().equalsIgnoreCase(OVSDB_RPC_TASK_TIMEOUT_PARAM)) {
590 setOvsdbRpcTaskTimeout(Integer.parseInt((String)paramEntry.getValue()));
591 } else if (paramEntry.getKey().equalsIgnoreCase(USE_SSL)) {
592 useSSL = Boolean.parseBoolean(paramEntry.getValue().toString());