blob: 239b43b5f96317efb4e3f63a4ff1e313cef1e4c6 [file] [log] [blame]
Thomas Vachuska58de4162015-09-10 16:15:33 -07001/*
Brian O'Connor5ab426f2016-04-09 01:19:45 -07002 * Copyright 2015-present Open Networking Laboratory
Thomas Vachuska58de4162015-09-10 16:15:33 -07003 *
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;
Madan Jampani05833872016-07-12 23:01:39 -070056import org.onosproject.core.HybridLogicalClockService;
Madan Jampaniafeebbd2015-05-19 15:26:01 -070057import org.onosproject.store.cluster.messaging.Endpoint;
Madan Jampania9e70a62016-03-02 16:28:18 -080058import org.onosproject.store.cluster.messaging.MessagingException;
Aaron Kruglikov1b727382016-02-09 16:17:47 -080059import org.onosproject.store.cluster.messaging.MessagingService;
Madan Jampania9e70a62016-03-02 16:28:18 -080060import org.onosproject.store.cluster.messaging.impl.InternalMessage.Status;
Madan Jampaniafeebbd2015-05-19 15:26:01 -070061import org.slf4j.Logger;
62import org.slf4j.LoggerFactory;
63
Aaron Kruglikov1b727382016-02-09 16:17:47 -080064import javax.net.ssl.KeyManagerFactory;
65import javax.net.ssl.SSLContext;
66import javax.net.ssl.SSLEngine;
67import javax.net.ssl.TrustManagerFactory;
Madan Jampania9e70a62016-03-02 16:28:18 -080068
Aaron Kruglikov1b727382016-02-09 16:17:47 -080069import java.io.FileInputStream;
70import java.io.IOException;
71import java.security.KeyStore;
72import java.util.Map;
Madan Jampania9e70a62016-03-02 16:28:18 -080073import java.util.Optional;
Aaron Kruglikov1b727382016-02-09 16:17:47 -080074import java.util.concurrent.CompletableFuture;
75import java.util.concurrent.ConcurrentHashMap;
76import java.util.concurrent.Executor;
77import java.util.concurrent.RejectedExecutionException;
78import java.util.concurrent.TimeUnit;
79import java.util.concurrent.TimeoutException;
80import java.util.concurrent.atomic.AtomicBoolean;
81import java.util.concurrent.atomic.AtomicLong;
82import java.util.function.BiConsumer;
83import java.util.function.BiFunction;
84import java.util.function.Consumer;
85
Heedo Kang4a47a302016-02-29 17:40:23 +090086import static org.onosproject.security.AppGuard.checkPermission;
87import static org.onosproject.security.AppPermission.Type.CLUSTER_WRITE;
88
Madan Jampaniafeebbd2015-05-19 15:26:01 -070089/**
90 * Netty based MessagingService.
91 */
92@Component(immediate = true, enabled = true)
93@Service
Aaron Kruglikov1b727382016-02-09 16:17:47 -080094public class NettyMessagingManager implements MessagingService {
95
Madan Jampanif5c38a72016-02-17 18:26:15 -080096 private static final int REPLY_TIME_OUT_SEC = 2;
Aaron Kruglikov1b727382016-02-09 16:17:47 -080097 private static final short MIN_KS_LENGTH = 6;
Madan Jampaniafeebbd2015-05-19 15:26:01 -070098
99 private final Logger log = LoggerFactory.getLogger(getClass());
100
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800101 private static final String REPLY_MESSAGE_TYPE = "NETTY_MESSAGING_REQUEST_REPLY";
102
Madan Jampani05833872016-07-12 23:01:39 -0700103 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
104 protected HybridLogicalClockService clockService;
105
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800106 private Endpoint localEp;
107 private int preamble;
108 private final AtomicBoolean started = new AtomicBoolean(false);
109 private final Map<String, Consumer<InternalMessage>> handlers = new ConcurrentHashMap<>();
110 private final AtomicLong messageIdGenerator = new AtomicLong(0);
111 private final Cache<Long, Callback> callbacks = CacheBuilder.newBuilder()
Madan Jampanif5c38a72016-02-17 18:26:15 -0800112 .expireAfterWrite(REPLY_TIME_OUT_SEC, TimeUnit.SECONDS)
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800113 .removalListener(new RemovalListener<Long, Callback>() {
114 @Override
115 public void onRemoval(RemovalNotification<Long, Callback> entry) {
116 if (entry.wasEvicted()) {
117 entry.getValue().completeExceptionally(new TimeoutException("Timedout waiting for reply"));
118 }
119 }
120 })
121 .build();
122
123 private final GenericKeyedObjectPool<Endpoint, Connection> channels
124 = new GenericKeyedObjectPool<Endpoint, Connection>(new OnosCommunicationChannelFactory());
125
126 private EventLoopGroup serverGroup;
127 private EventLoopGroup clientGroup;
128 private Class<? extends ServerChannel> serverChannelClass;
129 private Class<? extends Channel> clientChannelClass;
130
131 protected static final boolean TLS_DISABLED = false;
132 protected boolean enableNettyTls = TLS_DISABLED;
133
134 protected String ksLocation;
135 protected String tsLocation;
136 protected char[] ksPwd;
137 protected char[] tsPwd;
JunHuy Lam39eb4292015-06-26 17:24:23 +0900138
Madan Jampaniafeebbd2015-05-19 15:26:01 -0700139 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Madan Jampaniec1df022015-10-13 21:23:03 -0700140 protected ClusterMetadataService clusterMetadataService;
Madan Jampaniafeebbd2015-05-19 15:26:01 -0700141
142 @Activate
143 public void activate() throws Exception {
Madan Jampaniec1df022015-10-13 21:23:03 -0700144 ControllerNode localNode = clusterMetadataService.getLocalNode();
Jonathan Hartd9df7bd2015-11-10 17:10:25 -0800145 getTlsParameters();
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800146
147 if (started.get()) {
148 log.warn("Already running at local endpoint: {}", localEp);
149 return;
150 }
151 this.preamble = clusterMetadataService.getClusterMetadata().getName().hashCode();
152 this.localEp = new Endpoint(localNode.ip(), localNode.tcpPort());
153 channels.setLifo(true);
154 channels.setTestOnBorrow(true);
155 channels.setTestOnReturn(true);
156 channels.setMinEvictableIdleTimeMillis(60_000L);
157 channels.setTimeBetweenEvictionRunsMillis(30_000L);
158 initEventLoopGroup();
159 startAcceptingConnections();
160 started.set(true);
Madan Jampanif5c38a72016-02-17 18:26:15 -0800161 serverGroup.scheduleWithFixedDelay(callbacks::cleanUp, 0, REPLY_TIME_OUT_SEC, TimeUnit.SECONDS);
Madan Jampaniafeebbd2015-05-19 15:26:01 -0700162 log.info("Started");
163 }
164
165 @Deactivate
166 public void deactivate() throws Exception {
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800167 if (started.get()) {
168 channels.close();
169 serverGroup.shutdownGracefully();
170 clientGroup.shutdownGracefully();
171 started.set(false);
172 }
Madan Jampaniafeebbd2015-05-19 15:26:01 -0700173 log.info("Stopped");
174 }
JunHuy Lam39eb4292015-06-26 17:24:23 +0900175
Jonathan Hartd9df7bd2015-11-10 17:10:25 -0800176 private void getTlsParameters() {
JunHuy Lam39eb4292015-06-26 17:24:23 +0900177 String tempString = System.getProperty("enableNettyTLS");
Jonathan Hartd9df7bd2015-11-10 17:10:25 -0800178 enableNettyTls = Strings.isNullOrEmpty(tempString) ? TLS_DISABLED : Boolean.parseBoolean(tempString);
179 log.info("enableNettyTLS = {}", enableNettyTls);
180 if (enableNettyTls) {
JunHuy Lam39eb4292015-06-26 17:24:23 +0900181 ksLocation = System.getProperty("javax.net.ssl.keyStore");
182 if (Strings.isNullOrEmpty(ksLocation)) {
Jonathan Hartd9df7bd2015-11-10 17:10:25 -0800183 enableNettyTls = TLS_DISABLED;
JunHuy Lam39eb4292015-06-26 17:24:23 +0900184 return;
185 }
186 tsLocation = System.getProperty("javax.net.ssl.trustStore");
187 if (Strings.isNullOrEmpty(tsLocation)) {
Jonathan Hartd9df7bd2015-11-10 17:10:25 -0800188 enableNettyTls = TLS_DISABLED;
JunHuy Lam39eb4292015-06-26 17:24:23 +0900189 return;
190 }
191 ksPwd = System.getProperty("javax.net.ssl.keyStorePassword").toCharArray();
192 if (MIN_KS_LENGTH > ksPwd.length) {
Jonathan Hartd9df7bd2015-11-10 17:10:25 -0800193 enableNettyTls = TLS_DISABLED;
JunHuy Lam39eb4292015-06-26 17:24:23 +0900194 return;
195 }
196 tsPwd = System.getProperty("javax.net.ssl.trustStorePassword").toCharArray();
197 if (MIN_KS_LENGTH > tsPwd.length) {
Jonathan Hartd9df7bd2015-11-10 17:10:25 -0800198 enableNettyTls = TLS_DISABLED;
JunHuy Lam39eb4292015-06-26 17:24:23 +0900199 return;
200 }
201 }
202 }
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800203 private void initEventLoopGroup() {
204 // try Epoll first and if that does work, use nio.
205 try {
206 clientGroup = new EpollEventLoopGroup();
207 serverGroup = new EpollEventLoopGroup();
208 serverChannelClass = EpollServerSocketChannel.class;
209 clientChannelClass = EpollSocketChannel.class;
210 return;
211 } catch (Throwable e) {
212 log.debug("Failed to initialize native (epoll) transport. "
213 + "Reason: {}. Proceeding with nio.", e.getMessage());
214 }
215 clientGroup = new NioEventLoopGroup();
216 serverGroup = new NioEventLoopGroup();
217 serverChannelClass = NioServerSocketChannel.class;
218 clientChannelClass = NioSocketChannel.class;
219 }
220
221 @Override
222 public CompletableFuture<Void> sendAsync(Endpoint ep, String type, byte[] payload) {
Heedo Kang4a47a302016-02-29 17:40:23 +0900223 checkPermission(CLUSTER_WRITE);
Madan Jampanib825aeb2016-04-01 15:18:25 -0700224 InternalMessage message = new InternalMessage(preamble,
Madan Jampani05833872016-07-12 23:01:39 -0700225 clockService.timeNow(),
Madan Jampanib825aeb2016-04-01 15:18:25 -0700226 messageIdGenerator.incrementAndGet(),
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800227 localEp,
228 type,
229 payload);
230 return sendAsync(ep, message);
231 }
232
233 protected CompletableFuture<Void> sendAsync(Endpoint ep, InternalMessage message) {
Heedo Kang4a47a302016-02-29 17:40:23 +0900234 checkPermission(CLUSTER_WRITE);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800235 if (ep.equals(localEp)) {
236 try {
237 dispatchLocally(message);
238 } catch (IOException e) {
239 return Tools.exceptionalFuture(e);
240 }
241 return CompletableFuture.completedFuture(null);
242 }
243
244 CompletableFuture<Void> future = new CompletableFuture<>();
245 try {
246 Connection connection = null;
247 try {
248 connection = channels.borrowObject(ep);
249 connection.send(message, future);
250 } finally {
251 channels.returnObject(ep, connection);
252 }
253 } catch (Exception e) {
254 future.completeExceptionally(e);
255 }
256 return future;
257 }
258
259 @Override
260 public CompletableFuture<byte[]> sendAndReceive(Endpoint ep, String type, byte[] payload) {
Heedo Kang4a47a302016-02-29 17:40:23 +0900261 checkPermission(CLUSTER_WRITE);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800262 return sendAndReceive(ep, type, payload, MoreExecutors.directExecutor());
263 }
264
265 @Override
266 public CompletableFuture<byte[]> sendAndReceive(Endpoint ep, String type, byte[] payload, Executor executor) {
Heedo Kang4a47a302016-02-29 17:40:23 +0900267 checkPermission(CLUSTER_WRITE);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800268 CompletableFuture<byte[]> response = new CompletableFuture<>();
269 Callback callback = new Callback(response, executor);
270 Long messageId = messageIdGenerator.incrementAndGet();
271 callbacks.put(messageId, callback);
Madan Jampani05833872016-07-12 23:01:39 -0700272 InternalMessage message = new InternalMessage(preamble,
273 clockService.timeNow(),
274 messageId,
275 localEp,
276 type,
277 payload);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800278 return sendAsync(ep, message).whenComplete((r, e) -> {
279 if (e != null) {
280 callbacks.invalidate(messageId);
281 }
282 }).thenCompose(v -> response);
283 }
284
285 @Override
286 public void registerHandler(String type, BiConsumer<Endpoint, byte[]> handler, Executor executor) {
Heedo Kang4a47a302016-02-29 17:40:23 +0900287 checkPermission(CLUSTER_WRITE);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800288 handlers.put(type, message -> executor.execute(() -> handler.accept(message.sender(), message.payload())));
289 }
290
291 @Override
292 public void registerHandler(String type, BiFunction<Endpoint, byte[], byte[]> handler, Executor executor) {
Heedo Kang4a47a302016-02-29 17:40:23 +0900293 checkPermission(CLUSTER_WRITE);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800294 handlers.put(type, message -> executor.execute(() -> {
Madan Jampania9e70a62016-03-02 16:28:18 -0800295 byte[] responsePayload = null;
296 Status status = Status.OK;
297 try {
298 responsePayload = handler.apply(message.sender(), message.payload());
299 } catch (Exception e) {
300 status = Status.ERROR_HANDLER_EXCEPTION;
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800301 }
Madan Jampania9e70a62016-03-02 16:28:18 -0800302 sendReply(message, status, Optional.ofNullable(responsePayload));
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800303 }));
304 }
305
306 @Override
307 public void registerHandler(String type, BiFunction<Endpoint, byte[], CompletableFuture<byte[]>> handler) {
Heedo Kang4a47a302016-02-29 17:40:23 +0900308 checkPermission(CLUSTER_WRITE);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800309 handlers.put(type, message -> {
310 handler.apply(message.sender(), message.payload()).whenComplete((result, error) -> {
Madan Jampania9e70a62016-03-02 16:28:18 -0800311 Status status = error == null ? Status.OK : Status.ERROR_HANDLER_EXCEPTION;
312 sendReply(message, status, Optional.ofNullable(result));
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800313 });
314 });
315 }
316
317 @Override
318 public void unregisterHandler(String type) {
Heedo Kang4a47a302016-02-29 17:40:23 +0900319 checkPermission(CLUSTER_WRITE);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800320 handlers.remove(type);
321 }
322
323 private void startAcceptingConnections() throws InterruptedException {
324 ServerBootstrap b = new ServerBootstrap();
325 b.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 32 * 1024);
326 b.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024);
327 b.option(ChannelOption.SO_RCVBUF, 1048576);
328 b.option(ChannelOption.TCP_NODELAY, true);
329 b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
330 b.group(serverGroup, clientGroup);
331 b.channel(serverChannelClass);
332 if (enableNettyTls) {
333 b.childHandler(new SslServerCommunicationChannelInitializer());
334 } else {
335 b.childHandler(new OnosCommunicationChannelInitializer());
336 }
337 b.option(ChannelOption.SO_BACKLOG, 128);
338 b.childOption(ChannelOption.SO_KEEPALIVE, true);
339
340 // Bind and start to accept incoming connections.
341 b.bind(localEp.port()).sync().addListener(future -> {
342 if (future.isSuccess()) {
343 log.info("{} accepting incoming connections on port {}", localEp.host(), localEp.port());
344 } else {
345 log.warn("{} failed to bind to port {}", localEp.host(), localEp.port(), future.cause());
346 }
347 });
348 }
349
350 private class OnosCommunicationChannelFactory
351 implements KeyedPoolableObjectFactory<Endpoint, Connection> {
352
353 @Override
354 public void activateObject(Endpoint endpoint, Connection connection)
355 throws Exception {
356 }
357
358 @Override
359 public void destroyObject(Endpoint ep, Connection connection) throws Exception {
360 log.debug("Closing connection to {}", ep);
361 //Is this the right way to destroy?
362 connection.destroy();
363 }
364
365 @Override
366 public Connection makeObject(Endpoint ep) throws Exception {
367 Bootstrap bootstrap = new Bootstrap();
368 bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
369 bootstrap.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 10 * 64 * 1024);
370 bootstrap.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 10 * 32 * 1024);
371 bootstrap.option(ChannelOption.SO_SNDBUF, 1048576);
372 bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000);
373 bootstrap.group(clientGroup);
374 // TODO: Make this faster:
375 // http://normanmaurer.me/presentations/2014-facebook-eng-netty/slides.html#37.0
376 bootstrap.channel(clientChannelClass);
377 bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
378 if (enableNettyTls) {
379 bootstrap.handler(new SslClientCommunicationChannelInitializer());
380 } else {
381 bootstrap.handler(new OnosCommunicationChannelInitializer());
382 }
383 // Start the client.
384 CompletableFuture<Channel> retFuture = new CompletableFuture<>();
385 ChannelFuture f = bootstrap.connect(ep.host().toString(), ep.port());
386
387 f.addListener(future -> {
388 if (future.isSuccess()) {
389 retFuture.complete(f.channel());
390 } else {
391 retFuture.completeExceptionally(future.cause());
392 }
393 });
394 log.debug("Established a new connection to {}", ep);
395 return new Connection(retFuture);
396 }
397
398 @Override
399 public void passivateObject(Endpoint ep, Connection connection)
400 throws Exception {
401 }
402
403 @Override
404 public boolean validateObject(Endpoint ep, Connection connection) {
405 return connection.validate();
406 }
407 }
408
409 private class SslServerCommunicationChannelInitializer extends ChannelInitializer<SocketChannel> {
410
411 private final ChannelHandler dispatcher = new InboundMessageDispatcher();
412 private final ChannelHandler encoder = new MessageEncoder(preamble);
413
414 @Override
415 protected void initChannel(SocketChannel channel) throws Exception {
416 TrustManagerFactory tmFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
417 KeyStore ts = KeyStore.getInstance("JKS");
418 ts.load(new FileInputStream(tsLocation), tsPwd);
419 tmFactory.init(ts);
420
421 KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
422 KeyStore ks = KeyStore.getInstance("JKS");
423 ks.load(new FileInputStream(ksLocation), ksPwd);
424 kmf.init(ks, ksPwd);
425
426 SSLContext serverContext = SSLContext.getInstance("TLS");
427 serverContext.init(kmf.getKeyManagers(), tmFactory.getTrustManagers(), null);
428
429 SSLEngine serverSslEngine = serverContext.createSSLEngine();
430
431 serverSslEngine.setNeedClientAuth(true);
432 serverSslEngine.setUseClientMode(false);
433 serverSslEngine.setEnabledProtocols(serverSslEngine.getSupportedProtocols());
434 serverSslEngine.setEnabledCipherSuites(serverSslEngine.getSupportedCipherSuites());
435 serverSslEngine.setEnableSessionCreation(true);
436
437 channel.pipeline().addLast("ssl", new io.netty.handler.ssl.SslHandler(serverSslEngine))
438 .addLast("encoder", encoder)
Madan Jampanib825aeb2016-04-01 15:18:25 -0700439 .addLast("decoder", new MessageDecoder())
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800440 .addLast("handler", dispatcher);
441 }
442 }
443
444 private class SslClientCommunicationChannelInitializer extends ChannelInitializer<SocketChannel> {
445
446 private final ChannelHandler dispatcher = new InboundMessageDispatcher();
447 private final ChannelHandler encoder = new MessageEncoder(preamble);
448
449 @Override
450 protected void initChannel(SocketChannel channel) throws Exception {
451 TrustManagerFactory tmFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
452 KeyStore ts = KeyStore.getInstance("JKS");
453 ts.load(new FileInputStream(tsLocation), tsPwd);
454 tmFactory.init(ts);
455
456 KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
457 KeyStore ks = KeyStore.getInstance("JKS");
458 ks.load(new FileInputStream(ksLocation), ksPwd);
459 kmf.init(ks, ksPwd);
460
461 SSLContext clientContext = SSLContext.getInstance("TLS");
462 clientContext.init(kmf.getKeyManagers(), tmFactory.getTrustManagers(), null);
463
464 SSLEngine clientSslEngine = clientContext.createSSLEngine();
465
466 clientSslEngine.setUseClientMode(true);
467 clientSslEngine.setEnabledProtocols(clientSslEngine.getSupportedProtocols());
468 clientSslEngine.setEnabledCipherSuites(clientSslEngine.getSupportedCipherSuites());
469 clientSslEngine.setEnableSessionCreation(true);
470
471 channel.pipeline().addLast("ssl", new io.netty.handler.ssl.SslHandler(clientSslEngine))
472 .addLast("encoder", encoder)
Madan Jampanib825aeb2016-04-01 15:18:25 -0700473 .addLast("decoder", new MessageDecoder())
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800474 .addLast("handler", dispatcher);
475 }
476 }
477
478 private class OnosCommunicationChannelInitializer extends ChannelInitializer<SocketChannel> {
479
480 private final ChannelHandler dispatcher = new InboundMessageDispatcher();
481 private final ChannelHandler encoder = new MessageEncoder(preamble);
482
483 @Override
484 protected void initChannel(SocketChannel channel) throws Exception {
485 channel.pipeline()
486 .addLast("encoder", encoder)
Madan Jampanib825aeb2016-04-01 15:18:25 -0700487 .addLast("decoder", new MessageDecoder())
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800488 .addLast("handler", dispatcher);
489 }
490 }
491
492 @ChannelHandler.Sharable
493 private class InboundMessageDispatcher extends SimpleChannelInboundHandler<InternalMessage> {
494
495 @Override
496 protected void channelRead0(ChannelHandlerContext ctx, InternalMessage message) throws Exception {
497 try {
498 dispatchLocally(message);
499 } catch (RejectedExecutionException e) {
500 log.warn("Unable to dispatch message due to {}", e.getMessage());
501 }
502 }
503
504 @Override
505 public void exceptionCaught(ChannelHandlerContext context, Throwable cause) {
506 log.error("Exception inside channel handling pipeline.", cause);
507 context.close();
508 }
509 }
510 private void dispatchLocally(InternalMessage message) throws IOException {
Madan Jampanib825aeb2016-04-01 15:18:25 -0700511 if (message.preamble() != preamble) {
512 log.debug("Received {} with invalid preamble from {}", message.type(), message.sender());
513 sendReply(message, Status.PROTOCOL_EXCEPTION, Optional.empty());
514 }
Madan Jampani05833872016-07-12 23:01:39 -0700515 clockService.recordEventTime(message.time());
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800516 String type = message.type();
517 if (REPLY_MESSAGE_TYPE.equals(type)) {
518 try {
519 Callback callback =
520 callbacks.getIfPresent(message.id());
521 if (callback != null) {
Madan Jampania9e70a62016-03-02 16:28:18 -0800522 if (message.status() == Status.OK) {
523 callback.complete(message.payload());
524 } else if (message.status() == Status.ERROR_NO_HANDLER) {
525 callback.completeExceptionally(new MessagingException.NoRemoteHandler());
526 } else if (message.status() == Status.ERROR_HANDLER_EXCEPTION) {
527 callback.completeExceptionally(new MessagingException.RemoteHandlerFailure());
Madan Jampanib825aeb2016-04-01 15:18:25 -0700528 } else if (message.status() == Status.PROTOCOL_EXCEPTION) {
529 callback.completeExceptionally(new MessagingException.ProcotolException());
Madan Jampania9e70a62016-03-02 16:28:18 -0800530 }
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800531 } else {
Madan Jampania9e70a62016-03-02 16:28:18 -0800532 log.debug("Received a reply for message id:[{}]. "
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800533 + " from {}. But was unable to locate the"
534 + " request handle", message.id(), message.sender());
535 }
536 } finally {
537 callbacks.invalidate(message.id());
538 }
539 return;
540 }
541 Consumer<InternalMessage> handler = handlers.get(type);
542 if (handler != null) {
543 handler.accept(message);
544 } else {
Madan Jampania9e70a62016-03-02 16:28:18 -0800545 log.debug("No handler for message type {}", message.type(), message.sender());
546 sendReply(message, Status.ERROR_NO_HANDLER, Optional.empty());
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800547 }
548 }
549
Madan Jampania9e70a62016-03-02 16:28:18 -0800550 private void sendReply(InternalMessage message, Status status, Optional<byte[]> responsePayload) {
Madan Jampanib825aeb2016-04-01 15:18:25 -0700551 InternalMessage response = new InternalMessage(preamble,
Madan Jampani05833872016-07-12 23:01:39 -0700552 clockService.timeNow(),
Madan Jampanib825aeb2016-04-01 15:18:25 -0700553 message.id(),
Madan Jampania9e70a62016-03-02 16:28:18 -0800554 localEp,
555 REPLY_MESSAGE_TYPE,
556 responsePayload.orElse(new byte[0]),
557 status);
558 sendAsync(message.sender(), response).whenComplete((result, error) -> {
559 if (error != null) {
560 log.debug("Failed to respond", error);
561 }
562 });
563 }
564
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800565 private final class Callback {
566 private final CompletableFuture<byte[]> future;
567 private final Executor executor;
568
569 public Callback(CompletableFuture<byte[]> future, Executor executor) {
570 this.future = future;
571 this.executor = executor;
572 }
573
574 public void complete(byte[] value) {
575 executor.execute(() -> future.complete(value));
576 }
577
578 public void completeExceptionally(Throwable error) {
579 executor.execute(() -> future.completeExceptionally(error));
580 }
581 }
582 private final class Connection {
583 private final CompletableFuture<Channel> internalFuture;
584
585 public Connection(CompletableFuture<Channel> internalFuture) {
586 this.internalFuture = internalFuture;
587 }
588
589 /**
590 * Sends a message out on its channel and associated the message with a
591 * completable future used for signaling.
592 * @param message the message to be sent
593 * @param future a future that is completed normally or exceptionally if
594 * message sending succeeds or fails respectively
595 */
596 public void send(Object message, CompletableFuture<Void> future) {
597 internalFuture.whenComplete((channel, throwable) -> {
598 if (throwable == null) {
599 channel.writeAndFlush(message).addListener(channelFuture -> {
600 if (!channelFuture.isSuccess()) {
601 future.completeExceptionally(channelFuture.cause());
602 } else {
603 future.complete(null);
604 }
605 });
606 } else {
607 future.completeExceptionally(throwable);
608 }
609 });
610 }
611
612 /**
613 * Destroys a channel by closing its channel (if it exists) and
614 * cancelling its future.
615 */
616 public void destroy() {
617 Channel channel = internalFuture.getNow(null);
618 if (channel != null) {
619 channel.close();
620 }
621 internalFuture.cancel(false);
622 }
623
624 /**
625 * Determines whether the connection is valid meaning it is either
626 * complete with and active channel
627 * or it has not yet completed.
628 * @return true if the channel has an active connection or has not
629 * yet completed
630 */
631 public boolean validate() {
632 if (internalFuture.isCompletedExceptionally()) {
633 return false;
634 }
635 Channel channel = internalFuture.getNow(null);
636 return channel == null || channel.isActive();
637 }
638 }
JunHuy Lam39eb4292015-06-26 17:24:23 +0900639}