blob: a806c0243b9cdee63513fa7a923aa80de67c08f9 [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;
44import org.apache.commons.pool.KeyedPoolableObjectFactory;
45import org.apache.commons.pool.impl.GenericKeyedObjectPool;
Madan Jampaniafeebbd2015-05-19 15:26:01 -070046import org.apache.felix.scr.annotations.Activate;
47import org.apache.felix.scr.annotations.Component;
48import org.apache.felix.scr.annotations.Deactivate;
49import org.apache.felix.scr.annotations.Reference;
50import org.apache.felix.scr.annotations.ReferenceCardinality;
51import org.apache.felix.scr.annotations.Service;
Aaron Kruglikov1b727382016-02-09 16:17:47 -080052import org.onlab.util.Tools;
Madan Jampaniec1df022015-10-13 21:23:03 -070053import org.onosproject.cluster.ClusterMetadataService;
Madan Jampaniafeebbd2015-05-19 15:26:01 -070054import org.onosproject.cluster.ControllerNode;
Madan Jampani05833872016-07-12 23:01:39 -070055import org.onosproject.core.HybridLogicalClockService;
Madan Jampaniafeebbd2015-05-19 15:26:01 -070056import 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
Yuta HIGUCHI90a16892016-07-20 20:36:08 -070085import static org.onlab.util.Tools.groupedThreads;
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 */
Sho SHIMIZU5c396e32016-08-12 15:19:12 -070092@Component(immediate = true)
Madan Jampaniafeebbd2015-05-19 15:26:01 -070093@Service
Aaron Kruglikov1b727382016-02-09 16:17:47 -080094public class NettyMessagingManager implements MessagingService {
95
Madan Jampanif3ab4242016-07-27 17:21:47 -070096 private static final int REPLY_TIME_OUT_MILLIS = 250;
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 Jampanif3ab4242016-07-27 17:21:47 -0700112 .expireAfterWrite(REPLY_TIME_OUT_MILLIS, TimeUnit.MILLISECONDS)
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
Yuta HIGUCHI90a16892016-07-20 20:36:08 -0700124 = new GenericKeyedObjectPool<>(new OnosCommunicationChannelFactory());
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800125
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 Jampanif3ab4242016-07-27 17:21:47 -0700161 serverGroup.scheduleWithFixedDelay(callbacks::cleanUp, 0, REPLY_TIME_OUT_MILLIS, TimeUnit.MILLISECONDS);
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 {
Yuta HIGUCHI90a16892016-07-20 20:36:08 -0700206 clientGroup = new EpollEventLoopGroup(0, groupedThreads("NettyMessagingEvt", "epollC-%d", log));
207 serverGroup = new EpollEventLoopGroup(0, groupedThreads("NettyMessagingEvt", "epollS-%d", log));
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800208 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 }
Yuta HIGUCHI90a16892016-07-20 20:36:08 -0700215 clientGroup = new NioEventLoopGroup(0, groupedThreads("NettyMessagingEvt", "nioC-%d", log));
216 serverGroup = new NioEventLoopGroup(0, groupedThreads("NettyMessagingEvt", "nioS-%d", log));
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800217 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 }
Yuta HIGUCHIed1ca662016-08-11 11:11:37 -0700282 }).thenComposeAsync(v -> response, executor);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800283 }
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<>();
Yuta HIGUCHIc012dda2016-08-17 00:43:46 -0700385 ChannelFuture f = bootstrap.connect(ep.host().toInetAddress(), ep.port());
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800386
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
Yuta HIGUCHIc012dda2016-08-17 00:43:46 -0700493 private class InboundMessageDispatcher extends SimpleChannelInboundHandler<Object> {
494 // Effectively SimpleChannelInboundHandler<InternalMessage>,
495 // had to specify <Object> to avoid Class Loader not being able to find some classes.
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800496
497 @Override
Yuta HIGUCHIc012dda2016-08-17 00:43:46 -0700498 protected void channelRead0(ChannelHandlerContext ctx, Object rawMessage) throws Exception {
499 InternalMessage message = (InternalMessage) rawMessage;
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800500 try {
501 dispatchLocally(message);
502 } catch (RejectedExecutionException e) {
503 log.warn("Unable to dispatch message due to {}", e.getMessage());
504 }
505 }
506
507 @Override
508 public void exceptionCaught(ChannelHandlerContext context, Throwable cause) {
509 log.error("Exception inside channel handling pipeline.", cause);
510 context.close();
511 }
Yuta HIGUCHIc012dda2016-08-17 00:43:46 -0700512
513 /**
514 * Returns true if the given message should be handled.
515 *
516 * @param msg inbound message
517 * @return true if {@code msg} is {@link InternalMessage} instance.
518 *
519 * @see SimpleChannelInboundHandler#acceptInboundMessage(Object)
520 */
521 @Override
522 public final boolean acceptInboundMessage(Object msg) {
523 return msg instanceof InternalMessage;
524 }
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800525 }
Yuta HIGUCHIc012dda2016-08-17 00:43:46 -0700526
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800527 private void dispatchLocally(InternalMessage message) throws IOException {
Madan Jampanib825aeb2016-04-01 15:18:25 -0700528 if (message.preamble() != preamble) {
529 log.debug("Received {} with invalid preamble from {}", message.type(), message.sender());
530 sendReply(message, Status.PROTOCOL_EXCEPTION, Optional.empty());
531 }
Madan Jampani05833872016-07-12 23:01:39 -0700532 clockService.recordEventTime(message.time());
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800533 String type = message.type();
534 if (REPLY_MESSAGE_TYPE.equals(type)) {
535 try {
536 Callback callback =
537 callbacks.getIfPresent(message.id());
538 if (callback != null) {
Madan Jampania9e70a62016-03-02 16:28:18 -0800539 if (message.status() == Status.OK) {
540 callback.complete(message.payload());
541 } else if (message.status() == Status.ERROR_NO_HANDLER) {
542 callback.completeExceptionally(new MessagingException.NoRemoteHandler());
543 } else if (message.status() == Status.ERROR_HANDLER_EXCEPTION) {
544 callback.completeExceptionally(new MessagingException.RemoteHandlerFailure());
Madan Jampanib825aeb2016-04-01 15:18:25 -0700545 } else if (message.status() == Status.PROTOCOL_EXCEPTION) {
546 callback.completeExceptionally(new MessagingException.ProcotolException());
Madan Jampania9e70a62016-03-02 16:28:18 -0800547 }
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800548 } else {
Madan Jampania9e70a62016-03-02 16:28:18 -0800549 log.debug("Received a reply for message id:[{}]. "
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800550 + " from {}. But was unable to locate the"
551 + " request handle", message.id(), message.sender());
552 }
553 } finally {
554 callbacks.invalidate(message.id());
555 }
556 return;
557 }
558 Consumer<InternalMessage> handler = handlers.get(type);
559 if (handler != null) {
560 handler.accept(message);
561 } else {
Madan Jampania9e70a62016-03-02 16:28:18 -0800562 log.debug("No handler for message type {}", message.type(), message.sender());
563 sendReply(message, Status.ERROR_NO_HANDLER, Optional.empty());
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800564 }
565 }
566
Madan Jampania9e70a62016-03-02 16:28:18 -0800567 private void sendReply(InternalMessage message, Status status, Optional<byte[]> responsePayload) {
Madan Jampanib825aeb2016-04-01 15:18:25 -0700568 InternalMessage response = new InternalMessage(preamble,
Madan Jampani05833872016-07-12 23:01:39 -0700569 clockService.timeNow(),
Madan Jampanib825aeb2016-04-01 15:18:25 -0700570 message.id(),
Madan Jampania9e70a62016-03-02 16:28:18 -0800571 localEp,
572 REPLY_MESSAGE_TYPE,
573 responsePayload.orElse(new byte[0]),
574 status);
575 sendAsync(message.sender(), response).whenComplete((result, error) -> {
576 if (error != null) {
577 log.debug("Failed to respond", error);
578 }
579 });
580 }
581
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800582 private final class Callback {
583 private final CompletableFuture<byte[]> future;
584 private final Executor executor;
585
586 public Callback(CompletableFuture<byte[]> future, Executor executor) {
587 this.future = future;
588 this.executor = executor;
589 }
590
591 public void complete(byte[] value) {
592 executor.execute(() -> future.complete(value));
593 }
594
595 public void completeExceptionally(Throwable error) {
596 executor.execute(() -> future.completeExceptionally(error));
597 }
598 }
599 private final class Connection {
600 private final CompletableFuture<Channel> internalFuture;
601
602 public Connection(CompletableFuture<Channel> internalFuture) {
603 this.internalFuture = internalFuture;
604 }
605
606 /**
607 * Sends a message out on its channel and associated the message with a
608 * completable future used for signaling.
609 * @param message the message to be sent
610 * @param future a future that is completed normally or exceptionally if
611 * message sending succeeds or fails respectively
612 */
613 public void send(Object message, CompletableFuture<Void> future) {
614 internalFuture.whenComplete((channel, throwable) -> {
615 if (throwable == null) {
616 channel.writeAndFlush(message).addListener(channelFuture -> {
617 if (!channelFuture.isSuccess()) {
618 future.completeExceptionally(channelFuture.cause());
619 } else {
620 future.complete(null);
621 }
622 });
623 } else {
624 future.completeExceptionally(throwable);
625 }
626 });
627 }
628
629 /**
630 * Destroys a channel by closing its channel (if it exists) and
631 * cancelling its future.
632 */
633 public void destroy() {
634 Channel channel = internalFuture.getNow(null);
635 if (channel != null) {
636 channel.close();
637 }
638 internalFuture.cancel(false);
639 }
640
641 /**
642 * Determines whether the connection is valid meaning it is either
643 * complete with and active channel
644 * or it has not yet completed.
645 * @return true if the channel has an active connection or has not
646 * yet completed
647 */
648 public boolean validate() {
649 if (internalFuture.isCompletedExceptionally()) {
650 return false;
651 }
652 Channel channel = internalFuture.getNow(null);
653 return channel == null || channel.isActive();
654 }
655 }
JunHuy Lam39eb4292015-06-26 17:24:23 +0900656}