da3f7c30b1fcc89b5db84a1bf4148de6c792ea9c
[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
9 package org.opendaylight.ovsdb.lib.impl;
10
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;
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.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;
70
71 /**
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
77  * the controller.
78  *
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.
82  *
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.
86  */
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
94
95     private static final ScheduledExecutorService EXECUTOR_SERVICE = Executors.newScheduledThreadPool(10,
96             new ThreadFactoryBuilder().setNameFormat("OVSDBPassiveConnServ-%d").build());
97
98     private static final ExecutorService CONNECTION_NOTIFIER_SERVICE = Executors
99             .newCachedThreadPool(new ThreadFactoryBuilder().setNameFormat("OVSDBConnNotifSer-%d").build());
100
101     private static final StalePassiveConnectionService STALE_PASSIVE_CONNECTION_SERVICE =
102             new StalePassiveConnectionService((client) -> {
103                 notifyListenerForPassiveConnection(client);
104                 return null;
105             });
106
107     private static final Set<OvsdbConnectionListener> CONNECTION_LISTENERS = ConcurrentHashMap.newKeySet();
108     private static final Map<OvsdbClient, Channel> CONNECTIONS = new ConcurrentHashMap<>();
109
110     private volatile boolean useSSL = false;
111     private final ICertificateManager certManagerSrv;
112
113     private volatile int jsonRpcDecoderMaxFrameLength = 100000;
114     private volatile Channel serverChannel;
115
116     private final AtomicBoolean singletonCreated = new AtomicBoolean(false);
117     private volatile String listenerIp = "0.0.0.0";
118     private volatile int listenerPort = 6640;
119
120     @Inject
121     public OvsdbConnectionService(ICertificateManager certManagerSrv) {
122         this.certManagerSrv = certManagerSrv;
123     }
124
125     /**
126      * If the SSL flag is enabled, the method internally will establish TLS communication using the default
127      * ODL certificateManager SSLContext and attributes.
128      */
129     @Override
130     public OvsdbClient connect(final InetAddress address, final int port) {
131         if (useSSL) {
132             if (certManagerSrv == null) {
133                 LOG.error("Certificate Manager service is not available cannot establish the SSL communication.");
134                 return null;
135             }
136             return connectWithSsl(address, port, certManagerSrv);
137         } else {
138             return connectWithSsl(address, port, null /* SslContext */);
139         }
140     }
141
142     @Override
143     @SuppressWarnings("checkstyle:IllegalCatch")
144     public OvsdbClient connectWithSsl(final InetAddress address, final int port,
145                                final ICertificateManager certificateManagerSrv) {
146         try {
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));
152
153             bootstrap.handler(new ChannelInitializer<SocketChannel>() {
154                 @Override
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 */
159                         SSLEngine engine =
160                             sslContext.createSSLEngine(address.toString(), port);
161                         engine.setUseClientMode(true);
162                         channel.pipeline().addLast("ssl", new SslHandler(engine));
163                     }
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));
171                 }
172             });
173
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);
182             throw throwable;
183         }
184         return null;
185     }
186
187     @Override
188     public void disconnect(OvsdbClient client) {
189         if (client == null) {
190             return;
191         }
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();
198         }
199         CONNECTIONS.remove(client);
200     }
201
202     @Override
203     public void registerConnectionListener(OvsdbConnectionListener listener) {
204         LOG.info("registerConnectionListener: registering {}", listener.getClass().getSimpleName());
205         CONNECTION_LISTENERS.add(listener);
206         notifyAlreadyExistingConnectionsToListener(listener);
207     }
208
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);
214             });
215         }
216     }
217
218     @Override
219     public void unregisterConnectionListener(OvsdbConnectionListener listener) {
220         CONNECTION_LISTENERS.remove(listener);
221     }
222
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);
228
229         JsonRpcEndpoint factory = new JsonRpcEndpoint(objectMapper, channel);
230         JsonRpcServiceBinderHandler binderHandler = new JsonRpcServiceBinderHandler(factory);
231         binderHandler.setContext(channel);
232         channel.pipeline().addLast(binderHandler);
233
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));
240         return client;
241     }
242
243     /**
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.
247      */
248     @Override
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();
255             return true;
256         } else {
257             return false;
258         }
259     }
260
261     /**
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.
265      */
266     @Override
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();
273             return true;
274         } else {
275             return false;
276         }
277     }
278
279     @Override
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");
288         }
289         serverChannel = null;
290         return startOvsdbManagerWithSsl(ovsdbListenIp, ovsdbListenPort,
291             certificateManagerSrv, protocols, cipherSuites);
292     }
293
294     /**
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.
299      */
300     private void ovsdbManager(String ip, int port) {
301         if (useSSL) {
302             if (certManagerSrv == null) {
303                 LOG.error("Certificate Manager service is not available cannot establish the SSL communication.");
304                 return;
305             }
306             ovsdbManagerWithSsl(ip, port, certManagerSrv, certManagerSrv.getTlsProtocols(),
307                     certManagerSrv.getCipherSuites());
308         } else {
309             ovsdbManagerWithSsl(ip, port, null /* SslContext */, null, null);
310         }
311     }
312
313     /**
314      * OVSDB Passive listening thread that uses Netty ServerBootstrap to open
315      * passive connection with Ssl and handle channel callbacks.
316      */
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();
322         try {
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>() {
329                         @Override
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()));
345                                 }
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()));
351                                 }
352                                 channel.pipeline().addLast("ssl", new SslHandler(engine));
353                             }
354
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));
361
362                             handleNewPassiveConnection(channel);
363                         }
364                     });
365             serverBootstrap.option(ChannelOption.TCP_NODELAY, true);
366             serverBootstrap.option(ChannelOption.RCVBUF_ALLOCATOR,
367                     new AdaptiveRecvByteBufAllocator(65535, 65535, 65535));
368             // Start the server.
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);
379             throw throwable;
380         } finally {
381             // Shut down all event loops to terminate all threads.
382             bossGroup.shutdownGracefully();
383             workerGroup.shutdownGracefully();
384         }
385     }
386
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>>() {
391             @Override
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);
397                 } else {
398                     STALE_PASSIVE_CONNECTION_SERVICE.handleNewPassiveConnection(client, clientsFromSameNode);
399                 }
400             }
401
402             @Override
403             public void onFailure(Throwable failureException) {
404                 LOG.error("Probe failed to OVSDB switch. Disconnecting the channel {}", client.getConnectionInfo());
405                 client.disconnect();
406             }
407         }, CONNECTION_NOTIFIER_SERVICE);
408     }
409
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);
413             return;
414         }
415         SslHandler sslHandler = (SslHandler) channel.pipeline().get("ssl");
416         if (sslHandler != null) {
417             class HandleNewPassiveSslRunner implements Runnable {
418                 private int retryTimes = 3;
419
420                 private void retry() {
421                     if (retryTimes > 0) {
422                         EXECUTOR_SERVICE.schedule(this,  RETRY_PERIOD, TimeUnit.MILLISECONDS);
423                     } else {
424                         LOG.debug("channel closed {}", channel);
425                         channel.disconnect();
426                     }
427                     retryTimes--;
428                 }
429
430                 @Override
431                 public void run() {
432                     HandshakeStatus status = sslHandler.engine().getHandshakeStatus();
433                     LOG.debug("Handshake status {}", status);
434                     switch (status) {
435                         case FINISHED:
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);
441                                 retry();
442                             } else {
443                               //Check if peer is trusted before notifying listeners
444                                 try {
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);
453                                     retry();
454                                 }
455                             }
456                             break;
457
458                         case NEED_UNWRAP:
459                         case NEED_TASK:
460                             //Handshake still ongoing. Retry later.
461                             LOG.debug("handshake not done yet {}", status);
462                             retry();
463                             break;
464
465                         case NEED_WRAP:
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();
471                             } else {
472                                 /*
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.
480                                  */
481                                 LOG.debug("handshake not done yet {}", status);
482                                 retry();
483                             }
484                             break;
485
486                         default:
487                             LOG.error("unknown hadshake status {}", status);
488                     }
489                 }
490             }
491
492             EXECUTOR_SERVICE.schedule(new HandleNewPassiveSslRunner(),
493                     RETRY_PERIOD, TimeUnit.MILLISECONDS);
494         } else {
495             EXECUTOR_SERVICE.execute(() -> {
496                 OvsdbClient client = getChannelClient(channel, ConnectionType.PASSIVE,
497                     SocketConnectionType.NON_SSL);
498                 handleNewPassiveConnection(client);
499             });
500         }
501     }
502
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);
509             }
510         }
511         STALE_PASSIVE_CONNECTION_SERVICE.clientDisconnected(client);
512     }
513
514     @Override
515     public Collection<OvsdbClient> getConnections() {
516         return CONNECTIONS.keySet();
517     }
518
519     @Override
520     public void close() throws Exception {
521         LOG.info("OvsdbConnectionService closed");
522         JsonRpcEndpoint.close();
523     }
524
525     @Override
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)) {
531                 return client;
532             }
533         }
534         return null;
535     }
536
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);
545             }
546         }
547         return passiveClients;
548     }
549
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);
556             });
557         }
558     }
559
560     public void setOvsdbRpcTaskTimeout(int timeout) {
561         JsonRpcEndpoint.setReaperInterval(timeout);
562     }
563
564     /**
565      * Set useSSL flag.
566      *
567      * @param flag boolean for using ssl
568      */
569     public void setUseSsl(boolean flag) {
570         useSSL = flag;
571     }
572
573     /**
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)
579      */
580     public void setJsonRpcDecoderMaxFrameLength(int maxFrameLength) {
581         jsonRpcDecoderMaxFrameLength = maxFrameLength;
582         LOG.info("Json Rpc Decoder Max Frame Length set to : {}", jsonRpcDecoderMaxFrameLength);
583     }
584
585     public void setOvsdbListenerIp(String ip) {
586         LOG.info("OVSDB IP for listening connection is set to : {}", ip);
587         listenerIp = ip;
588     }
589
590     public void setOvsdbListenerPort(int portNumber) {
591         LOG.info("OVSDB port for listening connection is set to : {}", portNumber);
592         listenerPort = portNumber;
593     }
594
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());
603                 }
604             }
605         }
606     }
607 }