0b032e5df61286d949cb8e455064e2e67240bbb8
[ovsdb.git] / library / impl / src / main / java / org / opendaylight / ovsdb / lib / impl / OvsdbConnectionService.java
1 /*
2  * Copyright (c) 2014, 2015 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.collect.Maps;
15 import com.google.common.collect.Sets;
16 import com.google.common.util.concurrent.FutureCallback;
17 import com.google.common.util.concurrent.Futures;
18 import com.google.common.util.concurrent.ListenableFuture;
19 import com.google.common.util.concurrent.ThreadFactoryBuilder;
20 import io.netty.bootstrap.Bootstrap;
21 import io.netty.bootstrap.ServerBootstrap;
22 import io.netty.channel.AdaptiveRecvByteBufAllocator;
23 import io.netty.channel.Channel;
24 import io.netty.channel.ChannelFuture;
25 import io.netty.channel.ChannelInitializer;
26 import io.netty.channel.ChannelOption;
27 import io.netty.channel.EventLoopGroup;
28 import io.netty.channel.nio.NioEventLoopGroup;
29 import io.netty.channel.socket.SocketChannel;
30 import io.netty.channel.socket.nio.NioServerSocketChannel;
31 import io.netty.channel.socket.nio.NioSocketChannel;
32 import io.netty.handler.codec.string.StringEncoder;
33 import io.netty.handler.logging.LogLevel;
34 import io.netty.handler.logging.LoggingHandler;
35 import io.netty.handler.ssl.SslHandler;
36 import io.netty.handler.timeout.IdleStateHandler;
37 import io.netty.handler.timeout.ReadTimeoutHandler;
38 import io.netty.util.CharsetUtil;
39 import java.net.InetAddress;
40 import java.util.ArrayList;
41 import java.util.Arrays;
42 import java.util.Collection;
43 import java.util.List;
44 import java.util.Map;
45 import java.util.Set;
46 import java.util.concurrent.ExecutorService;
47 import java.util.concurrent.Executors;
48 import java.util.concurrent.ScheduledExecutorService;
49 import java.util.concurrent.ThreadFactory;
50 import java.util.concurrent.TimeUnit;
51 import javax.annotation.Nullable;
52 import javax.net.ssl.SSLContext;
53 import javax.net.ssl.SSLEngine;
54 import javax.net.ssl.SSLEngineResult.HandshakeStatus;
55 import javax.net.ssl.SSLPeerUnverifiedException;
56 import org.opendaylight.ovsdb.lib.OvsdbClient;
57 import org.opendaylight.ovsdb.lib.OvsdbConnection;
58 import org.opendaylight.ovsdb.lib.OvsdbConnectionInfo.ConnectionType;
59 import org.opendaylight.ovsdb.lib.OvsdbConnectionInfo.SocketConnectionType;
60 import org.opendaylight.ovsdb.lib.OvsdbConnectionListener;
61 import org.opendaylight.ovsdb.lib.jsonrpc.ExceptionHandler;
62 import org.opendaylight.ovsdb.lib.jsonrpc.JsonRpcDecoder;
63 import org.opendaylight.ovsdb.lib.jsonrpc.JsonRpcEndpoint;
64 import org.opendaylight.ovsdb.lib.jsonrpc.JsonRpcServiceBinderHandler;
65 import org.opendaylight.ovsdb.lib.message.OvsdbRPC;
66 import org.slf4j.Logger;
67 import org.slf4j.LoggerFactory;
68
69 /**
70  * OvsDBConnectionService provides OVSDB connection management functionality which includes
71  * both Active and Passive connections.
72  * From the Library perspective, Active OVSDB connections are those that are initiated from
73  * the Controller towards the ovsdb-manager.
74  * While Passive OVSDB connections are those that are initiated from the ovs towards
75  * the controller.
76  *
77  * <p>Applications that use OvsDBConnectionService can use the OvsDBConnection class' connect APIs
78  * to initiate Active connections and can listen to the asynchronous Passive connections via
79  * registerConnectionListener listener API.
80  *
81  * <p>The library is designed as Java modular component that can work in both OSGi and non-OSGi
82  * environment. Hence a single instance of the service will be active (via Service Registry in OSGi)
83  * and a Singleton object in a non-OSGi environment.
84  */
85 public class OvsdbConnectionService implements AutoCloseable, OvsdbConnection {
86     private static final Logger LOG = LoggerFactory.getLogger(OvsdbConnectionService.class);
87
88     private static ThreadFactory passiveConnectionThreadFactory = new ThreadFactoryBuilder()
89             .setNameFormat("OVSDBPassiveConnServ-%d").build();
90     private static ScheduledExecutorService executorService
91             = Executors.newScheduledThreadPool(10, passiveConnectionThreadFactory);
92
93     private static ThreadFactory connectionNotifierThreadFactory = new ThreadFactoryBuilder()
94             .setNameFormat("OVSDBConnNotifSer-%d").build();
95     private static ExecutorService connectionNotifierService
96             = Executors.newCachedThreadPool(connectionNotifierThreadFactory);
97
98     private static Set<OvsdbConnectionListener> connectionListeners = Sets.newHashSet();
99     private static Map<OvsdbClient, Channel> connections = Maps.newHashMap();
100     private static OvsdbConnection connectionService;
101     private static volatile boolean singletonCreated = false;
102     private static final int IDLE_READER_TIMEOUT = 30;
103     private static final int READ_TIMEOUT = 180;
104
105     private static final StalePassiveConnectionService STALE_PASSIVE_CONNECTION_SERVICE =
106             new StalePassiveConnectionService(executorService);
107
108     private static int retryPeriod = 100; // retry after 100 milliseconds
109
110
111     public static OvsdbConnection getService() {
112         if (connectionService == null) {
113             connectionService = new OvsdbConnectionService();
114         }
115         return connectionService;
116     }
117
118     @Override
119     public OvsdbClient connect(final InetAddress address, final int port) {
120         return connectWithSsl(address, port, null /* SslContext */);
121     }
122
123     @Override
124     public OvsdbClient connectWithSsl(final InetAddress address, final int port,
125                                final SSLContext sslContext) {
126         try {
127             Bootstrap bootstrap = new Bootstrap();
128             bootstrap.group(new NioEventLoopGroup());
129             bootstrap.channel(NioSocketChannel.class);
130             bootstrap.option(ChannelOption.TCP_NODELAY, true);
131             bootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(65535, 65535, 65535));
132
133             bootstrap.handler(new ChannelInitializer<SocketChannel>() {
134                 @Override
135                 public void initChannel(SocketChannel channel) throws Exception {
136                     if (sslContext != null) {
137                         /* First add ssl handler if ssl context is given */
138                         SSLEngine engine =
139                             sslContext.createSSLEngine(address.toString(), port);
140                         engine.setUseClientMode(true);
141                         channel.pipeline().addLast("ssl", new SslHandler(engine));
142                     }
143                     channel.pipeline().addLast(
144                             //new LoggingHandler(LogLevel.INFO),
145                             new JsonRpcDecoder(100000),
146                             new StringEncoder(CharsetUtil.UTF_8),
147                             new IdleStateHandler(IDLE_READER_TIMEOUT, 0, 0),
148                             new ReadTimeoutHandler(READ_TIMEOUT),
149                             new ExceptionHandler());
150                 }
151             });
152
153             ChannelFuture future = bootstrap.connect(address, port).sync();
154             Channel channel = future.channel();
155             return getChannelClient(channel, ConnectionType.ACTIVE, SocketConnectionType.SSL);
156         } catch (InterruptedException e) {
157             LOG.warn("Failed to connect {}:{}", address, port, e);
158         }
159         return null;
160     }
161
162     @Override
163     public void disconnect(OvsdbClient client) {
164         if (client == null) {
165             return;
166         }
167         Channel channel = connections.get(client);
168         if (channel != null) {
169             channel.disconnect();
170         }
171         connections.remove(client);
172     }
173
174     @Override
175     public void registerConnectionListener(OvsdbConnectionListener listener) {
176         LOG.info("registerConnectionListener: registering {}", listener.getClass().getSimpleName());
177         connectionListeners.add(listener);
178     }
179
180     @Override
181     public void unregisterConnectionListener(OvsdbConnectionListener listener) {
182         connectionListeners.remove(listener);
183     }
184
185     private static OvsdbClient getChannelClient(Channel channel, ConnectionType type,
186         SocketConnectionType socketConnType) {
187         ObjectMapper objectMapper = new ObjectMapper();
188         objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
189         objectMapper.setSerializationInclusion(Include.NON_NULL);
190
191         JsonRpcEndpoint factory = new JsonRpcEndpoint(objectMapper, channel);
192         JsonRpcServiceBinderHandler binderHandler = new JsonRpcServiceBinderHandler(factory);
193         binderHandler.setContext(channel);
194         channel.pipeline().addLast(binderHandler);
195
196         OvsdbRPC rpc = factory.getClient(channel, OvsdbRPC.class);
197         OvsdbClientImpl client = new OvsdbClientImpl(rpc, channel, type, socketConnType);
198         client.setConnectionPublished(true);
199         connections.put(client, channel);
200         ChannelFuture closeFuture = channel.closeFuture();
201         closeFuture.addListener(new ChannelConnectionHandler(client));
202         return client;
203     }
204
205     /**
206      * Method that initiates the Passive OVSDB channel listening functionality.
207      * By default the ovsdb passive connection will listen in port 6640 which can
208      * be overridden using the ovsdb.listenPort system property.
209      */
210     @Override
211     public synchronized boolean startOvsdbManager(final int ovsdbListenPort) {
212         if (!singletonCreated) {
213             LOG.info("startOvsdbManager: Starting");
214             new Thread() {
215                 @Override
216                 public void run() {
217                     ovsdbManager(ovsdbListenPort);
218                 }
219             }.start();
220             singletonCreated = true;
221             return true;
222         } else {
223             return false;
224         }
225     }
226
227     /**
228      * Method that initiates the Passive OVSDB channel listening functionality
229      * with ssl.By default the ovsdb passive connection will listen in port
230      * 6640 which can be overridden using the ovsdb.listenPort system property.
231      */
232     @Override
233     public synchronized boolean startOvsdbManagerWithSsl(final int ovsdbListenPort,
234                                      final SSLContext sslContext) {
235         if (!singletonCreated) {
236             new Thread() {
237                 @Override
238                 public void run() {
239                     ovsdbManagerWithSsl(ovsdbListenPort, sslContext);
240                 }
241             }.start();
242             singletonCreated = true;
243             return true;
244         } else {
245             return false;
246         }
247     }
248
249     /**
250      * OVSDB Passive listening thread that uses Netty ServerBootstrap to open
251      * passive connection handle channel callbacks.
252      */
253     private static void ovsdbManager(int port) {
254         ovsdbManagerWithSsl(port, null /* SslContext */);
255     }
256
257     /**
258      * OVSDB Passive listening thread that uses Netty ServerBootstrap to open
259      * passive connection with Ssl and handle channel callbacks.
260      */
261     private static void ovsdbManagerWithSsl(int port, final SSLContext sslContext) {
262         EventLoopGroup bossGroup = new NioEventLoopGroup();
263         EventLoopGroup workerGroup = new NioEventLoopGroup();
264         try {
265             ServerBootstrap serverBootstrap = new ServerBootstrap();
266             serverBootstrap.group(bossGroup, workerGroup)
267                     .channel(NioServerSocketChannel.class)
268                     .option(ChannelOption.SO_BACKLOG, 100)
269                     .handler(new LoggingHandler(LogLevel.INFO))
270                     .childHandler(new ChannelInitializer<SocketChannel>() {
271                         @Override
272                         public void initChannel(SocketChannel channel) throws Exception {
273                             LOG.debug("New Passive channel created : {}", channel);
274                             if (sslContext != null) {
275                                 /* Add SSL handler first if SSL context is provided */
276                                 SSLEngine engine = sslContext.createSSLEngine();
277                                 engine.setUseClientMode(false); // work in a server mode
278                                 engine.setNeedClientAuth(true); // need client authentication
279                                 //Disable SSLv3 and enable all other supported protocols
280                                 String[] protocols = {"SSLv2Hello", "TLSv1", "TLSv1.1", "TLSv1.2"};
281                                 LOG.debug("Set enable protocols {}", Arrays.toString(protocols));
282                                 engine.setEnabledProtocols(protocols);
283                                 LOG.debug("Supported ssl protocols {}",
284                                         Arrays.toString(engine.getSupportedProtocols()));
285                                 LOG.debug("Enabled ssl protocols {}",
286                                         Arrays.toString(engine.getEnabledProtocols()));
287                                 //Set cipher suites
288                                 String[] cipherSuites = {"TLS_RSA_WITH_AES_128_CBC_SHA"};
289                                 LOG.debug("Set enable cipher cuites {}", Arrays.toString(cipherSuites));
290                                 engine.setEnabledCipherSuites(cipherSuites);
291                                 LOG.debug("Enabled cipher suites {}",
292                                         Arrays.toString(engine.getEnabledCipherSuites()));
293                                 channel.pipeline().addLast("ssl", new SslHandler(engine));
294                             }
295
296                             channel.pipeline().addLast(
297                                  new JsonRpcDecoder(100000),
298                                  new StringEncoder(CharsetUtil.UTF_8),
299                                  new IdleStateHandler(IDLE_READER_TIMEOUT, 0, 0),
300                                  new ReadTimeoutHandler(READ_TIMEOUT),
301                                  new ExceptionHandler());
302
303                             handleNewPassiveConnection(channel);
304                         }
305                     });
306             serverBootstrap.option(ChannelOption.TCP_NODELAY, true);
307             serverBootstrap.option(ChannelOption.RCVBUF_ALLOCATOR,
308                     new AdaptiveRecvByteBufAllocator(65535, 65535, 65535));
309             // Start the server.
310             ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
311             Channel serverListenChannel = channelFuture.channel();
312             // Wait until the server socket is closed.
313             serverListenChannel.closeFuture().sync();
314         } catch (InterruptedException e) {
315             LOG.error("Thread interrupted", e);
316         } finally {
317             // Shut down all event loops to terminate all threads.
318             bossGroup.shutdownGracefully();
319             workerGroup.shutdownGracefully();
320         }
321     }
322
323     private static void handleNewPassiveConnection(OvsdbClient client) {
324         ListenableFuture<List<String>> echoFuture = client.echo();
325         LOG.debug("Send echo message to probe the OVSDB switch {}",client.getConnectionInfo());
326         Futures.addCallback(echoFuture, new FutureCallback<List<String>>() {
327             @Override
328             public void onSuccess(@Nullable List<String> result) {
329                 LOG.debug("Probe was successful to OVSDB switch {}",client.getConnectionInfo());
330                 List<OvsdbClient> clientsFromSameNode = getPassiveClientsFromSameNode(client);
331                 if (clientsFromSameNode.size() == 0) {
332                     notifyListenerForPassiveConnection(client);
333                 } else {
334                     STALE_PASSIVE_CONNECTION_SERVICE.handleNewPassiveConnection(client, clientsFromSameNode);
335                 }
336             }
337
338             @Override
339             public void onFailure(Throwable failureException) {
340                 LOG.error("Probe failed to OVSDB switch. Disconnecting the channel {}", client.getConnectionInfo());
341                 client.disconnect();
342             }
343         }, connectionNotifierService);
344     }
345
346     private static void handleNewPassiveConnection(final Channel channel) {
347         if (!channel.isOpen()) {
348             LOG.warn("Channel {} is not open, skipped further processing of the connection.",channel);
349             return;
350         }
351         SslHandler sslHandler = (SslHandler) channel.pipeline().get("ssl");
352         if (sslHandler != null) {
353             class HandleNewPassiveSslRunner implements Runnable {
354                 public SslHandler sslHandler;
355                 public final Channel channel;
356                 private int retryTimes;
357
358                 HandleNewPassiveSslRunner(Channel channel, SslHandler sslHandler) {
359                     this.channel = channel;
360                     this.sslHandler = sslHandler;
361                     this.retryTimes = 3;
362                 }
363
364                 @Override
365                 public void run() {
366                     HandshakeStatus status = sslHandler.engine().getHandshakeStatus();
367                     LOG.debug("Handshake status {}", status);
368                     switch (status) {
369                         case FINISHED:
370                         case NOT_HANDSHAKING:
371                             if (sslHandler.engine().getSession().getCipherSuite()
372                                     .equals("SSL_NULL_WITH_NULL_NULL")) {
373                                 // Not begin handshake yet. Retry later.
374                                 LOG.debug("handshake not begin yet {}", status);
375                                 executorService.schedule(this, retryPeriod, TimeUnit.MILLISECONDS);
376                             } else {
377                               //Check if peer is trusted before notifying listeners
378                                 try {
379                                     sslHandler.engine().getSession().getPeerCertificates();
380                                     //Handshake done. Notify listener.
381                                     OvsdbClient client = getChannelClient(channel, ConnectionType.PASSIVE,
382                                         SocketConnectionType.SSL);
383                                     handleNewPassiveConnection(client);
384                                 } catch (SSLPeerUnverifiedException e) {
385                                     //Trust manager is still checking peer certificate. Retry later
386                                     LOG.debug("Peer certifiacte is not verified yet {}", status);
387                                     executorService.schedule(this, retryPeriod, TimeUnit.MILLISECONDS);
388                                 }
389                             }
390                             break;
391
392                         case NEED_UNWRAP:
393                         case NEED_TASK:
394                             //Handshake still ongoing. Retry later.
395                             LOG.debug("handshake not done yet {}", status);
396                             executorService.schedule(this,  retryPeriod, TimeUnit.MILLISECONDS);
397                             break;
398
399                         case NEED_WRAP:
400                             if (sslHandler.engine().getSession().getCipherSuite()
401                                     .equals("SSL_NULL_WITH_NULL_NULL")) {
402                                 /* peer not authenticated. No need to notify listener in this case. */
403                                 LOG.error("Ssl handshake fail. channel {}", channel);
404                             } else {
405                                 /*
406                                  * peer is authenticated. Give some time to wait for completion.
407                                  * If status is still NEED_WRAP, client might already disconnect.
408                                  * This happens when the first time client connects to controller in two-way handshake.
409                                  * After obtaining controller certificate, client will disconnect and start
410                                  * new connection with controller certificate it obtained.
411                                  * In this case no need to do anything for the first connection attempt. Just skip
412                                  * since client will reconnect later.
413                                  */
414                                 LOG.debug("handshake not done yet {}", status);
415                                 if (retryTimes > 0) {
416                                     executorService.schedule(this,  retryPeriod, TimeUnit.MILLISECONDS);
417                                 } else {
418                                     LOG.debug("channel closed {}", channel);
419                                 }
420                                 retryTimes--;
421                             }
422                             break;
423
424                         default:
425                             LOG.error("unknown hadshake status {}", status);
426                     }
427                 }
428             }
429
430             executorService.schedule(new HandleNewPassiveSslRunner(channel, sslHandler),
431                     retryPeriod, TimeUnit.MILLISECONDS);
432         } else {
433             executorService.execute(new Runnable() {
434                 @Override
435                 public void run() {
436                     OvsdbClient client = getChannelClient(channel, ConnectionType.PASSIVE,
437                         SocketConnectionType.NON_SSL);
438                     handleNewPassiveConnection(client);
439                 }
440             });
441         }
442     }
443
444     public static void channelClosed(final OvsdbClient client) {
445         LOG.info("Connection closed {}", client.getConnectionInfo().toString());
446         connections.remove(client);
447         if (client.isConnectionPublished()) {
448             for (OvsdbConnectionListener listener : connectionListeners) {
449                 listener.disconnected(client);
450             }
451         }
452         STALE_PASSIVE_CONNECTION_SERVICE.clientDisconnected(client);
453     }
454
455     @Override
456     public Collection<OvsdbClient> getConnections() {
457         return connections.keySet();
458     }
459
460     @Override
461     public void close() throws Exception {
462         LOG.info("OvsdbConnectionService closed");
463     }
464
465     @Override
466     public OvsdbClient getClient(Channel channel) {
467         for (OvsdbClient client : connections.keySet()) {
468             Channel ctx = connections.get(client);
469             if (ctx.equals(channel)) {
470                 return client;
471             }
472         }
473         return null;
474     }
475
476     private static List<OvsdbClient> getPassiveClientsFromSameNode(OvsdbClient ovsdbClient) {
477         List<OvsdbClient> passiveClients = new ArrayList<>();
478         for (OvsdbClient client : connections.keySet()) {
479             if (!client.equals(ovsdbClient)
480                     && client.getConnectionInfo().getRemoteAddress()
481                             .equals(ovsdbClient.getConnectionInfo().getRemoteAddress())
482                     && client.getConnectionInfo().getType() == ConnectionType.PASSIVE) {
483                 passiveClients.add(client);
484             }
485         }
486         return passiveClients;
487     }
488
489     public static void notifyListenerForPassiveConnection(final OvsdbClient client) {
490         client.setConnectionPublished(true);
491         for (final OvsdbConnectionListener listener : connectionListeners) {
492             connectionNotifierService.submit(new Runnable() {
493                 @Override
494                 public void run() {
495                     LOG.trace("Connection {} notified to listener {}", client.getConnectionInfo(), listener);
496                     listener.connected(client);
497                 }
498             });
499         }
500     }
501 }