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 @SuppressWarnings("checkstyle:IllegalCatch")
144 public OvsdbClient connectWithSsl(final InetAddress address, final int port,
145 final ICertificateManager certificateManagerSrv) {
147 Bootstrap bootstrap = new Bootstrap();
148 bootstrap.group(new NioEventLoopGroup());
149 bootstrap.channel(NioSocketChannel.class);
150 bootstrap.option(ChannelOption.TCP_NODELAY, true);
151 bootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(65535, 65535, 65535));
153 bootstrap.handler(new ChannelInitializer<SocketChannel>() {
155 public void initChannel(SocketChannel channel) throws Exception {
156 if (certificateManagerSrv != null && certificateManagerSrv.getServerContext() != null) {
157 SSLContext sslContext = certificateManagerSrv.getServerContext();
158 /* First add ssl handler if ssl context is given */
160 sslContext.createSSLEngine(address.toString(), port);
161 engine.setUseClientMode(true);
162 channel.pipeline().addLast("ssl", new SslHandler(engine));
164 channel.pipeline().addLast(
165 //new LoggingHandler(LogLevel.INFO),
166 new JsonRpcDecoder(jsonRpcDecoderMaxFrameLength),
167 new StringEncoder(CharsetUtil.UTF_8),
168 new IdleStateHandler(IDLE_READER_TIMEOUT, 0, 0),
169 new ReadTimeoutHandler(READ_TIMEOUT),
170 new ExceptionHandler(OvsdbConnectionService.this));
174 ChannelFuture future = bootstrap.connect(address, port).sync();
175 Channel channel = future.channel();
176 return getChannelClient(channel, ConnectionType.ACTIVE, SocketConnectionType.SSL);
177 } catch (InterruptedException e) {
178 LOG.warn("Failed to connect {}:{}", address, port, e);
179 } catch (Throwable throwable) {
180 // sync() re-throws exceptions declared as Throwable, so the compiler doesn't see them
181 LOG.error("Error while binding to address {}, port {}", address, port, throwable);
188 public void disconnect(OvsdbClient client) {
189 if (client == null) {
192 Channel channel = CONNECTIONS.get(client);
193 if (channel != null) {
194 //It's an explicit disconnect from user, so no need to notify back
195 //to user about the disconnect.
196 client.setConnectionPublished(false);
197 channel.disconnect();
199 CONNECTIONS.remove(client);
203 public void registerConnectionListener(OvsdbConnectionListener listener) {
204 LOG.info("registerConnectionListener: registering {}", listener.getClass().getSimpleName());
205 CONNECTION_LISTENERS.add(listener);
206 notifyAlreadyExistingConnectionsToListener(listener);
209 private void notifyAlreadyExistingConnectionsToListener(final OvsdbConnectionListener listener) {
210 for (final OvsdbClient client : getConnections()) {
211 CONNECTION_NOTIFIER_SERVICE.execute(() -> {
212 LOG.trace("Connection {} notified to listener {}", client.getConnectionInfo(), listener);
213 listener.connected(client);
219 public void unregisterConnectionListener(OvsdbConnectionListener listener) {
220 CONNECTION_LISTENERS.remove(listener);
223 private static OvsdbClient getChannelClient(Channel channel, ConnectionType type,
224 SocketConnectionType socketConnType) {
225 ObjectMapper objectMapper = new ObjectMapper();
226 objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
227 objectMapper.setSerializationInclusion(Include.NON_NULL);
229 JsonRpcEndpoint factory = new JsonRpcEndpoint(objectMapper, channel);
230 JsonRpcServiceBinderHandler binderHandler = new JsonRpcServiceBinderHandler(factory);
231 binderHandler.setContext(channel);
232 channel.pipeline().addLast(binderHandler);
234 OvsdbRPC rpc = factory.getClient(channel, OvsdbRPC.class);
235 OvsdbClientImpl client = new OvsdbClientImpl(rpc, channel, type, socketConnType);
236 client.setConnectionPublished(true);
237 CONNECTIONS.put(client, channel);
238 ChannelFuture closeFuture = channel.closeFuture();
239 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 String[] protocols, 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(String ip, 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(String ip, 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(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(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 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(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().toString());
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(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(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(int timeout) {
561 JsonRpcEndpoint.setReaperInterval(timeout);
567 * @param flag boolean for using ssl
569 public void setUseSsl(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(int maxFrameLength) {
581 jsonRpcDecoderMaxFrameLength = maxFrameLength;
582 LOG.info("Json Rpc Decoder Max Frame Length set to : {}", jsonRpcDecoderMaxFrameLength);
585 public void setOvsdbListenerIp(String ip) {
586 LOG.info("OVSDB IP for listening connection is set to : {}", ip);
590 public void setOvsdbListenerPort(int portNumber) {
591 LOG.info("OVSDB port for listening connection is set to : {}", portNumber);
592 listenerPort = portNumber;
595 public void updateConfigParameter(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());