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 edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
19 import io.netty.bootstrap.Bootstrap;
20 import io.netty.bootstrap.ServerBootstrap;
21 import io.netty.channel.AdaptiveRecvByteBufAllocator;
22 import io.netty.channel.Channel;
23 import io.netty.channel.ChannelFuture;
24 import io.netty.channel.ChannelInitializer;
25 import io.netty.channel.ChannelOption;
26 import io.netty.channel.EventLoopGroup;
27 import io.netty.channel.nio.NioEventLoopGroup;
28 import io.netty.channel.socket.SocketChannel;
29 import io.netty.channel.socket.nio.NioServerSocketChannel;
30 import io.netty.channel.socket.nio.NioSocketChannel;
31 import io.netty.handler.codec.string.StringEncoder;
32 import io.netty.handler.logging.LogLevel;
33 import io.netty.handler.logging.LoggingHandler;
34 import io.netty.handler.ssl.SslHandler;
35 import io.netty.handler.timeout.IdleStateHandler;
36 import io.netty.handler.timeout.ReadTimeoutHandler;
37 import io.netty.util.CharsetUtil;
38 import java.net.InetAddress;
39 import java.util.ArrayList;
40 import java.util.Arrays;
41 import java.util.Collection;
42 import java.util.List;
44 import java.util.Map.Entry;
46 import java.util.concurrent.ConcurrentHashMap;
47 import java.util.concurrent.ExecutorService;
48 import java.util.concurrent.Executors;
49 import java.util.concurrent.ScheduledExecutorService;
50 import java.util.concurrent.TimeUnit;
51 import java.util.concurrent.atomic.AtomicBoolean;
52 import javax.annotation.Nullable;
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 @SuppressFBWarnings("ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD")
88 public class OvsdbConnectionService implements AutoCloseable, OvsdbConnection {
89 private static final Logger LOG = LoggerFactory.getLogger(OvsdbConnectionService.class);
90 private static final int IDLE_READER_TIMEOUT = 30;
91 private static final int READ_TIMEOUT = 180;
92 private static final String OVSDB_RPC_TASK_TIMEOUT_PARAM = "ovsdb-rpc-task-timeout";
93 private static final String USE_SSL = "use-ssl";
94 private static final int RETRY_PERIOD = 100; // retry after 100 milliseconds
96 private static final ScheduledExecutorService EXECUTOR_SERVICE = Executors.newScheduledThreadPool(10,
97 new ThreadFactoryBuilder().setNameFormat("OVSDBPassiveConnServ-%d").build());
99 private static final ExecutorService CONNECTION_NOTIFIER_SERVICE = Executors
100 .newCachedThreadPool(new ThreadFactoryBuilder().setNameFormat("OVSDBConnNotifSer-%d").build());
102 private static final StalePassiveConnectionService STALE_PASSIVE_CONNECTION_SERVICE =
103 new StalePassiveConnectionService(EXECUTOR_SERVICE);
105 private static final OvsdbConnection CONNECTION_SERVICE = new OvsdbConnectionService();
107 private static final Set<OvsdbConnectionListener> CONNECTION_LISTENERS = ConcurrentHashMap.newKeySet();
108 private static final Map<OvsdbClient, Channel> CONNECTIONS = new ConcurrentHashMap<>();
110 private static volatile boolean useSSL = false;
111 private static volatile ICertificateManager certManagerSrv;
113 private static volatile int jsonRpcDecoderMaxFrameLength = 100000;
114 private static volatile Channel serverChannel;
116 private final AtomicBoolean singletonCreated = new AtomicBoolean(false);
117 private volatile int listenerPort = 6640;
119 public static OvsdbConnection getService() {
120 return CONNECTION_SERVICE;
124 * If the SSL flag is enabled, the method internally will establish TLS communication using the default
125 * ODL certificateManager SSLContext and attributes.
128 public OvsdbClient connect(final InetAddress address, final int port) {
130 if (certManagerSrv == null) {
131 LOG.error("Certificate Manager service is not available cannot establish the SSL communication.");
134 return connectWithSsl(address, port, certManagerSrv.getServerContext());
136 return connectWithSsl(address, port, null /* SslContext */);
141 public OvsdbClient connectWithSsl(final InetAddress address, final int port,
142 final SSLContext sslContext) {
144 Bootstrap bootstrap = new Bootstrap();
145 bootstrap.group(new NioEventLoopGroup());
146 bootstrap.channel(NioSocketChannel.class);
147 bootstrap.option(ChannelOption.TCP_NODELAY, true);
148 bootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(65535, 65535, 65535));
150 bootstrap.handler(new ChannelInitializer<SocketChannel>() {
152 public void initChannel(SocketChannel channel) throws Exception {
153 if (sslContext != null) {
154 /* First add ssl handler if ssl context is given */
156 sslContext.createSSLEngine(address.toString(), port);
157 engine.setUseClientMode(true);
158 channel.pipeline().addLast("ssl", new SslHandler(engine));
160 channel.pipeline().addLast(
161 //new LoggingHandler(LogLevel.INFO),
162 new JsonRpcDecoder(jsonRpcDecoderMaxFrameLength),
163 new StringEncoder(CharsetUtil.UTF_8),
164 new IdleStateHandler(IDLE_READER_TIMEOUT, 0, 0),
165 new ReadTimeoutHandler(READ_TIMEOUT),
166 new ExceptionHandler());
170 ChannelFuture future = bootstrap.connect(address, port).sync();
171 Channel channel = future.channel();
172 return getChannelClient(channel, ConnectionType.ACTIVE, SocketConnectionType.SSL);
173 } catch (InterruptedException e) {
174 LOG.warn("Failed to connect {}:{}", address, port, e);
180 public void disconnect(OvsdbClient client) {
181 if (client == null) {
184 Channel channel = CONNECTIONS.get(client);
185 if (channel != null) {
186 //It's an explicit disconnect from user, so no need to notify back
187 //to user about the disconnect.
188 client.setConnectionPublished(false);
189 channel.disconnect();
191 CONNECTIONS.remove(client);
195 public void registerConnectionListener(OvsdbConnectionListener listener) {
196 LOG.info("registerConnectionListener: registering {}", listener.getClass().getSimpleName());
197 CONNECTION_LISTENERS.add(listener);
198 notifyAlreadyExistingConnectionsToListener(listener);
201 private void notifyAlreadyExistingConnectionsToListener(final OvsdbConnectionListener listener) {
202 for (final OvsdbClient client : getConnections()) {
203 CONNECTION_NOTIFIER_SERVICE.execute(() -> {
204 LOG.trace("Connection {} notified to listener {}", client.getConnectionInfo(), listener);
205 listener.connected(client);
211 public void unregisterConnectionListener(OvsdbConnectionListener listener) {
212 CONNECTION_LISTENERS.remove(listener);
215 private static OvsdbClient getChannelClient(Channel channel, ConnectionType type,
216 SocketConnectionType socketConnType) {
217 ObjectMapper objectMapper = new ObjectMapper();
218 objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
219 objectMapper.setSerializationInclusion(Include.NON_NULL);
221 JsonRpcEndpoint factory = new JsonRpcEndpoint(objectMapper, channel);
222 JsonRpcServiceBinderHandler binderHandler = new JsonRpcServiceBinderHandler(factory);
223 binderHandler.setContext(channel);
224 channel.pipeline().addLast(binderHandler);
226 OvsdbRPC rpc = factory.getClient(channel, OvsdbRPC.class);
227 OvsdbClientImpl client = new OvsdbClientImpl(rpc, channel, type, socketConnType);
228 client.setConnectionPublished(true);
229 CONNECTIONS.put(client, channel);
230 ChannelFuture closeFuture = channel.closeFuture();
231 closeFuture.addListener(new ChannelConnectionHandler(client));
236 * Method that initiates the Passive OVSDB channel listening functionality.
237 * By default the ovsdb passive connection will listen in port 6640 which can
238 * be overridden using the ovsdb.listenPort system property.
241 public synchronized boolean startOvsdbManager() {
242 final int ovsdbListenerPort = this.listenerPort;
243 if (!singletonCreated.getAndSet(true)) {
244 LOG.info("startOvsdbManager: Starting");
245 new Thread(() -> ovsdbManager(ovsdbListenerPort)).start();
253 * Method that initiates the Passive OVSDB channel listening functionality
254 * with ssl.By default the ovsdb passive connection will listen in port
255 * 6640 which can be overridden using the ovsdb.listenPort system property.
258 public synchronized boolean startOvsdbManagerWithSsl(final int ovsdbListenPort,
259 final SSLContext sslContext, String[] protocols, String[] cipherSuites) {
260 if (!singletonCreated.getAndSet(true)) {
261 new Thread(() -> ovsdbManagerWithSsl(ovsdbListenPort, sslContext, protocols, cipherSuites)).start();
269 public synchronized boolean restartOvsdbManagerWithSsl(final int ovsdbListenPort,
270 final SSLContext sslContext,
271 final String[] protocols,
272 final String[] cipherSuites) {
273 if (singletonCreated.getAndSet(false) && serverChannel != null) {
274 serverChannel.close();
275 LOG.info("Server channel closed");
277 serverChannel = null;
278 return startOvsdbManagerWithSsl(ovsdbListenPort, sslContext, protocols, cipherSuites);
282 * OVSDB Passive listening thread that uses Netty ServerBootstrap to open
283 * passive connection handle channel callbacks.
284 * If the SSL flag is enabled, the method internally will establish TLS communication using the default
285 * ODL certificateManager SSLContext and attributes.
287 private static void ovsdbManager(int port) {
289 if (certManagerSrv == null) {
290 LOG.error("Certificate Manager service is not available cannot establish the SSL communication.");
293 ovsdbManagerWithSsl(port, certManagerSrv.getServerContext(), certManagerSrv.getTlsProtocols(),
294 certManagerSrv.getCipherSuites());
296 ovsdbManagerWithSsl(port, null /* SslContext */, null, null);
301 * OVSDB Passive listening thread that uses Netty ServerBootstrap to open
302 * passive connection with Ssl and handle channel callbacks.
304 private static void ovsdbManagerWithSsl(int port, final SSLContext sslContext, final String[] protocols,
305 final String[] cipherSuites) {
306 EventLoopGroup bossGroup = new NioEventLoopGroup();
307 EventLoopGroup workerGroup = new NioEventLoopGroup();
309 ServerBootstrap serverBootstrap = new ServerBootstrap();
310 serverBootstrap.group(bossGroup, workerGroup)
311 .channel(NioServerSocketChannel.class)
312 .option(ChannelOption.SO_BACKLOG, 100)
313 .handler(new LoggingHandler(LogLevel.INFO))
314 .childHandler(new ChannelInitializer<SocketChannel>() {
316 public void initChannel(SocketChannel channel) throws Exception {
317 LOG.debug("New Passive channel created : {}", channel);
318 if (sslContext != null) {
319 /* Add SSL handler first if SSL context is provided */
320 SSLEngine engine = sslContext.createSSLEngine();
321 engine.setUseClientMode(false); // work in a server mode
322 engine.setNeedClientAuth(true); // need client authentication
323 if (protocols != null && protocols.length > 0) {
324 //Set supported protocols
325 engine.setEnabledProtocols(protocols);
326 LOG.debug("Supported ssl protocols {}",
327 Arrays.toString(engine.getSupportedProtocols()));
328 LOG.debug("Enabled ssl protocols {}",
329 Arrays.toString(engine.getEnabledProtocols()));
331 if (cipherSuites != null && cipherSuites.length > 0) {
332 //Set supported cipher suites
333 engine.setEnabledCipherSuites(cipherSuites);
334 LOG.debug("Enabled cipher suites {}",
335 Arrays.toString(engine.getEnabledCipherSuites()));
337 channel.pipeline().addLast("ssl", new SslHandler(engine));
340 channel.pipeline().addLast(
341 new JsonRpcDecoder(jsonRpcDecoderMaxFrameLength),
342 new StringEncoder(CharsetUtil.UTF_8),
343 new IdleStateHandler(IDLE_READER_TIMEOUT, 0, 0),
344 new ReadTimeoutHandler(READ_TIMEOUT),
345 new ExceptionHandler());
347 handleNewPassiveConnection(channel);
350 serverBootstrap.option(ChannelOption.TCP_NODELAY, true);
351 serverBootstrap.option(ChannelOption.RCVBUF_ALLOCATOR,
352 new AdaptiveRecvByteBufAllocator(65535, 65535, 65535));
354 ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
355 Channel serverListenChannel = channelFuture.channel();
356 serverChannel = serverListenChannel;
357 // Wait until the server socket is closed.
358 serverListenChannel.closeFuture().sync();
359 } catch (InterruptedException e) {
360 LOG.error("Thread interrupted", e);
362 // Shut down all event loops to terminate all threads.
363 bossGroup.shutdownGracefully();
364 workerGroup.shutdownGracefully();
368 private static void handleNewPassiveConnection(OvsdbClient client) {
369 ListenableFuture<List<String>> echoFuture = client.echo();
370 LOG.debug("Send echo message to probe the OVSDB switch {}",client.getConnectionInfo());
371 Futures.addCallback(echoFuture, new FutureCallback<List<String>>() {
373 public void onSuccess(@Nullable List<String> result) {
374 LOG.debug("Probe was successful to OVSDB switch {}",client.getConnectionInfo());
375 List<OvsdbClient> clientsFromSameNode = getPassiveClientsFromSameNode(client);
376 if (clientsFromSameNode.size() == 0) {
377 notifyListenerForPassiveConnection(client);
379 STALE_PASSIVE_CONNECTION_SERVICE.handleNewPassiveConnection(client, clientsFromSameNode);
384 public void onFailure(Throwable failureException) {
385 LOG.error("Probe failed to OVSDB switch. Disconnecting the channel {}", client.getConnectionInfo());
388 }, CONNECTION_NOTIFIER_SERVICE);
391 private static void handleNewPassiveConnection(final Channel channel) {
392 if (!channel.isOpen()) {
393 LOG.warn("Channel {} is not open, skipped further processing of the connection.",channel);
396 SslHandler sslHandler = (SslHandler) channel.pipeline().get("ssl");
397 if (sslHandler != null) {
398 class HandleNewPassiveSslRunner implements Runnable {
399 private int retryTimes = 3;
401 private void retry() {
402 if (retryTimes > 0) {
403 EXECUTOR_SERVICE.schedule(this, RETRY_PERIOD, TimeUnit.MILLISECONDS);
405 LOG.debug("channel closed {}", channel);
406 channel.disconnect();
413 HandshakeStatus status = sslHandler.engine().getHandshakeStatus();
414 LOG.debug("Handshake status {}", status);
417 case NOT_HANDSHAKING:
418 if (sslHandler.engine().getSession().getCipherSuite()
419 .equals("SSL_NULL_WITH_NULL_NULL")) {
420 // Not begin handshake yet. Retry later.
421 LOG.debug("handshake not begin yet {}", status);
424 //Check if peer is trusted before notifying listeners
426 sslHandler.engine().getSession().getPeerCertificates();
427 //Handshake done. Notify listener.
428 OvsdbClient client = getChannelClient(channel, ConnectionType.PASSIVE,
429 SocketConnectionType.SSL);
430 handleNewPassiveConnection(client);
431 } catch (SSLPeerUnverifiedException e) {
432 //Trust manager is still checking peer certificate. Retry later
433 LOG.debug("Peer certifiacte is not verified yet {}", status);
441 //Handshake still ongoing. Retry later.
442 LOG.debug("handshake not done yet {}", status);
447 if (sslHandler.engine().getSession().getCipherSuite()
448 .equals("SSL_NULL_WITH_NULL_NULL")) {
449 /* peer not authenticated. No need to notify listener in this case. */
450 LOG.error("Ssl handshake fail. channel {}", channel);
451 channel.disconnect();
454 * peer is authenticated. Give some time to wait for completion.
455 * If status is still NEED_WRAP, client might already disconnect.
456 * This happens when the first time client connects to controller in two-way handshake.
457 * After obtaining controller certificate, client will disconnect and start
458 * new connection with controller certificate it obtained.
459 * In this case no need to do anything for the first connection attempt. Just skip
460 * since client will reconnect later.
462 LOG.debug("handshake not done yet {}", status);
468 LOG.error("unknown hadshake status {}", status);
473 EXECUTOR_SERVICE.schedule(new HandleNewPassiveSslRunner(),
474 RETRY_PERIOD, TimeUnit.MILLISECONDS);
476 EXECUTOR_SERVICE.execute(() -> {
477 OvsdbClient client = getChannelClient(channel, ConnectionType.PASSIVE,
478 SocketConnectionType.NON_SSL);
479 handleNewPassiveConnection(client);
484 public static void channelClosed(final OvsdbClient client) {
485 LOG.info("Connection closed {}", client.getConnectionInfo().toString());
486 CONNECTIONS.remove(client);
487 if (client.isConnectionPublished()) {
488 for (OvsdbConnectionListener listener : CONNECTION_LISTENERS) {
489 listener.disconnected(client);
492 STALE_PASSIVE_CONNECTION_SERVICE.clientDisconnected(client);
496 public Collection<OvsdbClient> getConnections() {
497 return CONNECTIONS.keySet();
501 public void close() throws Exception {
502 LOG.info("OvsdbConnectionService closed");
503 JsonRpcEndpoint.close();
507 public OvsdbClient getClient(Channel channel) {
508 for (Entry<OvsdbClient, Channel> entry : CONNECTIONS.entrySet()) {
509 OvsdbClient client = entry.getKey();
510 Channel ctx = entry.getValue();
511 if (ctx.equals(channel)) {
518 private static List<OvsdbClient> getPassiveClientsFromSameNode(OvsdbClient ovsdbClient) {
519 List<OvsdbClient> passiveClients = new ArrayList<>();
520 for (OvsdbClient client : CONNECTIONS.keySet()) {
521 if (!client.equals(ovsdbClient)
522 && client.getConnectionInfo().getRemoteAddress()
523 .equals(ovsdbClient.getConnectionInfo().getRemoteAddress())
524 && client.getConnectionInfo().getType() == ConnectionType.PASSIVE) {
525 passiveClients.add(client);
528 return passiveClients;
531 public static void notifyListenerForPassiveConnection(final OvsdbClient client) {
532 client.setConnectionPublished(true);
533 for (final OvsdbConnectionListener listener : CONNECTION_LISTENERS) {
534 CONNECTION_NOTIFIER_SERVICE.execute(() -> {
535 LOG.trace("Connection {} notified to listener {}", client.getConnectionInfo(), listener);
536 listener.connected(client);
541 public void setOvsdbRpcTaskTimeout(int timeout) {
542 JsonRpcEndpoint.setReaperInterval(timeout);
548 * @param flag boolean for using ssl
550 public void setUseSsl(boolean flag) {
555 * Set default Certificate manager service.
557 * @param certificateManagerSrv reference
559 public void setCertificatManager(ICertificateManager certificateManagerSrv) {
560 certManagerSrv = certificateManagerSrv;
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 setOvsdbListenerPort(int portNumber) {
576 LOG.info("OVSDB port for listening connection is set to : {}", portNumber);
577 listenerPort = portNumber;
580 public void updateConfigParameter(Map<String, Object> configParameters) {
581 if (configParameters != null && !configParameters.isEmpty()) {
582 LOG.debug("Config parameters received : {}", configParameters.entrySet());
583 for (Map.Entry<String, Object> paramEntry : configParameters.entrySet()) {
584 if (paramEntry.getKey().equalsIgnoreCase(OVSDB_RPC_TASK_TIMEOUT_PARAM)) {
585 setOvsdbRpcTaskTimeout(Integer.parseInt((String)paramEntry.getValue()));
586 } else if (paramEntry.getKey().equalsIgnoreCase(USE_SSL)) {
587 useSSL = Boolean.parseBoolean(paramEntry.getValue().toString());