blob: e93e63b88a7fde449074ded4368fa488a05b86c1 [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;
Jon Hall9a44d6a2017-03-02 18:14:37 -080037import io.netty.channel.WriteBufferWaterMark;
Aaron Kruglikov1b727382016-02-09 16:17:47 -080038import io.netty.channel.epoll.EpollEventLoopGroup;
39import io.netty.channel.epoll.EpollServerSocketChannel;
40import io.netty.channel.epoll.EpollSocketChannel;
41import io.netty.channel.nio.NioEventLoopGroup;
42import io.netty.channel.socket.SocketChannel;
43import io.netty.channel.socket.nio.NioServerSocketChannel;
44import io.netty.channel.socket.nio.NioSocketChannel;
45import 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 {
Yuta HIGUCHIb47c9532016-08-22 09:41:23 -0700252 if (connection != null) {
253 channels.returnObject(ep, connection);
254 }
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800255 }
256 } catch (Exception e) {
257 future.completeExceptionally(e);
258 }
259 return future;
260 }
261
262 @Override
263 public CompletableFuture<byte[]> sendAndReceive(Endpoint ep, String type, byte[] payload) {
Heedo Kang4a47a302016-02-29 17:40:23 +0900264 checkPermission(CLUSTER_WRITE);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800265 return sendAndReceive(ep, type, payload, MoreExecutors.directExecutor());
266 }
267
268 @Override
269 public CompletableFuture<byte[]> sendAndReceive(Endpoint ep, String type, byte[] payload, Executor executor) {
Heedo Kang4a47a302016-02-29 17:40:23 +0900270 checkPermission(CLUSTER_WRITE);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800271 CompletableFuture<byte[]> response = new CompletableFuture<>();
272 Callback callback = new Callback(response, executor);
273 Long messageId = messageIdGenerator.incrementAndGet();
274 callbacks.put(messageId, callback);
Madan Jampani05833872016-07-12 23:01:39 -0700275 InternalMessage message = new InternalMessage(preamble,
276 clockService.timeNow(),
277 messageId,
278 localEp,
279 type,
280 payload);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800281 return sendAsync(ep, message).whenComplete((r, e) -> {
282 if (e != null) {
283 callbacks.invalidate(messageId);
284 }
Yuta HIGUCHIed1ca662016-08-11 11:11:37 -0700285 }).thenComposeAsync(v -> response, executor);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800286 }
287
288 @Override
289 public void registerHandler(String type, BiConsumer<Endpoint, byte[]> handler, Executor executor) {
Heedo Kang4a47a302016-02-29 17:40:23 +0900290 checkPermission(CLUSTER_WRITE);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800291 handlers.put(type, message -> executor.execute(() -> handler.accept(message.sender(), message.payload())));
292 }
293
294 @Override
295 public void registerHandler(String type, BiFunction<Endpoint, byte[], byte[]> handler, Executor executor) {
Heedo Kang4a47a302016-02-29 17:40:23 +0900296 checkPermission(CLUSTER_WRITE);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800297 handlers.put(type, message -> executor.execute(() -> {
Madan Jampania9e70a62016-03-02 16:28:18 -0800298 byte[] responsePayload = null;
299 Status status = Status.OK;
300 try {
301 responsePayload = handler.apply(message.sender(), message.payload());
302 } catch (Exception e) {
303 status = Status.ERROR_HANDLER_EXCEPTION;
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800304 }
Madan Jampania9e70a62016-03-02 16:28:18 -0800305 sendReply(message, status, Optional.ofNullable(responsePayload));
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800306 }));
307 }
308
309 @Override
310 public void registerHandler(String type, BiFunction<Endpoint, byte[], CompletableFuture<byte[]>> handler) {
Heedo Kang4a47a302016-02-29 17:40:23 +0900311 checkPermission(CLUSTER_WRITE);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800312 handlers.put(type, message -> {
313 handler.apply(message.sender(), message.payload()).whenComplete((result, error) -> {
Madan Jampania9e70a62016-03-02 16:28:18 -0800314 Status status = error == null ? Status.OK : Status.ERROR_HANDLER_EXCEPTION;
315 sendReply(message, status, Optional.ofNullable(result));
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800316 });
317 });
318 }
319
320 @Override
321 public void unregisterHandler(String type) {
Heedo Kang4a47a302016-02-29 17:40:23 +0900322 checkPermission(CLUSTER_WRITE);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800323 handlers.remove(type);
324 }
325
326 private void startAcceptingConnections() throws InterruptedException {
327 ServerBootstrap b = new ServerBootstrap();
Jon Hall9a44d6a2017-03-02 18:14:37 -0800328 b.childOption(ChannelOption.WRITE_BUFFER_WATER_MARK,
329 new WriteBufferWaterMark(8 * 1024, 32 * 1024));
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800330 b.option(ChannelOption.SO_RCVBUF, 1048576);
331 b.option(ChannelOption.TCP_NODELAY, true);
Yuta HIGUCHIb47c9532016-08-22 09:41:23 -0700332 b.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800333 b.group(serverGroup, clientGroup);
334 b.channel(serverChannelClass);
335 if (enableNettyTls) {
336 b.childHandler(new SslServerCommunicationChannelInitializer());
337 } else {
338 b.childHandler(new OnosCommunicationChannelInitializer());
339 }
340 b.option(ChannelOption.SO_BACKLOG, 128);
341 b.childOption(ChannelOption.SO_KEEPALIVE, true);
342
343 // Bind and start to accept incoming connections.
344 b.bind(localEp.port()).sync().addListener(future -> {
345 if (future.isSuccess()) {
346 log.info("{} accepting incoming connections on port {}", localEp.host(), localEp.port());
347 } else {
Jon Hall9a44d6a2017-03-02 18:14:37 -0800348 log.warn("{} failed to bind to port {} due to {}", localEp.host(), localEp.port(), future.cause());
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800349 }
350 });
351 }
352
353 private class OnosCommunicationChannelFactory
354 implements KeyedPoolableObjectFactory<Endpoint, Connection> {
355
356 @Override
Jon Hall9a44d6a2017-03-02 18:14:37 -0800357 public void activateObject(Endpoint endpoint, Connection connection)
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800358 throws Exception {
359 }
360
361 @Override
362 public void destroyObject(Endpoint ep, Connection connection) throws Exception {
Jon Hall9a44d6a2017-03-02 18:14:37 -0800363 log.debug("Closing connection {} to {}", connection, ep);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800364 //Is this the right way to destroy?
365 connection.destroy();
366 }
367
368 @Override
369 public Connection makeObject(Endpoint ep) throws Exception {
370 Bootstrap bootstrap = new Bootstrap();
371 bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
Jon Hall9a44d6a2017-03-02 18:14:37 -0800372 bootstrap.option(ChannelOption.WRITE_BUFFER_WATER_MARK,
373 new WriteBufferWaterMark(10 * 32 * 1024, 10 * 64 * 1024));
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800374 bootstrap.option(ChannelOption.SO_SNDBUF, 1048576);
375 bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000);
376 bootstrap.group(clientGroup);
377 // TODO: Make this faster:
378 // http://normanmaurer.me/presentations/2014-facebook-eng-netty/slides.html#37.0
379 bootstrap.channel(clientChannelClass);
380 bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
381 if (enableNettyTls) {
382 bootstrap.handler(new SslClientCommunicationChannelInitializer());
383 } else {
384 bootstrap.handler(new OnosCommunicationChannelInitializer());
385 }
386 // Start the client.
387 CompletableFuture<Channel> retFuture = new CompletableFuture<>();
Yuta HIGUCHIc012dda2016-08-17 00:43:46 -0700388 ChannelFuture f = bootstrap.connect(ep.host().toInetAddress(), ep.port());
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800389
390 f.addListener(future -> {
391 if (future.isSuccess()) {
392 retFuture.complete(f.channel());
393 } else {
394 retFuture.completeExceptionally(future.cause());
395 }
396 });
397 log.debug("Established a new connection to {}", ep);
398 return new Connection(retFuture);
399 }
400
401 @Override
402 public void passivateObject(Endpoint ep, Connection connection)
403 throws Exception {
404 }
405
406 @Override
407 public boolean validateObject(Endpoint ep, Connection connection) {
408 return connection.validate();
409 }
410 }
411
412 private class SslServerCommunicationChannelInitializer extends ChannelInitializer<SocketChannel> {
413
414 private final ChannelHandler dispatcher = new InboundMessageDispatcher();
415 private final ChannelHandler encoder = new MessageEncoder(preamble);
416
417 @Override
418 protected void initChannel(SocketChannel channel) throws Exception {
419 TrustManagerFactory tmFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
420 KeyStore ts = KeyStore.getInstance("JKS");
421 ts.load(new FileInputStream(tsLocation), tsPwd);
422 tmFactory.init(ts);
423
424 KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
425 KeyStore ks = KeyStore.getInstance("JKS");
426 ks.load(new FileInputStream(ksLocation), ksPwd);
427 kmf.init(ks, ksPwd);
428
429 SSLContext serverContext = SSLContext.getInstance("TLS");
430 serverContext.init(kmf.getKeyManagers(), tmFactory.getTrustManagers(), null);
431
432 SSLEngine serverSslEngine = serverContext.createSSLEngine();
433
434 serverSslEngine.setNeedClientAuth(true);
435 serverSslEngine.setUseClientMode(false);
436 serverSslEngine.setEnabledProtocols(serverSslEngine.getSupportedProtocols());
437 serverSslEngine.setEnabledCipherSuites(serverSslEngine.getSupportedCipherSuites());
438 serverSslEngine.setEnableSessionCreation(true);
439
440 channel.pipeline().addLast("ssl", new io.netty.handler.ssl.SslHandler(serverSslEngine))
441 .addLast("encoder", encoder)
Madan Jampanib825aeb2016-04-01 15:18:25 -0700442 .addLast("decoder", new MessageDecoder())
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800443 .addLast("handler", dispatcher);
444 }
445 }
446
447 private class SslClientCommunicationChannelInitializer extends ChannelInitializer<SocketChannel> {
448
449 private final ChannelHandler dispatcher = new InboundMessageDispatcher();
450 private final ChannelHandler encoder = new MessageEncoder(preamble);
451
452 @Override
453 protected void initChannel(SocketChannel channel) throws Exception {
454 TrustManagerFactory tmFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
455 KeyStore ts = KeyStore.getInstance("JKS");
456 ts.load(new FileInputStream(tsLocation), tsPwd);
457 tmFactory.init(ts);
458
459 KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
460 KeyStore ks = KeyStore.getInstance("JKS");
461 ks.load(new FileInputStream(ksLocation), ksPwd);
462 kmf.init(ks, ksPwd);
463
464 SSLContext clientContext = SSLContext.getInstance("TLS");
465 clientContext.init(kmf.getKeyManagers(), tmFactory.getTrustManagers(), null);
466
467 SSLEngine clientSslEngine = clientContext.createSSLEngine();
468
469 clientSslEngine.setUseClientMode(true);
470 clientSslEngine.setEnabledProtocols(clientSslEngine.getSupportedProtocols());
471 clientSslEngine.setEnabledCipherSuites(clientSslEngine.getSupportedCipherSuites());
472 clientSslEngine.setEnableSessionCreation(true);
473
474 channel.pipeline().addLast("ssl", new io.netty.handler.ssl.SslHandler(clientSslEngine))
475 .addLast("encoder", encoder)
Madan Jampanib825aeb2016-04-01 15:18:25 -0700476 .addLast("decoder", new MessageDecoder())
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800477 .addLast("handler", dispatcher);
478 }
479 }
480
481 private class OnosCommunicationChannelInitializer extends ChannelInitializer<SocketChannel> {
482
483 private final ChannelHandler dispatcher = new InboundMessageDispatcher();
484 private final ChannelHandler encoder = new MessageEncoder(preamble);
485
486 @Override
487 protected void initChannel(SocketChannel channel) throws Exception {
488 channel.pipeline()
489 .addLast("encoder", encoder)
Madan Jampanib825aeb2016-04-01 15:18:25 -0700490 .addLast("decoder", new MessageDecoder())
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800491 .addLast("handler", dispatcher);
492 }
493 }
494
495 @ChannelHandler.Sharable
Yuta HIGUCHIc012dda2016-08-17 00:43:46 -0700496 private class InboundMessageDispatcher extends SimpleChannelInboundHandler<Object> {
497 // Effectively SimpleChannelInboundHandler<InternalMessage>,
498 // had to specify <Object> to avoid Class Loader not being able to find some classes.
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800499
500 @Override
Yuta HIGUCHIc012dda2016-08-17 00:43:46 -0700501 protected void channelRead0(ChannelHandlerContext ctx, Object rawMessage) throws Exception {
502 InternalMessage message = (InternalMessage) rawMessage;
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800503 try {
504 dispatchLocally(message);
505 } catch (RejectedExecutionException e) {
506 log.warn("Unable to dispatch message due to {}", e.getMessage());
507 }
508 }
509
510 @Override
511 public void exceptionCaught(ChannelHandlerContext context, Throwable cause) {
512 log.error("Exception inside channel handling pipeline.", cause);
513 context.close();
514 }
Yuta HIGUCHIc012dda2016-08-17 00:43:46 -0700515
516 /**
517 * Returns true if the given message should be handled.
518 *
519 * @param msg inbound message
520 * @return true if {@code msg} is {@link InternalMessage} instance.
521 *
522 * @see SimpleChannelInboundHandler#acceptInboundMessage(Object)
523 */
524 @Override
525 public final boolean acceptInboundMessage(Object msg) {
526 return msg instanceof InternalMessage;
527 }
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800528 }
Yuta HIGUCHIc012dda2016-08-17 00:43:46 -0700529
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800530 private void dispatchLocally(InternalMessage message) throws IOException {
Madan Jampanib825aeb2016-04-01 15:18:25 -0700531 if (message.preamble() != preamble) {
532 log.debug("Received {} with invalid preamble from {}", message.type(), message.sender());
533 sendReply(message, Status.PROTOCOL_EXCEPTION, Optional.empty());
534 }
Madan Jampani05833872016-07-12 23:01:39 -0700535 clockService.recordEventTime(message.time());
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800536 String type = message.type();
537 if (REPLY_MESSAGE_TYPE.equals(type)) {
538 try {
539 Callback callback =
540 callbacks.getIfPresent(message.id());
541 if (callback != null) {
Madan Jampania9e70a62016-03-02 16:28:18 -0800542 if (message.status() == Status.OK) {
543 callback.complete(message.payload());
544 } else if (message.status() == Status.ERROR_NO_HANDLER) {
545 callback.completeExceptionally(new MessagingException.NoRemoteHandler());
546 } else if (message.status() == Status.ERROR_HANDLER_EXCEPTION) {
547 callback.completeExceptionally(new MessagingException.RemoteHandlerFailure());
Madan Jampanib825aeb2016-04-01 15:18:25 -0700548 } else if (message.status() == Status.PROTOCOL_EXCEPTION) {
Jonathan Harte255cc42016-09-12 14:50:24 -0700549 callback.completeExceptionally(new MessagingException.ProtocolException());
Madan Jampania9e70a62016-03-02 16:28:18 -0800550 }
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800551 } else {
Madan Jampania9e70a62016-03-02 16:28:18 -0800552 log.debug("Received a reply for message id:[{}]. "
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800553 + " from {}. But was unable to locate the"
554 + " request handle", message.id(), message.sender());
555 }
556 } finally {
557 callbacks.invalidate(message.id());
558 }
559 return;
560 }
561 Consumer<InternalMessage> handler = handlers.get(type);
562 if (handler != null) {
563 handler.accept(message);
564 } else {
Jon Hall9a44d6a2017-03-02 18:14:37 -0800565 log.debug("No handler for message type {} from {}", message.type(), message.sender());
Madan Jampania9e70a62016-03-02 16:28:18 -0800566 sendReply(message, Status.ERROR_NO_HANDLER, Optional.empty());
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800567 }
568 }
569
Madan Jampania9e70a62016-03-02 16:28:18 -0800570 private void sendReply(InternalMessage message, Status status, Optional<byte[]> responsePayload) {
Madan Jampanib825aeb2016-04-01 15:18:25 -0700571 InternalMessage response = new InternalMessage(preamble,
Madan Jampani05833872016-07-12 23:01:39 -0700572 clockService.timeNow(),
Madan Jampanib825aeb2016-04-01 15:18:25 -0700573 message.id(),
Madan Jampania9e70a62016-03-02 16:28:18 -0800574 localEp,
575 REPLY_MESSAGE_TYPE,
576 responsePayload.orElse(new byte[0]),
577 status);
578 sendAsync(message.sender(), response).whenComplete((result, error) -> {
579 if (error != null) {
580 log.debug("Failed to respond", error);
581 }
582 });
583 }
584
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800585 private final class Callback {
586 private final CompletableFuture<byte[]> future;
587 private final Executor executor;
588
589 public Callback(CompletableFuture<byte[]> future, Executor executor) {
590 this.future = future;
591 this.executor = executor;
592 }
593
594 public void complete(byte[] value) {
595 executor.execute(() -> future.complete(value));
596 }
597
598 public void completeExceptionally(Throwable error) {
599 executor.execute(() -> future.completeExceptionally(error));
600 }
601 }
602 private final class Connection {
603 private final CompletableFuture<Channel> internalFuture;
604
605 public Connection(CompletableFuture<Channel> internalFuture) {
606 this.internalFuture = internalFuture;
607 }
608
609 /**
610 * Sends a message out on its channel and associated the message with a
611 * completable future used for signaling.
612 * @param message the message to be sent
613 * @param future a future that is completed normally or exceptionally if
614 * message sending succeeds or fails respectively
615 */
616 public void send(Object message, CompletableFuture<Void> future) {
617 internalFuture.whenComplete((channel, throwable) -> {
618 if (throwable == null) {
619 channel.writeAndFlush(message).addListener(channelFuture -> {
620 if (!channelFuture.isSuccess()) {
621 future.completeExceptionally(channelFuture.cause());
622 } else {
623 future.complete(null);
624 }
625 });
626 } else {
627 future.completeExceptionally(throwable);
628 }
629 });
630 }
631
632 /**
633 * Destroys a channel by closing its channel (if it exists) and
634 * cancelling its future.
635 */
636 public void destroy() {
637 Channel channel = internalFuture.getNow(null);
638 if (channel != null) {
639 channel.close();
640 }
641 internalFuture.cancel(false);
642 }
643
644 /**
645 * Determines whether the connection is valid meaning it is either
646 * complete with and active channel
647 * or it has not yet completed.
648 * @return true if the channel has an active connection or has not
649 * yet completed
650 */
651 public boolean validate() {
652 if (internalFuture.isCompletedExceptionally()) {
653 return false;
654 }
655 Channel channel = internalFuture.getNow(null);
656 return channel == null || channel.isActive();
657 }
658 }
JunHuy Lam39eb4292015-06-26 17:24:23 +0900659}