blob: 52a264e28e5b092fb3318af222bad82ac38dc026 [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
Yuta HIGUCHI90a16892016-07-20 20:36:08 -070086import static org.onlab.util.Tools.groupedThreads;
Heedo Kang4a47a302016-02-29 17:40:23 +090087import static org.onosproject.security.AppGuard.checkPermission;
88import static org.onosproject.security.AppPermission.Type.CLUSTER_WRITE;
89
Madan Jampaniafeebbd2015-05-19 15:26:01 -070090/**
91 * Netty based MessagingService.
92 */
Sho SHIMIZU5c396e32016-08-12 15:19:12 -070093@Component(immediate = true)
Madan Jampaniafeebbd2015-05-19 15:26:01 -070094@Service
Aaron Kruglikov1b727382016-02-09 16:17:47 -080095public class NettyMessagingManager implements MessagingService {
96
Madan Jampanif3ab4242016-07-27 17:21:47 -070097 private static final int REPLY_TIME_OUT_MILLIS = 250;
Aaron Kruglikov1b727382016-02-09 16:17:47 -080098 private static final short MIN_KS_LENGTH = 6;
Madan Jampaniafeebbd2015-05-19 15:26:01 -070099
100 private final Logger log = LoggerFactory.getLogger(getClass());
101
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800102 private static final String REPLY_MESSAGE_TYPE = "NETTY_MESSAGING_REQUEST_REPLY";
103
Madan Jampani05833872016-07-12 23:01:39 -0700104 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
105 protected HybridLogicalClockService clockService;
106
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800107 private Endpoint localEp;
108 private int preamble;
109 private final AtomicBoolean started = new AtomicBoolean(false);
110 private final Map<String, Consumer<InternalMessage>> handlers = new ConcurrentHashMap<>();
111 private final AtomicLong messageIdGenerator = new AtomicLong(0);
112 private final Cache<Long, Callback> callbacks = CacheBuilder.newBuilder()
Madan Jampanif3ab4242016-07-27 17:21:47 -0700113 .expireAfterWrite(REPLY_TIME_OUT_MILLIS, TimeUnit.MILLISECONDS)
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800114 .removalListener(new RemovalListener<Long, Callback>() {
115 @Override
116 public void onRemoval(RemovalNotification<Long, Callback> entry) {
117 if (entry.wasEvicted()) {
118 entry.getValue().completeExceptionally(new TimeoutException("Timedout waiting for reply"));
119 }
120 }
121 })
122 .build();
123
124 private final GenericKeyedObjectPool<Endpoint, Connection> channels
Yuta HIGUCHI90a16892016-07-20 20:36:08 -0700125 = new GenericKeyedObjectPool<>(new OnosCommunicationChannelFactory());
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800126
127 private EventLoopGroup serverGroup;
128 private EventLoopGroup clientGroup;
129 private Class<? extends ServerChannel> serverChannelClass;
130 private Class<? extends Channel> clientChannelClass;
131
132 protected static final boolean TLS_DISABLED = false;
133 protected boolean enableNettyTls = TLS_DISABLED;
134
135 protected String ksLocation;
136 protected String tsLocation;
137 protected char[] ksPwd;
138 protected char[] tsPwd;
JunHuy Lam39eb4292015-06-26 17:24:23 +0900139
Madan Jampaniafeebbd2015-05-19 15:26:01 -0700140 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Madan Jampaniec1df022015-10-13 21:23:03 -0700141 protected ClusterMetadataService clusterMetadataService;
Madan Jampaniafeebbd2015-05-19 15:26:01 -0700142
143 @Activate
144 public void activate() throws Exception {
Madan Jampaniec1df022015-10-13 21:23:03 -0700145 ControllerNode localNode = clusterMetadataService.getLocalNode();
Jonathan Hartd9df7bd2015-11-10 17:10:25 -0800146 getTlsParameters();
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800147
148 if (started.get()) {
149 log.warn("Already running at local endpoint: {}", localEp);
150 return;
151 }
152 this.preamble = clusterMetadataService.getClusterMetadata().getName().hashCode();
153 this.localEp = new Endpoint(localNode.ip(), localNode.tcpPort());
154 channels.setLifo(true);
155 channels.setTestOnBorrow(true);
156 channels.setTestOnReturn(true);
157 channels.setMinEvictableIdleTimeMillis(60_000L);
158 channels.setTimeBetweenEvictionRunsMillis(30_000L);
159 initEventLoopGroup();
160 startAcceptingConnections();
161 started.set(true);
Madan Jampanif3ab4242016-07-27 17:21:47 -0700162 serverGroup.scheduleWithFixedDelay(callbacks::cleanUp, 0, REPLY_TIME_OUT_MILLIS, TimeUnit.MILLISECONDS);
Madan Jampaniafeebbd2015-05-19 15:26:01 -0700163 log.info("Started");
164 }
165
166 @Deactivate
167 public void deactivate() throws Exception {
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800168 if (started.get()) {
169 channels.close();
170 serverGroup.shutdownGracefully();
171 clientGroup.shutdownGracefully();
172 started.set(false);
173 }
Madan Jampaniafeebbd2015-05-19 15:26:01 -0700174 log.info("Stopped");
175 }
JunHuy Lam39eb4292015-06-26 17:24:23 +0900176
Jonathan Hartd9df7bd2015-11-10 17:10:25 -0800177 private void getTlsParameters() {
JunHuy Lam39eb4292015-06-26 17:24:23 +0900178 String tempString = System.getProperty("enableNettyTLS");
Jonathan Hartd9df7bd2015-11-10 17:10:25 -0800179 enableNettyTls = Strings.isNullOrEmpty(tempString) ? TLS_DISABLED : Boolean.parseBoolean(tempString);
180 log.info("enableNettyTLS = {}", enableNettyTls);
181 if (enableNettyTls) {
JunHuy Lam39eb4292015-06-26 17:24:23 +0900182 ksLocation = System.getProperty("javax.net.ssl.keyStore");
183 if (Strings.isNullOrEmpty(ksLocation)) {
Jonathan Hartd9df7bd2015-11-10 17:10:25 -0800184 enableNettyTls = TLS_DISABLED;
JunHuy Lam39eb4292015-06-26 17:24:23 +0900185 return;
186 }
187 tsLocation = System.getProperty("javax.net.ssl.trustStore");
188 if (Strings.isNullOrEmpty(tsLocation)) {
Jonathan Hartd9df7bd2015-11-10 17:10:25 -0800189 enableNettyTls = TLS_DISABLED;
JunHuy Lam39eb4292015-06-26 17:24:23 +0900190 return;
191 }
192 ksPwd = System.getProperty("javax.net.ssl.keyStorePassword").toCharArray();
193 if (MIN_KS_LENGTH > ksPwd.length) {
Jonathan Hartd9df7bd2015-11-10 17:10:25 -0800194 enableNettyTls = TLS_DISABLED;
JunHuy Lam39eb4292015-06-26 17:24:23 +0900195 return;
196 }
197 tsPwd = System.getProperty("javax.net.ssl.trustStorePassword").toCharArray();
198 if (MIN_KS_LENGTH > tsPwd.length) {
Jonathan Hartd9df7bd2015-11-10 17:10:25 -0800199 enableNettyTls = TLS_DISABLED;
JunHuy Lam39eb4292015-06-26 17:24:23 +0900200 return;
201 }
202 }
203 }
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800204 private void initEventLoopGroup() {
205 // try Epoll first and if that does work, use nio.
206 try {
Yuta HIGUCHI90a16892016-07-20 20:36:08 -0700207 clientGroup = new EpollEventLoopGroup(0, groupedThreads("NettyMessagingEvt", "epollC-%d", log));
208 serverGroup = new EpollEventLoopGroup(0, groupedThreads("NettyMessagingEvt", "epollS-%d", log));
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800209 serverChannelClass = EpollServerSocketChannel.class;
210 clientChannelClass = EpollSocketChannel.class;
211 return;
212 } catch (Throwable e) {
213 log.debug("Failed to initialize native (epoll) transport. "
214 + "Reason: {}. Proceeding with nio.", e.getMessage());
215 }
Yuta HIGUCHI90a16892016-07-20 20:36:08 -0700216 clientGroup = new NioEventLoopGroup(0, groupedThreads("NettyMessagingEvt", "nioC-%d", log));
217 serverGroup = new NioEventLoopGroup(0, groupedThreads("NettyMessagingEvt", "nioS-%d", log));
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800218 serverChannelClass = NioServerSocketChannel.class;
219 clientChannelClass = NioSocketChannel.class;
220 }
221
222 @Override
223 public CompletableFuture<Void> sendAsync(Endpoint ep, String type, byte[] payload) {
Heedo Kang4a47a302016-02-29 17:40:23 +0900224 checkPermission(CLUSTER_WRITE);
Madan Jampanib825aeb2016-04-01 15:18:25 -0700225 InternalMessage message = new InternalMessage(preamble,
Madan Jampani05833872016-07-12 23:01:39 -0700226 clockService.timeNow(),
Madan Jampanib825aeb2016-04-01 15:18:25 -0700227 messageIdGenerator.incrementAndGet(),
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800228 localEp,
229 type,
230 payload);
231 return sendAsync(ep, message);
232 }
233
234 protected CompletableFuture<Void> sendAsync(Endpoint ep, InternalMessage message) {
Heedo Kang4a47a302016-02-29 17:40:23 +0900235 checkPermission(CLUSTER_WRITE);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800236 if (ep.equals(localEp)) {
237 try {
238 dispatchLocally(message);
239 } catch (IOException e) {
240 return Tools.exceptionalFuture(e);
241 }
242 return CompletableFuture.completedFuture(null);
243 }
244
245 CompletableFuture<Void> future = new CompletableFuture<>();
246 try {
247 Connection connection = null;
248 try {
249 connection = channels.borrowObject(ep);
250 connection.send(message, future);
251 } finally {
252 channels.returnObject(ep, connection);
253 }
254 } catch (Exception e) {
255 future.completeExceptionally(e);
256 }
257 return future;
258 }
259
260 @Override
261 public CompletableFuture<byte[]> sendAndReceive(Endpoint ep, String type, byte[] payload) {
Heedo Kang4a47a302016-02-29 17:40:23 +0900262 checkPermission(CLUSTER_WRITE);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800263 return sendAndReceive(ep, type, payload, MoreExecutors.directExecutor());
264 }
265
266 @Override
267 public CompletableFuture<byte[]> sendAndReceive(Endpoint ep, String type, byte[] payload, Executor executor) {
Heedo Kang4a47a302016-02-29 17:40:23 +0900268 checkPermission(CLUSTER_WRITE);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800269 CompletableFuture<byte[]> response = new CompletableFuture<>();
270 Callback callback = new Callback(response, executor);
271 Long messageId = messageIdGenerator.incrementAndGet();
272 callbacks.put(messageId, callback);
Madan Jampani05833872016-07-12 23:01:39 -0700273 InternalMessage message = new InternalMessage(preamble,
274 clockService.timeNow(),
275 messageId,
276 localEp,
277 type,
278 payload);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800279 return sendAsync(ep, message).whenComplete((r, e) -> {
280 if (e != null) {
281 callbacks.invalidate(messageId);
282 }
Yuta HIGUCHIed1ca662016-08-11 11:11:37 -0700283 }).thenComposeAsync(v -> response, executor);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800284 }
285
286 @Override
287 public void registerHandler(String type, BiConsumer<Endpoint, byte[]> handler, Executor executor) {
Heedo Kang4a47a302016-02-29 17:40:23 +0900288 checkPermission(CLUSTER_WRITE);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800289 handlers.put(type, message -> executor.execute(() -> handler.accept(message.sender(), message.payload())));
290 }
291
292 @Override
293 public void registerHandler(String type, BiFunction<Endpoint, byte[], byte[]> handler, Executor executor) {
Heedo Kang4a47a302016-02-29 17:40:23 +0900294 checkPermission(CLUSTER_WRITE);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800295 handlers.put(type, message -> executor.execute(() -> {
Madan Jampania9e70a62016-03-02 16:28:18 -0800296 byte[] responsePayload = null;
297 Status status = Status.OK;
298 try {
299 responsePayload = handler.apply(message.sender(), message.payload());
300 } catch (Exception e) {
301 status = Status.ERROR_HANDLER_EXCEPTION;
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800302 }
Madan Jampania9e70a62016-03-02 16:28:18 -0800303 sendReply(message, status, Optional.ofNullable(responsePayload));
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800304 }));
305 }
306
307 @Override
308 public void registerHandler(String type, BiFunction<Endpoint, byte[], CompletableFuture<byte[]>> handler) {
Heedo Kang4a47a302016-02-29 17:40:23 +0900309 checkPermission(CLUSTER_WRITE);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800310 handlers.put(type, message -> {
311 handler.apply(message.sender(), message.payload()).whenComplete((result, error) -> {
Madan Jampania9e70a62016-03-02 16:28:18 -0800312 Status status = error == null ? Status.OK : Status.ERROR_HANDLER_EXCEPTION;
313 sendReply(message, status, Optional.ofNullable(result));
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800314 });
315 });
316 }
317
318 @Override
319 public void unregisterHandler(String type) {
Heedo Kang4a47a302016-02-29 17:40:23 +0900320 checkPermission(CLUSTER_WRITE);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800321 handlers.remove(type);
322 }
323
324 private void startAcceptingConnections() throws InterruptedException {
325 ServerBootstrap b = new ServerBootstrap();
326 b.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 32 * 1024);
327 b.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024);
328 b.option(ChannelOption.SO_RCVBUF, 1048576);
329 b.option(ChannelOption.TCP_NODELAY, true);
330 b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
331 b.group(serverGroup, clientGroup);
332 b.channel(serverChannelClass);
333 if (enableNettyTls) {
334 b.childHandler(new SslServerCommunicationChannelInitializer());
335 } else {
336 b.childHandler(new OnosCommunicationChannelInitializer());
337 }
338 b.option(ChannelOption.SO_BACKLOG, 128);
339 b.childOption(ChannelOption.SO_KEEPALIVE, true);
340
341 // Bind and start to accept incoming connections.
342 b.bind(localEp.port()).sync().addListener(future -> {
343 if (future.isSuccess()) {
344 log.info("{} accepting incoming connections on port {}", localEp.host(), localEp.port());
345 } else {
346 log.warn("{} failed to bind to port {}", localEp.host(), localEp.port(), future.cause());
347 }
348 });
349 }
350
351 private class OnosCommunicationChannelFactory
352 implements KeyedPoolableObjectFactory<Endpoint, Connection> {
353
354 @Override
355 public void activateObject(Endpoint endpoint, Connection connection)
356 throws Exception {
357 }
358
359 @Override
360 public void destroyObject(Endpoint ep, Connection connection) throws Exception {
361 log.debug("Closing connection to {}", ep);
362 //Is this the right way to destroy?
363 connection.destroy();
364 }
365
366 @Override
367 public Connection makeObject(Endpoint ep) throws Exception {
368 Bootstrap bootstrap = new Bootstrap();
369 bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
370 bootstrap.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 10 * 64 * 1024);
371 bootstrap.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 10 * 32 * 1024);
372 bootstrap.option(ChannelOption.SO_SNDBUF, 1048576);
373 bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000);
374 bootstrap.group(clientGroup);
375 // TODO: Make this faster:
376 // http://normanmaurer.me/presentations/2014-facebook-eng-netty/slides.html#37.0
377 bootstrap.channel(clientChannelClass);
378 bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
379 if (enableNettyTls) {
380 bootstrap.handler(new SslClientCommunicationChannelInitializer());
381 } else {
382 bootstrap.handler(new OnosCommunicationChannelInitializer());
383 }
384 // Start the client.
385 CompletableFuture<Channel> retFuture = new CompletableFuture<>();
386 ChannelFuture f = bootstrap.connect(ep.host().toString(), ep.port());
387
388 f.addListener(future -> {
389 if (future.isSuccess()) {
390 retFuture.complete(f.channel());
391 } else {
392 retFuture.completeExceptionally(future.cause());
393 }
394 });
395 log.debug("Established a new connection to {}", ep);
396 return new Connection(retFuture);
397 }
398
399 @Override
400 public void passivateObject(Endpoint ep, Connection connection)
401 throws Exception {
402 }
403
404 @Override
405 public boolean validateObject(Endpoint ep, Connection connection) {
406 return connection.validate();
407 }
408 }
409
410 private class SslServerCommunicationChannelInitializer extends ChannelInitializer<SocketChannel> {
411
412 private final ChannelHandler dispatcher = new InboundMessageDispatcher();
413 private final ChannelHandler encoder = new MessageEncoder(preamble);
414
415 @Override
416 protected void initChannel(SocketChannel channel) throws Exception {
417 TrustManagerFactory tmFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
418 KeyStore ts = KeyStore.getInstance("JKS");
419 ts.load(new FileInputStream(tsLocation), tsPwd);
420 tmFactory.init(ts);
421
422 KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
423 KeyStore ks = KeyStore.getInstance("JKS");
424 ks.load(new FileInputStream(ksLocation), ksPwd);
425 kmf.init(ks, ksPwd);
426
427 SSLContext serverContext = SSLContext.getInstance("TLS");
428 serverContext.init(kmf.getKeyManagers(), tmFactory.getTrustManagers(), null);
429
430 SSLEngine serverSslEngine = serverContext.createSSLEngine();
431
432 serverSslEngine.setNeedClientAuth(true);
433 serverSslEngine.setUseClientMode(false);
434 serverSslEngine.setEnabledProtocols(serverSslEngine.getSupportedProtocols());
435 serverSslEngine.setEnabledCipherSuites(serverSslEngine.getSupportedCipherSuites());
436 serverSslEngine.setEnableSessionCreation(true);
437
438 channel.pipeline().addLast("ssl", new io.netty.handler.ssl.SslHandler(serverSslEngine))
439 .addLast("encoder", encoder)
Madan Jampanib825aeb2016-04-01 15:18:25 -0700440 .addLast("decoder", new MessageDecoder())
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800441 .addLast("handler", dispatcher);
442 }
443 }
444
445 private class SslClientCommunicationChannelInitializer extends ChannelInitializer<SocketChannel> {
446
447 private final ChannelHandler dispatcher = new InboundMessageDispatcher();
448 private final ChannelHandler encoder = new MessageEncoder(preamble);
449
450 @Override
451 protected void initChannel(SocketChannel channel) throws Exception {
452 TrustManagerFactory tmFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
453 KeyStore ts = KeyStore.getInstance("JKS");
454 ts.load(new FileInputStream(tsLocation), tsPwd);
455 tmFactory.init(ts);
456
457 KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
458 KeyStore ks = KeyStore.getInstance("JKS");
459 ks.load(new FileInputStream(ksLocation), ksPwd);
460 kmf.init(ks, ksPwd);
461
462 SSLContext clientContext = SSLContext.getInstance("TLS");
463 clientContext.init(kmf.getKeyManagers(), tmFactory.getTrustManagers(), null);
464
465 SSLEngine clientSslEngine = clientContext.createSSLEngine();
466
467 clientSslEngine.setUseClientMode(true);
468 clientSslEngine.setEnabledProtocols(clientSslEngine.getSupportedProtocols());
469 clientSslEngine.setEnabledCipherSuites(clientSslEngine.getSupportedCipherSuites());
470 clientSslEngine.setEnableSessionCreation(true);
471
472 channel.pipeline().addLast("ssl", new io.netty.handler.ssl.SslHandler(clientSslEngine))
473 .addLast("encoder", encoder)
Madan Jampanib825aeb2016-04-01 15:18:25 -0700474 .addLast("decoder", new MessageDecoder())
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800475 .addLast("handler", dispatcher);
476 }
477 }
478
479 private class OnosCommunicationChannelInitializer extends ChannelInitializer<SocketChannel> {
480
481 private final ChannelHandler dispatcher = new InboundMessageDispatcher();
482 private final ChannelHandler encoder = new MessageEncoder(preamble);
483
484 @Override
485 protected void initChannel(SocketChannel channel) throws Exception {
486 channel.pipeline()
487 .addLast("encoder", encoder)
Madan Jampanib825aeb2016-04-01 15:18:25 -0700488 .addLast("decoder", new MessageDecoder())
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800489 .addLast("handler", dispatcher);
490 }
491 }
492
493 @ChannelHandler.Sharable
494 private class InboundMessageDispatcher extends SimpleChannelInboundHandler<InternalMessage> {
495
496 @Override
497 protected void channelRead0(ChannelHandlerContext ctx, InternalMessage message) throws Exception {
498 try {
499 dispatchLocally(message);
500 } catch (RejectedExecutionException e) {
501 log.warn("Unable to dispatch message due to {}", e.getMessage());
502 }
503 }
504
505 @Override
506 public void exceptionCaught(ChannelHandlerContext context, Throwable cause) {
507 log.error("Exception inside channel handling pipeline.", cause);
508 context.close();
509 }
510 }
511 private void dispatchLocally(InternalMessage message) throws IOException {
Madan Jampanib825aeb2016-04-01 15:18:25 -0700512 if (message.preamble() != preamble) {
513 log.debug("Received {} with invalid preamble from {}", message.type(), message.sender());
514 sendReply(message, Status.PROTOCOL_EXCEPTION, Optional.empty());
515 }
Madan Jampani05833872016-07-12 23:01:39 -0700516 clockService.recordEventTime(message.time());
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800517 String type = message.type();
518 if (REPLY_MESSAGE_TYPE.equals(type)) {
519 try {
520 Callback callback =
521 callbacks.getIfPresent(message.id());
522 if (callback != null) {
Madan Jampania9e70a62016-03-02 16:28:18 -0800523 if (message.status() == Status.OK) {
524 callback.complete(message.payload());
525 } else if (message.status() == Status.ERROR_NO_HANDLER) {
526 callback.completeExceptionally(new MessagingException.NoRemoteHandler());
527 } else if (message.status() == Status.ERROR_HANDLER_EXCEPTION) {
528 callback.completeExceptionally(new MessagingException.RemoteHandlerFailure());
Madan Jampanib825aeb2016-04-01 15:18:25 -0700529 } else if (message.status() == Status.PROTOCOL_EXCEPTION) {
530 callback.completeExceptionally(new MessagingException.ProcotolException());
Madan Jampania9e70a62016-03-02 16:28:18 -0800531 }
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800532 } else {
Madan Jampania9e70a62016-03-02 16:28:18 -0800533 log.debug("Received a reply for message id:[{}]. "
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800534 + " from {}. But was unable to locate the"
535 + " request handle", message.id(), message.sender());
536 }
537 } finally {
538 callbacks.invalidate(message.id());
539 }
540 return;
541 }
542 Consumer<InternalMessage> handler = handlers.get(type);
543 if (handler != null) {
544 handler.accept(message);
545 } else {
Madan Jampania9e70a62016-03-02 16:28:18 -0800546 log.debug("No handler for message type {}", message.type(), message.sender());
547 sendReply(message, Status.ERROR_NO_HANDLER, Optional.empty());
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800548 }
549 }
550
Madan Jampania9e70a62016-03-02 16:28:18 -0800551 private void sendReply(InternalMessage message, Status status, Optional<byte[]> responsePayload) {
Madan Jampanib825aeb2016-04-01 15:18:25 -0700552 InternalMessage response = new InternalMessage(preamble,
Madan Jampani05833872016-07-12 23:01:39 -0700553 clockService.timeNow(),
Madan Jampanib825aeb2016-04-01 15:18:25 -0700554 message.id(),
Madan Jampania9e70a62016-03-02 16:28:18 -0800555 localEp,
556 REPLY_MESSAGE_TYPE,
557 responsePayload.orElse(new byte[0]),
558 status);
559 sendAsync(message.sender(), response).whenComplete((result, error) -> {
560 if (error != null) {
561 log.debug("Failed to respond", error);
562 }
563 });
564 }
565
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800566 private final class Callback {
567 private final CompletableFuture<byte[]> future;
568 private final Executor executor;
569
570 public Callback(CompletableFuture<byte[]> future, Executor executor) {
571 this.future = future;
572 this.executor = executor;
573 }
574
575 public void complete(byte[] value) {
576 executor.execute(() -> future.complete(value));
577 }
578
579 public void completeExceptionally(Throwable error) {
580 executor.execute(() -> future.completeExceptionally(error));
581 }
582 }
583 private final class Connection {
584 private final CompletableFuture<Channel> internalFuture;
585
586 public Connection(CompletableFuture<Channel> internalFuture) {
587 this.internalFuture = internalFuture;
588 }
589
590 /**
591 * Sends a message out on its channel and associated the message with a
592 * completable future used for signaling.
593 * @param message the message to be sent
594 * @param future a future that is completed normally or exceptionally if
595 * message sending succeeds or fails respectively
596 */
597 public void send(Object message, CompletableFuture<Void> future) {
598 internalFuture.whenComplete((channel, throwable) -> {
599 if (throwable == null) {
600 channel.writeAndFlush(message).addListener(channelFuture -> {
601 if (!channelFuture.isSuccess()) {
602 future.completeExceptionally(channelFuture.cause());
603 } else {
604 future.complete(null);
605 }
606 });
607 } else {
608 future.completeExceptionally(throwable);
609 }
610 });
611 }
612
613 /**
614 * Destroys a channel by closing its channel (if it exists) and
615 * cancelling its future.
616 */
617 public void destroy() {
618 Channel channel = internalFuture.getNow(null);
619 if (channel != null) {
620 channel.close();
621 }
622 internalFuture.cancel(false);
623 }
624
625 /**
626 * Determines whether the connection is valid meaning it is either
627 * complete with and active channel
628 * or it has not yet completed.
629 * @return true if the channel has an active connection or has not
630 * yet completed
631 */
632 public boolean validate() {
633 if (internalFuture.isCompletedExceptionally()) {
634 return false;
635 }
636 Channel channel = internalFuture.getNow(null);
637 return channel == null || channel.isActive();
638 }
639 }
JunHuy Lam39eb4292015-06-26 17:24:23 +0900640}