blob: 53611f353bfe502ab8732233fe9bb88f64708ff5 [file] [log] [blame]
Thomas Vachuska58de4162015-09-10 16:15:33 -07001/*
2 * Copyright 2015 Open Networking Laboratory
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Madan Jampaniafeebbd2015-05-19 15:26:01 -070016package org.onosproject.store.cluster.messaging.impl;
17
JunHuy Lam39eb4292015-06-26 17:24:23 +090018import com.google.common.base.Strings;
Aaron Kruglikov1b727382016-02-09 16:17:47 -080019import com.google.common.cache.Cache;
20import com.google.common.cache.CacheBuilder;
21import com.google.common.cache.RemovalListener;
22import com.google.common.cache.RemovalNotification;
23import com.google.common.util.concurrent.MoreExecutors;
Madan Jampania9e70a62016-03-02 16:28:18 -080024
Aaron Kruglikov1b727382016-02-09 16:17:47 -080025import io.netty.bootstrap.Bootstrap;
26import io.netty.bootstrap.ServerBootstrap;
27import io.netty.buffer.PooledByteBufAllocator;
28import io.netty.channel.Channel;
29import io.netty.channel.ChannelFuture;
30import io.netty.channel.ChannelHandler;
31import io.netty.channel.ChannelHandlerContext;
32import io.netty.channel.ChannelInitializer;
33import io.netty.channel.ChannelOption;
34import io.netty.channel.EventLoopGroup;
35import io.netty.channel.ServerChannel;
36import io.netty.channel.SimpleChannelInboundHandler;
37import io.netty.channel.epoll.EpollEventLoopGroup;
38import io.netty.channel.epoll.EpollServerSocketChannel;
39import io.netty.channel.epoll.EpollSocketChannel;
40import io.netty.channel.nio.NioEventLoopGroup;
41import io.netty.channel.socket.SocketChannel;
42import io.netty.channel.socket.nio.NioServerSocketChannel;
43import io.netty.channel.socket.nio.NioSocketChannel;
Madan Jampania9e70a62016-03-02 16:28:18 -080044
Aaron Kruglikov1b727382016-02-09 16:17:47 -080045import org.apache.commons.pool.KeyedPoolableObjectFactory;
46import org.apache.commons.pool.impl.GenericKeyedObjectPool;
Madan Jampaniafeebbd2015-05-19 15:26:01 -070047import org.apache.felix.scr.annotations.Activate;
48import org.apache.felix.scr.annotations.Component;
49import org.apache.felix.scr.annotations.Deactivate;
50import org.apache.felix.scr.annotations.Reference;
51import org.apache.felix.scr.annotations.ReferenceCardinality;
52import org.apache.felix.scr.annotations.Service;
Aaron Kruglikov1b727382016-02-09 16:17:47 -080053import org.onlab.util.Tools;
Madan Jampaniec1df022015-10-13 21:23:03 -070054import org.onosproject.cluster.ClusterMetadataService;
Madan Jampaniafeebbd2015-05-19 15:26:01 -070055import org.onosproject.cluster.ControllerNode;
56import org.onosproject.store.cluster.messaging.Endpoint;
Madan Jampania9e70a62016-03-02 16:28:18 -080057import org.onosproject.store.cluster.messaging.MessagingException;
Aaron Kruglikov1b727382016-02-09 16:17:47 -080058import org.onosproject.store.cluster.messaging.MessagingService;
Madan Jampania9e70a62016-03-02 16:28:18 -080059import org.onosproject.store.cluster.messaging.impl.InternalMessage.Status;
Madan Jampaniafeebbd2015-05-19 15:26:01 -070060import org.slf4j.Logger;
61import org.slf4j.LoggerFactory;
62
Aaron Kruglikov1b727382016-02-09 16:17:47 -080063import javax.net.ssl.KeyManagerFactory;
64import javax.net.ssl.SSLContext;
65import javax.net.ssl.SSLEngine;
66import javax.net.ssl.TrustManagerFactory;
Madan Jampania9e70a62016-03-02 16:28:18 -080067
Aaron Kruglikov1b727382016-02-09 16:17:47 -080068import java.io.FileInputStream;
69import java.io.IOException;
70import java.security.KeyStore;
71import java.util.Map;
Madan Jampania9e70a62016-03-02 16:28:18 -080072import java.util.Optional;
Aaron Kruglikov1b727382016-02-09 16:17:47 -080073import java.util.concurrent.CompletableFuture;
74import java.util.concurrent.ConcurrentHashMap;
75import java.util.concurrent.Executor;
76import java.util.concurrent.RejectedExecutionException;
77import java.util.concurrent.TimeUnit;
78import java.util.concurrent.TimeoutException;
79import java.util.concurrent.atomic.AtomicBoolean;
80import java.util.concurrent.atomic.AtomicLong;
81import java.util.function.BiConsumer;
82import java.util.function.BiFunction;
83import java.util.function.Consumer;
84
Heedo Kang4a47a302016-02-29 17:40:23 +090085import static org.onosproject.security.AppGuard.checkPermission;
86import static org.onosproject.security.AppPermission.Type.CLUSTER_WRITE;
87
Madan Jampaniafeebbd2015-05-19 15:26:01 -070088/**
89 * Netty based MessagingService.
90 */
91@Component(immediate = true, enabled = true)
92@Service
Aaron Kruglikov1b727382016-02-09 16:17:47 -080093public class NettyMessagingManager implements MessagingService {
94
Madan Jampanif5c38a72016-02-17 18:26:15 -080095 private static final int REPLY_TIME_OUT_SEC = 2;
Aaron Kruglikov1b727382016-02-09 16:17:47 -080096 private static final short MIN_KS_LENGTH = 6;
Madan Jampaniafeebbd2015-05-19 15:26:01 -070097
98 private final Logger log = LoggerFactory.getLogger(getClass());
99
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800100 private static final String REPLY_MESSAGE_TYPE = "NETTY_MESSAGING_REQUEST_REPLY";
101
102 private Endpoint localEp;
103 private int preamble;
104 private final AtomicBoolean started = new AtomicBoolean(false);
105 private final Map<String, Consumer<InternalMessage>> handlers = new ConcurrentHashMap<>();
106 private final AtomicLong messageIdGenerator = new AtomicLong(0);
107 private final Cache<Long, Callback> callbacks = CacheBuilder.newBuilder()
Madan Jampanif5c38a72016-02-17 18:26:15 -0800108 .expireAfterWrite(REPLY_TIME_OUT_SEC, TimeUnit.SECONDS)
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800109 .removalListener(new RemovalListener<Long, Callback>() {
110 @Override
111 public void onRemoval(RemovalNotification<Long, Callback> entry) {
112 if (entry.wasEvicted()) {
113 entry.getValue().completeExceptionally(new TimeoutException("Timedout waiting for reply"));
114 }
115 }
116 })
117 .build();
118
119 private final GenericKeyedObjectPool<Endpoint, Connection> channels
120 = new GenericKeyedObjectPool<Endpoint, Connection>(new OnosCommunicationChannelFactory());
121
122 private EventLoopGroup serverGroup;
123 private EventLoopGroup clientGroup;
124 private Class<? extends ServerChannel> serverChannelClass;
125 private Class<? extends Channel> clientChannelClass;
126
127 protected static final boolean TLS_DISABLED = false;
128 protected boolean enableNettyTls = TLS_DISABLED;
129
130 protected String ksLocation;
131 protected String tsLocation;
132 protected char[] ksPwd;
133 protected char[] tsPwd;
JunHuy Lam39eb4292015-06-26 17:24:23 +0900134
Madan Jampaniafeebbd2015-05-19 15:26:01 -0700135 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Madan Jampaniec1df022015-10-13 21:23:03 -0700136 protected ClusterMetadataService clusterMetadataService;
Madan Jampaniafeebbd2015-05-19 15:26:01 -0700137
138 @Activate
139 public void activate() throws Exception {
Madan Jampaniec1df022015-10-13 21:23:03 -0700140 ControllerNode localNode = clusterMetadataService.getLocalNode();
Jonathan Hartd9df7bd2015-11-10 17:10:25 -0800141 getTlsParameters();
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800142
143 if (started.get()) {
144 log.warn("Already running at local endpoint: {}", localEp);
145 return;
146 }
147 this.preamble = clusterMetadataService.getClusterMetadata().getName().hashCode();
148 this.localEp = new Endpoint(localNode.ip(), localNode.tcpPort());
149 channels.setLifo(true);
150 channels.setTestOnBorrow(true);
151 channels.setTestOnReturn(true);
152 channels.setMinEvictableIdleTimeMillis(60_000L);
153 channels.setTimeBetweenEvictionRunsMillis(30_000L);
154 initEventLoopGroup();
155 startAcceptingConnections();
156 started.set(true);
Madan Jampanif5c38a72016-02-17 18:26:15 -0800157 serverGroup.scheduleWithFixedDelay(callbacks::cleanUp, 0, REPLY_TIME_OUT_SEC, TimeUnit.SECONDS);
Madan Jampaniafeebbd2015-05-19 15:26:01 -0700158 log.info("Started");
159 }
160
161 @Deactivate
162 public void deactivate() throws Exception {
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800163 if (started.get()) {
164 channels.close();
165 serverGroup.shutdownGracefully();
166 clientGroup.shutdownGracefully();
167 started.set(false);
168 }
Madan Jampaniafeebbd2015-05-19 15:26:01 -0700169 log.info("Stopped");
170 }
JunHuy Lam39eb4292015-06-26 17:24:23 +0900171
Jonathan Hartd9df7bd2015-11-10 17:10:25 -0800172 private void getTlsParameters() {
JunHuy Lam39eb4292015-06-26 17:24:23 +0900173 String tempString = System.getProperty("enableNettyTLS");
Jonathan Hartd9df7bd2015-11-10 17:10:25 -0800174 enableNettyTls = Strings.isNullOrEmpty(tempString) ? TLS_DISABLED : Boolean.parseBoolean(tempString);
175 log.info("enableNettyTLS = {}", enableNettyTls);
176 if (enableNettyTls) {
JunHuy Lam39eb4292015-06-26 17:24:23 +0900177 ksLocation = System.getProperty("javax.net.ssl.keyStore");
178 if (Strings.isNullOrEmpty(ksLocation)) {
Jonathan Hartd9df7bd2015-11-10 17:10:25 -0800179 enableNettyTls = TLS_DISABLED;
JunHuy Lam39eb4292015-06-26 17:24:23 +0900180 return;
181 }
182 tsLocation = System.getProperty("javax.net.ssl.trustStore");
183 if (Strings.isNullOrEmpty(tsLocation)) {
Jonathan Hartd9df7bd2015-11-10 17:10:25 -0800184 enableNettyTls = TLS_DISABLED;
JunHuy Lam39eb4292015-06-26 17:24:23 +0900185 return;
186 }
187 ksPwd = System.getProperty("javax.net.ssl.keyStorePassword").toCharArray();
188 if (MIN_KS_LENGTH > ksPwd.length) {
Jonathan Hartd9df7bd2015-11-10 17:10:25 -0800189 enableNettyTls = TLS_DISABLED;
JunHuy Lam39eb4292015-06-26 17:24:23 +0900190 return;
191 }
192 tsPwd = System.getProperty("javax.net.ssl.trustStorePassword").toCharArray();
193 if (MIN_KS_LENGTH > tsPwd.length) {
Jonathan Hartd9df7bd2015-11-10 17:10:25 -0800194 enableNettyTls = TLS_DISABLED;
JunHuy Lam39eb4292015-06-26 17:24:23 +0900195 return;
196 }
197 }
198 }
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800199 private void initEventLoopGroup() {
200 // try Epoll first and if that does work, use nio.
201 try {
202 clientGroup = new EpollEventLoopGroup();
203 serverGroup = new EpollEventLoopGroup();
204 serverChannelClass = EpollServerSocketChannel.class;
205 clientChannelClass = EpollSocketChannel.class;
206 return;
207 } catch (Throwable e) {
208 log.debug("Failed to initialize native (epoll) transport. "
209 + "Reason: {}. Proceeding with nio.", e.getMessage());
210 }
211 clientGroup = new NioEventLoopGroup();
212 serverGroup = new NioEventLoopGroup();
213 serverChannelClass = NioServerSocketChannel.class;
214 clientChannelClass = NioSocketChannel.class;
215 }
216
217 @Override
218 public CompletableFuture<Void> sendAsync(Endpoint ep, String type, byte[] payload) {
Heedo Kang4a47a302016-02-29 17:40:23 +0900219 checkPermission(CLUSTER_WRITE);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800220 InternalMessage message = new InternalMessage(messageIdGenerator.incrementAndGet(),
221 localEp,
222 type,
223 payload);
224 return sendAsync(ep, message);
225 }
226
227 protected CompletableFuture<Void> sendAsync(Endpoint ep, InternalMessage message) {
Heedo Kang4a47a302016-02-29 17:40:23 +0900228 checkPermission(CLUSTER_WRITE);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800229 if (ep.equals(localEp)) {
230 try {
231 dispatchLocally(message);
232 } catch (IOException e) {
233 return Tools.exceptionalFuture(e);
234 }
235 return CompletableFuture.completedFuture(null);
236 }
237
238 CompletableFuture<Void> future = new CompletableFuture<>();
239 try {
240 Connection connection = null;
241 try {
242 connection = channels.borrowObject(ep);
243 connection.send(message, future);
244 } finally {
245 channels.returnObject(ep, connection);
246 }
247 } catch (Exception e) {
248 future.completeExceptionally(e);
249 }
250 return future;
251 }
252
253 @Override
254 public CompletableFuture<byte[]> sendAndReceive(Endpoint ep, String type, byte[] payload) {
Heedo Kang4a47a302016-02-29 17:40:23 +0900255 checkPermission(CLUSTER_WRITE);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800256 return sendAndReceive(ep, type, payload, MoreExecutors.directExecutor());
257 }
258
259 @Override
260 public CompletableFuture<byte[]> sendAndReceive(Endpoint ep, String type, byte[] payload, Executor executor) {
Heedo Kang4a47a302016-02-29 17:40:23 +0900261 checkPermission(CLUSTER_WRITE);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800262 CompletableFuture<byte[]> response = new CompletableFuture<>();
263 Callback callback = new Callback(response, executor);
264 Long messageId = messageIdGenerator.incrementAndGet();
265 callbacks.put(messageId, callback);
266 InternalMessage message = new InternalMessage(messageId, localEp, type, payload);
267 return sendAsync(ep, message).whenComplete((r, e) -> {
268 if (e != null) {
269 callbacks.invalidate(messageId);
270 }
271 }).thenCompose(v -> response);
272 }
273
274 @Override
275 public void registerHandler(String type, BiConsumer<Endpoint, byte[]> handler, Executor executor) {
Heedo Kang4a47a302016-02-29 17:40:23 +0900276 checkPermission(CLUSTER_WRITE);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800277 handlers.put(type, message -> executor.execute(() -> handler.accept(message.sender(), message.payload())));
278 }
279
280 @Override
281 public void registerHandler(String type, BiFunction<Endpoint, byte[], byte[]> handler, Executor executor) {
Heedo Kang4a47a302016-02-29 17:40:23 +0900282 checkPermission(CLUSTER_WRITE);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800283 handlers.put(type, message -> executor.execute(() -> {
Madan Jampania9e70a62016-03-02 16:28:18 -0800284 byte[] responsePayload = null;
285 Status status = Status.OK;
286 try {
287 responsePayload = handler.apply(message.sender(), message.payload());
288 } catch (Exception e) {
289 status = Status.ERROR_HANDLER_EXCEPTION;
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800290 }
Madan Jampania9e70a62016-03-02 16:28:18 -0800291 sendReply(message, status, Optional.ofNullable(responsePayload));
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800292 }));
293 }
294
295 @Override
296 public void registerHandler(String type, BiFunction<Endpoint, byte[], CompletableFuture<byte[]>> handler) {
Heedo Kang4a47a302016-02-29 17:40:23 +0900297 checkPermission(CLUSTER_WRITE);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800298 handlers.put(type, message -> {
299 handler.apply(message.sender(), message.payload()).whenComplete((result, error) -> {
Madan Jampania9e70a62016-03-02 16:28:18 -0800300 Status status = error == null ? Status.OK : Status.ERROR_HANDLER_EXCEPTION;
301 sendReply(message, status, Optional.ofNullable(result));
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800302 });
303 });
304 }
305
306 @Override
307 public void unregisterHandler(String type) {
Heedo Kang4a47a302016-02-29 17:40:23 +0900308 checkPermission(CLUSTER_WRITE);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800309 handlers.remove(type);
310 }
311
312 private void startAcceptingConnections() throws InterruptedException {
313 ServerBootstrap b = new ServerBootstrap();
314 b.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 32 * 1024);
315 b.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024);
316 b.option(ChannelOption.SO_RCVBUF, 1048576);
317 b.option(ChannelOption.TCP_NODELAY, true);
318 b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
319 b.group(serverGroup, clientGroup);
320 b.channel(serverChannelClass);
321 if (enableNettyTls) {
322 b.childHandler(new SslServerCommunicationChannelInitializer());
323 } else {
324 b.childHandler(new OnosCommunicationChannelInitializer());
325 }
326 b.option(ChannelOption.SO_BACKLOG, 128);
327 b.childOption(ChannelOption.SO_KEEPALIVE, true);
328
329 // Bind and start to accept incoming connections.
330 b.bind(localEp.port()).sync().addListener(future -> {
331 if (future.isSuccess()) {
332 log.info("{} accepting incoming connections on port {}", localEp.host(), localEp.port());
333 } else {
334 log.warn("{} failed to bind to port {}", localEp.host(), localEp.port(), future.cause());
335 }
336 });
337 }
338
339 private class OnosCommunicationChannelFactory
340 implements KeyedPoolableObjectFactory<Endpoint, Connection> {
341
342 @Override
343 public void activateObject(Endpoint endpoint, Connection connection)
344 throws Exception {
345 }
346
347 @Override
348 public void destroyObject(Endpoint ep, Connection connection) throws Exception {
349 log.debug("Closing connection to {}", ep);
350 //Is this the right way to destroy?
351 connection.destroy();
352 }
353
354 @Override
355 public Connection makeObject(Endpoint ep) throws Exception {
356 Bootstrap bootstrap = new Bootstrap();
357 bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
358 bootstrap.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 10 * 64 * 1024);
359 bootstrap.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 10 * 32 * 1024);
360 bootstrap.option(ChannelOption.SO_SNDBUF, 1048576);
361 bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000);
362 bootstrap.group(clientGroup);
363 // TODO: Make this faster:
364 // http://normanmaurer.me/presentations/2014-facebook-eng-netty/slides.html#37.0
365 bootstrap.channel(clientChannelClass);
366 bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
367 if (enableNettyTls) {
368 bootstrap.handler(new SslClientCommunicationChannelInitializer());
369 } else {
370 bootstrap.handler(new OnosCommunicationChannelInitializer());
371 }
372 // Start the client.
373 CompletableFuture<Channel> retFuture = new CompletableFuture<>();
374 ChannelFuture f = bootstrap.connect(ep.host().toString(), ep.port());
375
376 f.addListener(future -> {
377 if (future.isSuccess()) {
378 retFuture.complete(f.channel());
379 } else {
380 retFuture.completeExceptionally(future.cause());
381 }
382 });
383 log.debug("Established a new connection to {}", ep);
384 return new Connection(retFuture);
385 }
386
387 @Override
388 public void passivateObject(Endpoint ep, Connection connection)
389 throws Exception {
390 }
391
392 @Override
393 public boolean validateObject(Endpoint ep, Connection connection) {
394 return connection.validate();
395 }
396 }
397
398 private class SslServerCommunicationChannelInitializer extends ChannelInitializer<SocketChannel> {
399
400 private final ChannelHandler dispatcher = new InboundMessageDispatcher();
401 private final ChannelHandler encoder = new MessageEncoder(preamble);
402
403 @Override
404 protected void initChannel(SocketChannel channel) throws Exception {
405 TrustManagerFactory tmFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
406 KeyStore ts = KeyStore.getInstance("JKS");
407 ts.load(new FileInputStream(tsLocation), tsPwd);
408 tmFactory.init(ts);
409
410 KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
411 KeyStore ks = KeyStore.getInstance("JKS");
412 ks.load(new FileInputStream(ksLocation), ksPwd);
413 kmf.init(ks, ksPwd);
414
415 SSLContext serverContext = SSLContext.getInstance("TLS");
416 serverContext.init(kmf.getKeyManagers(), tmFactory.getTrustManagers(), null);
417
418 SSLEngine serverSslEngine = serverContext.createSSLEngine();
419
420 serverSslEngine.setNeedClientAuth(true);
421 serverSslEngine.setUseClientMode(false);
422 serverSslEngine.setEnabledProtocols(serverSslEngine.getSupportedProtocols());
423 serverSslEngine.setEnabledCipherSuites(serverSslEngine.getSupportedCipherSuites());
424 serverSslEngine.setEnableSessionCreation(true);
425
426 channel.pipeline().addLast("ssl", new io.netty.handler.ssl.SslHandler(serverSslEngine))
427 .addLast("encoder", encoder)
428 .addLast("decoder", new MessageDecoder(preamble))
429 .addLast("handler", dispatcher);
430 }
431 }
432
433 private class SslClientCommunicationChannelInitializer extends ChannelInitializer<SocketChannel> {
434
435 private final ChannelHandler dispatcher = new InboundMessageDispatcher();
436 private final ChannelHandler encoder = new MessageEncoder(preamble);
437
438 @Override
439 protected void initChannel(SocketChannel channel) throws Exception {
440 TrustManagerFactory tmFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
441 KeyStore ts = KeyStore.getInstance("JKS");
442 ts.load(new FileInputStream(tsLocation), tsPwd);
443 tmFactory.init(ts);
444
445 KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
446 KeyStore ks = KeyStore.getInstance("JKS");
447 ks.load(new FileInputStream(ksLocation), ksPwd);
448 kmf.init(ks, ksPwd);
449
450 SSLContext clientContext = SSLContext.getInstance("TLS");
451 clientContext.init(kmf.getKeyManagers(), tmFactory.getTrustManagers(), null);
452
453 SSLEngine clientSslEngine = clientContext.createSSLEngine();
454
455 clientSslEngine.setUseClientMode(true);
456 clientSslEngine.setEnabledProtocols(clientSslEngine.getSupportedProtocols());
457 clientSslEngine.setEnabledCipherSuites(clientSslEngine.getSupportedCipherSuites());
458 clientSslEngine.setEnableSessionCreation(true);
459
460 channel.pipeline().addLast("ssl", new io.netty.handler.ssl.SslHandler(clientSslEngine))
461 .addLast("encoder", encoder)
462 .addLast("decoder", new MessageDecoder(preamble))
463 .addLast("handler", dispatcher);
464 }
465 }
466
467 private class OnosCommunicationChannelInitializer extends ChannelInitializer<SocketChannel> {
468
469 private final ChannelHandler dispatcher = new InboundMessageDispatcher();
470 private final ChannelHandler encoder = new MessageEncoder(preamble);
471
472 @Override
473 protected void initChannel(SocketChannel channel) throws Exception {
474 channel.pipeline()
475 .addLast("encoder", encoder)
476 .addLast("decoder", new MessageDecoder(preamble))
477 .addLast("handler", dispatcher);
478 }
479 }
480
481 @ChannelHandler.Sharable
482 private class InboundMessageDispatcher extends SimpleChannelInboundHandler<InternalMessage> {
483
484 @Override
485 protected void channelRead0(ChannelHandlerContext ctx, InternalMessage message) throws Exception {
486 try {
487 dispatchLocally(message);
488 } catch (RejectedExecutionException e) {
489 log.warn("Unable to dispatch message due to {}", e.getMessage());
490 }
491 }
492
493 @Override
494 public void exceptionCaught(ChannelHandlerContext context, Throwable cause) {
495 log.error("Exception inside channel handling pipeline.", cause);
496 context.close();
497 }
498 }
499 private void dispatchLocally(InternalMessage message) throws IOException {
500 String type = message.type();
501 if (REPLY_MESSAGE_TYPE.equals(type)) {
502 try {
503 Callback callback =
504 callbacks.getIfPresent(message.id());
505 if (callback != null) {
Madan Jampania9e70a62016-03-02 16:28:18 -0800506 if (message.status() == Status.OK) {
507 callback.complete(message.payload());
508 } else if (message.status() == Status.ERROR_NO_HANDLER) {
509 callback.completeExceptionally(new MessagingException.NoRemoteHandler());
510 } else if (message.status() == Status.ERROR_HANDLER_EXCEPTION) {
511 callback.completeExceptionally(new MessagingException.RemoteHandlerFailure());
512 }
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800513 } else {
Madan Jampania9e70a62016-03-02 16:28:18 -0800514 log.debug("Received a reply for message id:[{}]. "
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800515 + " from {}. But was unable to locate the"
516 + " request handle", message.id(), message.sender());
517 }
518 } finally {
519 callbacks.invalidate(message.id());
520 }
521 return;
522 }
523 Consumer<InternalMessage> handler = handlers.get(type);
524 if (handler != null) {
525 handler.accept(message);
526 } else {
Madan Jampania9e70a62016-03-02 16:28:18 -0800527 log.debug("No handler for message type {}", message.type(), message.sender());
528 sendReply(message, Status.ERROR_NO_HANDLER, Optional.empty());
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800529 }
530 }
531
Madan Jampania9e70a62016-03-02 16:28:18 -0800532 private void sendReply(InternalMessage message, Status status, Optional<byte[]> responsePayload) {
533 InternalMessage response = new InternalMessage(message.id(),
534 localEp,
535 REPLY_MESSAGE_TYPE,
536 responsePayload.orElse(new byte[0]),
537 status);
538 sendAsync(message.sender(), response).whenComplete((result, error) -> {
539 if (error != null) {
540 log.debug("Failed to respond", error);
541 }
542 });
543 }
544
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800545 private final class Callback {
546 private final CompletableFuture<byte[]> future;
547 private final Executor executor;
548
549 public Callback(CompletableFuture<byte[]> future, Executor executor) {
550 this.future = future;
551 this.executor = executor;
552 }
553
554 public void complete(byte[] value) {
555 executor.execute(() -> future.complete(value));
556 }
557
558 public void completeExceptionally(Throwable error) {
559 executor.execute(() -> future.completeExceptionally(error));
560 }
561 }
562 private final class Connection {
563 private final CompletableFuture<Channel> internalFuture;
564
565 public Connection(CompletableFuture<Channel> internalFuture) {
566 this.internalFuture = internalFuture;
567 }
568
569 /**
570 * Sends a message out on its channel and associated the message with a
571 * completable future used for signaling.
572 * @param message the message to be sent
573 * @param future a future that is completed normally or exceptionally if
574 * message sending succeeds or fails respectively
575 */
576 public void send(Object message, CompletableFuture<Void> future) {
577 internalFuture.whenComplete((channel, throwable) -> {
578 if (throwable == null) {
579 channel.writeAndFlush(message).addListener(channelFuture -> {
580 if (!channelFuture.isSuccess()) {
581 future.completeExceptionally(channelFuture.cause());
582 } else {
583 future.complete(null);
584 }
585 });
586 } else {
587 future.completeExceptionally(throwable);
588 }
589 });
590 }
591
592 /**
593 * Destroys a channel by closing its channel (if it exists) and
594 * cancelling its future.
595 */
596 public void destroy() {
597 Channel channel = internalFuture.getNow(null);
598 if (channel != null) {
599 channel.close();
600 }
601 internalFuture.cancel(false);
602 }
603
604 /**
605 * Determines whether the connection is valid meaning it is either
606 * complete with and active channel
607 * or it has not yet completed.
608 * @return true if the channel has an active connection or has not
609 * yet completed
610 */
611 public boolean validate() {
612 if (internalFuture.isCompletedExceptionally()) {
613 return false;
614 }
615 Channel channel = internalFuture.getNow(null);
616 return channel == null || channel.isActive();
617 }
618 }
JunHuy Lam39eb4292015-06-26 17:24:23 +0900619}