Do not use Foo.toString() when logging
[ovsdb.git] / library / impl / src / main / java / org / opendaylight / ovsdb / lib / impl / OvsdbConnectionService.java
1 /*
2  * Copyright © 2014, 2017 Red Hat, Inc. and others. All rights reserved.
3  *
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
7  */
8 package org.opendaylight.ovsdb.lib.impl;
9
10 import com.fasterxml.jackson.annotation.JsonInclude.Include;
11 import com.fasterxml.jackson.databind.DeserializationFeature;
12 import com.fasterxml.jackson.databind.ObjectMapper;
13 import com.google.common.util.concurrent.FutureCallback;
14 import com.google.common.util.concurrent.Futures;
15 import com.google.common.util.concurrent.ListenableFuture;
16 import com.google.common.util.concurrent.ThreadFactoryBuilder;
17 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
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;
42 import java.util.Map;
43 import java.util.Map.Entry;
44 import java.util.Set;
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.inject.Inject;
52 import javax.inject.Singleton;
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.apache.aries.blueprint.annotation.service.Reference;
58 import org.apache.aries.blueprint.annotation.service.Service;
59 import org.eclipse.jdt.annotation.Nullable;
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.opendaylight.ovsdb.lib.jsonrpc.JsonRpcServiceBinderHandler;
70 import org.opendaylight.ovsdb.lib.message.OvsdbRPC;
71 import org.slf4j.Logger;
72 import org.slf4j.LoggerFactory;
73
74 /**
75  * OvsDBConnectionService provides OVSDB connection management functionality which includes
76  * both Active and Passive connections.
77  * From the Library perspective, Active OVSDB connections are those that are initiated from
78  * the Controller towards the ovsdb-manager.
79  * While Passive OVSDB connections are those that are initiated from the ovs towards
80  * the controller.
81  *
82  * <p>Applications that use OvsDBConnectionService can use the OvsDBConnection class' connect APIs
83  * to initiate Active connections and can listen to the asynchronous Passive connections via
84  * registerConnectionListener listener API.
85  *
86  * <p>The library is designed as Java modular component that can work in both OSGi and non-OSGi
87  * environment. Hence a single instance of the service will be active (via Service Registry in OSGi)
88  * and a Singleton object in a non-OSGi environment.
89  */
90 @Singleton
91 @Service(classes = OvsdbConnection.class)
92 public class OvsdbConnectionService implements AutoCloseable, OvsdbConnection {
93     private static final Logger LOG = LoggerFactory.getLogger(OvsdbConnectionService.class);
94     private static final int IDLE_READER_TIMEOUT = 30;
95     private static final int READ_TIMEOUT = 180;
96     private static final String OVSDB_RPC_TASK_TIMEOUT_PARAM = "ovsdb-rpc-task-timeout";
97     private static final String USE_SSL = "use-ssl";
98     private static final int RETRY_PERIOD = 100; // retry after 100 milliseconds
99
100     private static final ScheduledExecutorService EXECUTOR_SERVICE = Executors.newScheduledThreadPool(10,
101             new ThreadFactoryBuilder().setNameFormat("OVSDBPassiveConnServ-%d").build());
102
103     private static final ExecutorService CONNECTION_NOTIFIER_SERVICE = Executors
104             .newCachedThreadPool(new ThreadFactoryBuilder().setNameFormat("OVSDBConnNotifSer-%d").build());
105
106     private static final StalePassiveConnectionService STALE_PASSIVE_CONNECTION_SERVICE =
107             new StalePassiveConnectionService((client) -> {
108                 notifyListenerForPassiveConnection(client);
109                 return null;
110             });
111
112     private static final Set<OvsdbConnectionListener> CONNECTION_LISTENERS = ConcurrentHashMap.newKeySet();
113     private static final Map<OvsdbClient, Channel> CONNECTIONS = new ConcurrentHashMap<>();
114
115     private volatile boolean useSSL = false;
116     private final ICertificateManager certManagerSrv;
117
118     private volatile int jsonRpcDecoderMaxFrameLength = 100000;
119     private volatile Channel serverChannel;
120
121     private final AtomicBoolean singletonCreated = new AtomicBoolean(false);
122     private volatile String listenerIp = "0.0.0.0";
123     private volatile int listenerPort = 6640;
124
125     @Inject
126     public OvsdbConnectionService(@Reference(filter = "type=default-certificate-manager")
127                                               ICertificateManager certManagerSrv) {
128         this.certManagerSrv = certManagerSrv;
129     }
130
131     /**
132      * If the SSL flag is enabled, the method internally will establish TLS communication using the default
133      * ODL certificateManager SSLContext and attributes.
134      */
135     @Override
136     public OvsdbClient connect(final InetAddress address, final int port) {
137         if (useSSL) {
138             if (certManagerSrv == null) {
139                 LOG.error("Certificate Manager service is not available cannot establish the SSL communication.");
140                 return null;
141             }
142             return connectWithSsl(address, port, certManagerSrv);
143         } else {
144             return connectWithSsl(address, port, null /* SslContext */);
145         }
146     }
147
148     @Override
149     @SuppressWarnings("checkstyle:IllegalCatch")
150     public OvsdbClient connectWithSsl(final InetAddress address, final int port,
151                                final ICertificateManager certificateManagerSrv) {
152         try {
153             Bootstrap bootstrap = new Bootstrap();
154             bootstrap.group(new NioEventLoopGroup());
155             bootstrap.channel(NioSocketChannel.class);
156             bootstrap.option(ChannelOption.TCP_NODELAY, true);
157             bootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(65535, 65535, 65535));
158
159             bootstrap.handler(new ChannelInitializer<SocketChannel>() {
160                 @Override
161                 public void initChannel(SocketChannel channel) throws Exception {
162                     if (certificateManagerSrv != null && certificateManagerSrv.getServerContext() != null) {
163                         SSLContext sslContext = certificateManagerSrv.getServerContext();
164                         /* First add ssl handler if ssl context is given */
165                         SSLEngine engine =
166                             sslContext.createSSLEngine(address.toString(), port);
167                         engine.setUseClientMode(true);
168                         channel.pipeline().addLast("ssl", new SslHandler(engine));
169                     }
170                     channel.pipeline().addLast(
171                             //new LoggingHandler(LogLevel.INFO),
172                             new JsonRpcDecoder(jsonRpcDecoderMaxFrameLength),
173                             new StringEncoder(CharsetUtil.UTF_8),
174                             new IdleStateHandler(IDLE_READER_TIMEOUT, 0, 0),
175                             new ReadTimeoutHandler(READ_TIMEOUT),
176                             new ExceptionHandler(OvsdbConnectionService.this));
177                 }
178             });
179
180             ChannelFuture future = bootstrap.connect(address, port).sync();
181             Channel channel = future.channel();
182             return getChannelClient(channel, ConnectionType.ACTIVE, SocketConnectionType.SSL);
183         } catch (InterruptedException e) {
184             LOG.warn("Failed to connect {}:{}", address, port, e);
185         } catch (Throwable throwable) {
186             // sync() re-throws exceptions declared as Throwable, so the compiler doesn't see them
187             LOG.error("Error while binding to address {}, port {}", address, port, throwable);
188             throw throwable;
189         }
190         return null;
191     }
192
193     @Override
194     public void disconnect(OvsdbClient client) {
195         if (client == null) {
196             return;
197         }
198         Channel channel = CONNECTIONS.get(client);
199         if (channel != null) {
200             //It's an explicit disconnect from user, so no need to notify back
201             //to user about the disconnect.
202             client.setConnectionPublished(false);
203             channel.disconnect();
204         }
205         CONNECTIONS.remove(client);
206     }
207
208     @Override
209     public void registerConnectionListener(OvsdbConnectionListener listener) {
210         LOG.info("registerConnectionListener: registering {}", listener.getClass().getSimpleName());
211         CONNECTION_LISTENERS.add(listener);
212         notifyAlreadyExistingConnectionsToListener(listener);
213     }
214
215     private void notifyAlreadyExistingConnectionsToListener(final OvsdbConnectionListener listener) {
216         for (final OvsdbClient client : getConnections()) {
217             CONNECTION_NOTIFIER_SERVICE.execute(() -> {
218                 LOG.trace("Connection {} notified to listener {}", client.getConnectionInfo(), listener);
219                 listener.connected(client);
220             });
221         }
222     }
223
224     @Override
225     public void unregisterConnectionListener(OvsdbConnectionListener listener) {
226         CONNECTION_LISTENERS.remove(listener);
227     }
228
229     private static OvsdbClient getChannelClient(Channel channel, ConnectionType type,
230         SocketConnectionType socketConnType) {
231         ObjectMapper objectMapper = new ObjectMapper();
232         objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
233         objectMapper.setSerializationInclusion(Include.NON_NULL);
234
235         JsonRpcEndpoint factory = new JsonRpcEndpoint(objectMapper, channel);
236         JsonRpcServiceBinderHandler binderHandler = new JsonRpcServiceBinderHandler(factory);
237         binderHandler.setContext(channel);
238         channel.pipeline().addLast(binderHandler);
239
240         OvsdbRPC rpc = factory.getClient(channel, OvsdbRPC.class);
241         OvsdbClientImpl client = new OvsdbClientImpl(rpc, channel, type, socketConnType);
242         client.setConnectionPublished(true);
243         CONNECTIONS.put(client, channel);
244         ChannelFuture closeFuture = channel.closeFuture();
245         closeFuture.addListener(new ChannelConnectionHandler(client));
246         return client;
247     }
248
249     /**
250      * Method that initiates the Passive OVSDB channel listening functionality.
251      * By default the ovsdb passive connection will listen in port 6640 which can
252      * be overridden using the ovsdb.listenPort system property.
253      */
254     @Override
255     public synchronized boolean startOvsdbManager() {
256         final int ovsdbListenerPort = this.listenerPort;
257         final String ovsdbListenerIp = this.listenerIp;
258         if (!singletonCreated.getAndSet(true)) {
259             LOG.info("startOvsdbManager: Starting");
260             new Thread(() -> ovsdbManager(ovsdbListenerIp, ovsdbListenerPort)).start();
261             return true;
262         } else {
263             return false;
264         }
265     }
266
267     /**
268      * Method that initiates the Passive OVSDB channel listening functionality
269      * with ssl.By default the ovsdb passive connection will listen in port
270      * 6640 which can be overridden using the ovsdb.listenPort system property.
271      */
272     @Override
273     public synchronized boolean startOvsdbManagerWithSsl(final String ovsdbListenIp, final int ovsdbListenPort,
274                                                          final ICertificateManager certificateManagerSrv,
275                                                          String[] protocols, String[] cipherSuites) {
276         if (!singletonCreated.getAndSet(true)) {
277             new Thread(() -> ovsdbManagerWithSsl(ovsdbListenIp, ovsdbListenPort,
278                     certificateManagerSrv, protocols, cipherSuites)).start();
279             return true;
280         } else {
281             return false;
282         }
283     }
284
285     @Override
286     public synchronized boolean restartOvsdbManagerWithSsl(final String ovsdbListenIp,
287         final int ovsdbListenPort,
288         final ICertificateManager certificateManagerSrv,
289         final String[] protocols,
290         final String[] cipherSuites) {
291         if (singletonCreated.getAndSet(false) && serverChannel != null) {
292             serverChannel.close();
293             LOG.info("Server channel closed");
294         }
295         serverChannel = null;
296         return startOvsdbManagerWithSsl(ovsdbListenIp, ovsdbListenPort,
297             certificateManagerSrv, protocols, cipherSuites);
298     }
299
300     /**
301      * OVSDB Passive listening thread that uses Netty ServerBootstrap to open
302      * passive connection handle channel callbacks.
303      * If the SSL flag is enabled, the method internally will establish TLS communication using the default
304      * ODL certificateManager SSLContext and attributes.
305      */
306     private void ovsdbManager(String ip, int port) {
307         if (useSSL) {
308             if (certManagerSrv == null) {
309                 LOG.error("Certificate Manager service is not available cannot establish the SSL communication.");
310                 return;
311             }
312             ovsdbManagerWithSsl(ip, port, certManagerSrv, certManagerSrv.getTlsProtocols(),
313                     certManagerSrv.getCipherSuites());
314         } else {
315             ovsdbManagerWithSsl(ip, port, null /* SslContext */, null, null);
316         }
317     }
318
319     /**
320      * OVSDB Passive listening thread that uses Netty ServerBootstrap to open
321      * passive connection with Ssl and handle channel callbacks.
322      */
323     @SuppressWarnings("checkstyle:IllegalCatch")
324     private void ovsdbManagerWithSsl(String ip, int port, final ICertificateManager certificateManagerSrv,
325                                             final String[] protocols, final String[] cipherSuites) {
326         EventLoopGroup bossGroup = new NioEventLoopGroup();
327         EventLoopGroup workerGroup = new NioEventLoopGroup();
328         try {
329             ServerBootstrap serverBootstrap = new ServerBootstrap();
330             serverBootstrap.group(bossGroup, workerGroup)
331                     .channel(NioServerSocketChannel.class)
332                     .option(ChannelOption.SO_BACKLOG, 100)
333                     .handler(new LoggingHandler(LogLevel.INFO))
334                     .childHandler(new ChannelInitializer<SocketChannel>() {
335                         @Override
336                         public void initChannel(SocketChannel channel) throws Exception {
337                             LOG.debug("New Passive channel created : {}", channel);
338                             if (certificateManagerSrv != null && certificateManagerSrv.getServerContext() != null) {
339                                 /* Add SSL handler first if SSL context is provided */
340                                 SSLContext sslContext = certificateManagerSrv.getServerContext();
341                                 SSLEngine engine = sslContext.createSSLEngine();
342                                 engine.setUseClientMode(false); // work in a server mode
343                                 engine.setNeedClientAuth(true); // need client authentication
344                                 if (protocols != null && protocols.length > 0) {
345                                     //Set supported protocols
346                                     engine.setEnabledProtocols(protocols);
347                                     LOG.debug("Supported ssl protocols {}",
348                                             Arrays.toString(engine.getSupportedProtocols()));
349                                     LOG.debug("Enabled ssl protocols {}",
350                                             Arrays.toString(engine.getEnabledProtocols()));
351                                 }
352                                 if (cipherSuites != null && cipherSuites.length > 0) {
353                                     //Set supported cipher suites
354                                     engine.setEnabledCipherSuites(cipherSuites);
355                                     LOG.debug("Enabled cipher suites {}",
356                                             Arrays.toString(engine.getEnabledCipherSuites()));
357                                 }
358                                 channel.pipeline().addLast("ssl", new SslHandler(engine));
359                             }
360
361                             channel.pipeline().addLast(
362                                  new JsonRpcDecoder(jsonRpcDecoderMaxFrameLength),
363                                  new StringEncoder(CharsetUtil.UTF_8),
364                                  new IdleStateHandler(IDLE_READER_TIMEOUT, 0, 0),
365                                  new ReadTimeoutHandler(READ_TIMEOUT),
366                                  new ExceptionHandler(OvsdbConnectionService.this));
367
368                             handleNewPassiveConnection(channel);
369                         }
370                     });
371             serverBootstrap.option(ChannelOption.TCP_NODELAY, true);
372             serverBootstrap.option(ChannelOption.RCVBUF_ALLOCATOR,
373                     new AdaptiveRecvByteBufAllocator(65535, 65535, 65535));
374             // Start the server.
375             ChannelFuture channelFuture = serverBootstrap.bind(ip, port).sync();
376             Channel serverListenChannel = channelFuture.channel();
377             serverChannel = serverListenChannel;
378             // Wait until the server socket is closed.
379             serverListenChannel.closeFuture().sync();
380         } catch (InterruptedException e) {
381             LOG.error("Thread interrupted", e);
382         } catch (Throwable throwable) {
383             // sync() re-throws exceptions declared as Throwable, so the compiler doesn't see them
384             LOG.error("Error while binding to address {}, port {}", ip, port, throwable);
385             throw throwable;
386         } finally {
387             // Shut down all event loops to terminate all threads.
388             bossGroup.shutdownGracefully();
389             workerGroup.shutdownGracefully();
390         }
391     }
392
393     private static void handleNewPassiveConnection(OvsdbClient client) {
394         ListenableFuture<List<String>> echoFuture = client.echo();
395         LOG.debug("Send echo message to probe the OVSDB switch {}",client.getConnectionInfo());
396         Futures.addCallback(echoFuture, new FutureCallback<List<String>>() {
397             @Override
398             public void onSuccess(@Nullable List<String> result) {
399                 LOG.debug("Probe was successful to OVSDB switch {}",client.getConnectionInfo());
400                 List<OvsdbClient> clientsFromSameNode = getPassiveClientsFromSameNode(client);
401                 if (clientsFromSameNode.size() == 0) {
402                     notifyListenerForPassiveConnection(client);
403                 } else {
404                     STALE_PASSIVE_CONNECTION_SERVICE.handleNewPassiveConnection(client, clientsFromSameNode);
405                 }
406             }
407
408             @Override
409             public void onFailure(Throwable failureException) {
410                 LOG.error("Probe failed to OVSDB switch. Disconnecting the channel {}", client.getConnectionInfo());
411                 client.disconnect();
412             }
413         }, CONNECTION_NOTIFIER_SERVICE);
414     }
415
416     @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
417             justification = "https://github.com/spotbugs/spotbugs/issues/811")
418     private static void handleNewPassiveConnection(final Channel channel) {
419         if (!channel.isOpen()) {
420             LOG.warn("Channel {} is not open, skipped further processing of the connection.",channel);
421             return;
422         }
423         SslHandler sslHandler = (SslHandler) channel.pipeline().get("ssl");
424         if (sslHandler != null) {
425             class HandleNewPassiveSslRunner implements Runnable {
426                 private int retryTimes = 3;
427
428                 private void retry() {
429                     if (retryTimes > 0) {
430                         EXECUTOR_SERVICE.schedule(this,  RETRY_PERIOD, TimeUnit.MILLISECONDS);
431                     } else {
432                         LOG.debug("channel closed {}", channel);
433                         channel.disconnect();
434                     }
435                     retryTimes--;
436                 }
437
438                 @Override
439                 public void run() {
440                     HandshakeStatus status = sslHandler.engine().getHandshakeStatus();
441                     LOG.debug("Handshake status {}", status);
442                     switch (status) {
443                         case FINISHED:
444                         case NOT_HANDSHAKING:
445                             if (sslHandler.engine().getSession().getCipherSuite()
446                                     .equals("SSL_NULL_WITH_NULL_NULL")) {
447                                 // Not begin handshake yet. Retry later.
448                                 LOG.debug("handshake not begin yet {}", status);
449                                 retry();
450                             } else {
451                               //Check if peer is trusted before notifying listeners
452                                 try {
453                                     sslHandler.engine().getSession().getPeerCertificates();
454                                     //Handshake done. Notify listener.
455                                     OvsdbClient client = getChannelClient(channel, ConnectionType.PASSIVE,
456                                         SocketConnectionType.SSL);
457                                     handleNewPassiveConnection(client);
458                                 } catch (SSLPeerUnverifiedException e) {
459                                     //Trust manager is still checking peer certificate. Retry later
460                                     LOG.debug("Peer certifiacte is not verified yet {}", status);
461                                     retry();
462                                 }
463                             }
464                             break;
465
466                         case NEED_UNWRAP:
467                         case NEED_TASK:
468                             //Handshake still ongoing. Retry later.
469                             LOG.debug("handshake not done yet {}", status);
470                             retry();
471                             break;
472
473                         case NEED_WRAP:
474                             if (sslHandler.engine().getSession().getCipherSuite()
475                                     .equals("SSL_NULL_WITH_NULL_NULL")) {
476                                 /* peer not authenticated. No need to notify listener in this case. */
477                                 LOG.error("Ssl handshake fail. channel {}", channel);
478                                 channel.disconnect();
479                             } else {
480                                 /*
481                                  * peer is authenticated. Give some time to wait for completion.
482                                  * If status is still NEED_WRAP, client might already disconnect.
483                                  * This happens when the first time client connects to controller in two-way handshake.
484                                  * After obtaining controller certificate, client will disconnect and start
485                                  * new connection with controller certificate it obtained.
486                                  * In this case no need to do anything for the first connection attempt. Just skip
487                                  * since client will reconnect later.
488                                  */
489                                 LOG.debug("handshake not done yet {}", status);
490                                 retry();
491                             }
492                             break;
493
494                         default:
495                             LOG.error("unknown hadshake status {}", status);
496                     }
497                 }
498             }
499
500             EXECUTOR_SERVICE.schedule(new HandleNewPassiveSslRunner(),
501                     RETRY_PERIOD, TimeUnit.MILLISECONDS);
502         } else {
503             EXECUTOR_SERVICE.execute(() -> {
504                 OvsdbClient client = getChannelClient(channel, ConnectionType.PASSIVE,
505                     SocketConnectionType.NON_SSL);
506                 handleNewPassiveConnection(client);
507             });
508         }
509     }
510
511     public static void channelClosed(final OvsdbClient client) {
512         LOG.info("Connection closed {}", client.getConnectionInfo());
513         CONNECTIONS.remove(client);
514         if (client.isConnectionPublished()) {
515             for (OvsdbConnectionListener listener : CONNECTION_LISTENERS) {
516                 listener.disconnected(client);
517             }
518         }
519         STALE_PASSIVE_CONNECTION_SERVICE.clientDisconnected(client);
520     }
521
522     @Override
523     public Collection<OvsdbClient> getConnections() {
524         return CONNECTIONS.keySet();
525     }
526
527     @Override
528     public void close() throws Exception {
529         LOG.info("OvsdbConnectionService closed");
530         JsonRpcEndpoint.close();
531     }
532
533     @Override
534     public OvsdbClient getClient(Channel channel) {
535         for (Entry<OvsdbClient, Channel> entry : CONNECTIONS.entrySet()) {
536             OvsdbClient client = entry.getKey();
537             Channel ctx = entry.getValue();
538             if (ctx.equals(channel)) {
539                 return client;
540             }
541         }
542         return null;
543     }
544
545     @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
546             justification = "https://github.com/spotbugs/spotbugs/issues/811")
547     private static List<OvsdbClient> getPassiveClientsFromSameNode(OvsdbClient ovsdbClient) {
548         List<OvsdbClient> passiveClients = new ArrayList<>();
549         for (OvsdbClient client : CONNECTIONS.keySet()) {
550             if (!client.equals(ovsdbClient)
551                     && client.getConnectionInfo().getRemoteAddress()
552                             .equals(ovsdbClient.getConnectionInfo().getRemoteAddress())
553                     && client.getConnectionInfo().getType() == ConnectionType.PASSIVE) {
554                 passiveClients.add(client);
555             }
556         }
557         return passiveClients;
558     }
559
560     public static void notifyListenerForPassiveConnection(final OvsdbClient client) {
561         client.setConnectionPublished(true);
562         for (final OvsdbConnectionListener listener : CONNECTION_LISTENERS) {
563             CONNECTION_NOTIFIER_SERVICE.execute(() -> {
564                 LOG.trace("Connection {} notified to listener {}", client.getConnectionInfo(), listener);
565                 listener.connected(client);
566             });
567         }
568     }
569
570     public void setOvsdbRpcTaskTimeout(int timeout) {
571         JsonRpcEndpoint.setReaperInterval(timeout);
572     }
573
574     /**
575      * Set useSSL flag.
576      *
577      * @param flag boolean for using ssl
578      */
579     public void setUseSsl(boolean flag) {
580         useSSL = flag;
581     }
582
583     /**
584      * Blueprint property setter method. Blueprint call this method and set the value of json rpc decoder
585      * max frame length to the value configured for config option (json-rpc-decoder-max-frame-length) in
586      * the configuration file. This option is only configured at the  boot time of the controller. Any
587      * change at the run time will have no impact.
588      * @param maxFrameLength Max frame length (default : 100000)
589      */
590     public void setJsonRpcDecoderMaxFrameLength(int maxFrameLength) {
591         jsonRpcDecoderMaxFrameLength = maxFrameLength;
592         LOG.info("Json Rpc Decoder Max Frame Length set to : {}", jsonRpcDecoderMaxFrameLength);
593     }
594
595     public void setOvsdbListenerIp(String ip) {
596         LOG.info("OVSDB IP for listening connection is set to : {}", ip);
597         listenerIp = ip;
598     }
599
600     public void setOvsdbListenerPort(int portNumber) {
601         LOG.info("OVSDB port for listening connection is set to : {}", portNumber);
602         listenerPort = portNumber;
603     }
604
605     public void updateConfigParameter(Map<String, Object> configParameters) {
606         if (configParameters != null && !configParameters.isEmpty()) {
607             LOG.debug("Config parameters received : {}", configParameters.entrySet());
608             for (Map.Entry<String, Object> paramEntry : configParameters.entrySet()) {
609                 if (paramEntry.getKey().equalsIgnoreCase(OVSDB_RPC_TASK_TIMEOUT_PARAM)) {
610                     setOvsdbRpcTaskTimeout(Integer.parseInt((String)paramEntry.getValue()));
611                 } else if (paramEntry.getKey().equalsIgnoreCase(USE_SSL)) {
612                     useSSL = Boolean.parseBoolean(paramEntry.getValue().toString());
613                 }
614             }
615         }
616     }
617 }