blob: d9ed9c3ba106ad3a81b5ffc90a22cc49d58ad5a9 [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
Aaron Kruglikov1b727382016-02-09 16:17:47 -080018import javax.net.ssl.KeyManagerFactory;
19import javax.net.ssl.SSLContext;
20import javax.net.ssl.SSLEngine;
21import javax.net.ssl.TrustManagerFactory;
Brian O'Connor740e98c2017-06-29 17:07:17 -070022import java.io.File;
Aaron Kruglikov1b727382016-02-09 16:17:47 -080023import java.io.FileInputStream;
Brian O'Connor740e98c2017-06-29 17:07:17 -070024import java.io.FileNotFoundException;
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -070025import java.net.ConnectException;
Brian O'Connor740e98c2017-06-29 17:07:17 -070026import java.security.Key;
Aaron Kruglikov1b727382016-02-09 16:17:47 -080027import java.security.KeyStore;
Brian O'Connor740e98c2017-06-29 17:07:17 -070028import java.security.MessageDigest;
29import java.security.cert.Certificate;
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -070030import java.time.Duration;
Jordan Halterman66e6e3b2017-07-10 11:26:34 -070031import java.util.ArrayList;
Brian O'Connor740e98c2017-06-29 17:07:17 -070032import java.util.Enumeration;
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -070033import java.util.Iterator;
Jordan Halterman66e6e3b2017-07-10 11:26:34 -070034import java.util.List;
Aaron Kruglikov1b727382016-02-09 16:17:47 -080035import java.util.Map;
Madan Jampania9e70a62016-03-02 16:28:18 -080036import java.util.Optional;
Brian O'Connor740e98c2017-06-29 17:07:17 -070037import java.util.StringJoiner;
Aaron Kruglikov1b727382016-02-09 16:17:47 -080038import java.util.concurrent.CompletableFuture;
39import java.util.concurrent.ConcurrentHashMap;
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -070040import java.util.concurrent.ExecutionException;
Aaron Kruglikov1b727382016-02-09 16:17:47 -080041import java.util.concurrent.Executor;
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -070042import java.util.concurrent.Executors;
Aaron Kruglikov1b727382016-02-09 16:17:47 -080043import java.util.concurrent.RejectedExecutionException;
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -070044import java.util.concurrent.ScheduledExecutorService;
45import java.util.concurrent.ScheduledFuture;
Aaron Kruglikov1b727382016-02-09 16:17:47 -080046import java.util.concurrent.TimeUnit;
47import java.util.concurrent.TimeoutException;
48import java.util.concurrent.atomic.AtomicBoolean;
49import java.util.concurrent.atomic.AtomicLong;
50import java.util.function.BiConsumer;
51import java.util.function.BiFunction;
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -070052import java.util.function.Function;
Aaron Kruglikov1b727382016-02-09 16:17:47 -080053
Jordan Halterman66e6e3b2017-07-10 11:26:34 -070054import com.google.common.cache.Cache;
55import com.google.common.cache.CacheBuilder;
56import com.google.common.collect.Lists;
57import com.google.common.collect.Maps;
58import com.google.common.util.concurrent.MoreExecutors;
59import io.netty.bootstrap.Bootstrap;
60import io.netty.bootstrap.ServerBootstrap;
61import io.netty.buffer.PooledByteBufAllocator;
62import io.netty.channel.Channel;
63import io.netty.channel.ChannelFuture;
64import io.netty.channel.ChannelHandler;
65import io.netty.channel.ChannelHandlerContext;
66import io.netty.channel.ChannelInitializer;
67import io.netty.channel.ChannelOption;
68import io.netty.channel.EventLoopGroup;
69import io.netty.channel.ServerChannel;
70import io.netty.channel.SimpleChannelInboundHandler;
71import io.netty.channel.WriteBufferWaterMark;
72import io.netty.channel.epoll.EpollEventLoopGroup;
73import io.netty.channel.epoll.EpollServerSocketChannel;
74import io.netty.channel.epoll.EpollSocketChannel;
75import io.netty.channel.nio.NioEventLoopGroup;
76import io.netty.channel.socket.SocketChannel;
77import io.netty.channel.socket.nio.NioServerSocketChannel;
78import io.netty.channel.socket.nio.NioSocketChannel;
79import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics;
80import org.apache.commons.math3.stat.descriptive.SynchronizedDescriptiveStatistics;
81import org.apache.felix.scr.annotations.Activate;
82import org.apache.felix.scr.annotations.Component;
83import org.apache.felix.scr.annotations.Deactivate;
84import org.apache.felix.scr.annotations.Reference;
85import org.apache.felix.scr.annotations.ReferenceCardinality;
86import org.apache.felix.scr.annotations.Service;
87import org.onosproject.cluster.ClusterMetadataService;
88import org.onosproject.cluster.ControllerNode;
89import org.onosproject.core.HybridLogicalClockService;
90import org.onosproject.store.cluster.messaging.Endpoint;
91import org.onosproject.store.cluster.messaging.MessagingException;
92import org.onosproject.store.cluster.messaging.MessagingService;
93import org.onosproject.store.cluster.messaging.impl.InternalMessage.Status;
94import org.slf4j.Logger;
95import org.slf4j.LoggerFactory;
96
Yuta HIGUCHI90a16892016-07-20 20:36:08 -070097import static org.onlab.util.Tools.groupedThreads;
Heedo Kang4a47a302016-02-29 17:40:23 +090098import static org.onosproject.security.AppGuard.checkPermission;
99import static org.onosproject.security.AppPermission.Type.CLUSTER_WRITE;
100
Madan Jampaniafeebbd2015-05-19 15:26:01 -0700101/**
102 * Netty based MessagingService.
103 */
Sho SHIMIZU5c396e32016-08-12 15:19:12 -0700104@Component(immediate = true)
Madan Jampaniafeebbd2015-05-19 15:26:01 -0700105@Service
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800106public class NettyMessagingManager implements MessagingService {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700107 private static final long DEFAULT_TIMEOUT_MILLIS = 500;
Jordan Halterman66e6e3b2017-07-10 11:26:34 -0700108 private static final long HISTORY_EXPIRE_MILLIS = Duration.ofMinutes(1).toMillis();
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700109 private static final long MIN_TIMEOUT_MILLIS = 100;
110 private static final long MAX_TIMEOUT_MILLIS = 5000;
111 private static final long TIMEOUT_INTERVAL = 50;
112 private static final int WINDOW_SIZE = 100;
113 private static final double TIMEOUT_MULTIPLIER = 2.5;
Jordan Halterman66e6e3b2017-07-10 11:26:34 -0700114 private static final int CHANNEL_POOL_SIZE = 8;
Madan Jampaniafeebbd2015-05-19 15:26:01 -0700115
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700116 private static final byte[] EMPTY_PAYLOAD = new byte[0];
117
Madan Jampaniafeebbd2015-05-19 15:26:01 -0700118 private final Logger log = LoggerFactory.getLogger(getClass());
119
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700120 private final ClientConnection localClientConnection = new LocalClientConnection();
121 private final ServerConnection localServerConnection = new LocalServerConnection(null);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800122
Brian O'Connor740e98c2017-06-29 17:07:17 -0700123 //TODO CONFIG_DIR is duplicated from ConfigFileBasedClusterMetadataProvider
124 private static final String CONFIG_DIR = "../config";
125 private static final String KS_FILE_NAME = "onos.jks";
126 private static final File DEFAULT_KS_FILE = new File(CONFIG_DIR, KS_FILE_NAME);
127 private static final String DEFAULT_KS_PASSWORD = "changeit";
128
Madan Jampani05833872016-07-12 23:01:39 -0700129 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
130 protected HybridLogicalClockService clockService;
131
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700132 private Endpoint localEndpoint;
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800133 private int preamble;
134 private final AtomicBoolean started = new AtomicBoolean(false);
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700135 private final Map<String, BiConsumer<InternalMessage, ServerConnection>> handlers = new ConcurrentHashMap<>();
136 private final Map<Channel, RemoteClientConnection> clientConnections = Maps.newConcurrentMap();
137 private final Map<Channel, RemoteServerConnection> serverConnections = Maps.newConcurrentMap();
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800138 private final AtomicLong messageIdGenerator = new AtomicLong(0);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800139
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700140 private ScheduledFuture<?> timeoutFuture;
141
Jordan Halterman66e6e3b2017-07-10 11:26:34 -0700142 private final Map<Endpoint, List<CompletableFuture<Channel>>> channels = Maps.newConcurrentMap();
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800143
144 private EventLoopGroup serverGroup;
145 private EventLoopGroup clientGroup;
146 private Class<? extends ServerChannel> serverChannelClass;
147 private Class<? extends Channel> clientChannelClass;
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700148 private ScheduledExecutorService timeoutExecutor;
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800149
Brian O'Connor740e98c2017-06-29 17:07:17 -0700150 protected static final boolean TLS_ENABLED = true;
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800151 protected static final boolean TLS_DISABLED = false;
Brian O'Connor740e98c2017-06-29 17:07:17 -0700152 protected boolean enableNettyTls = TLS_ENABLED;
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800153
Brian O'Connor740e98c2017-06-29 17:07:17 -0700154 protected TrustManagerFactory trustManager;
155 protected KeyManagerFactory keyManager;
JunHuy Lam39eb4292015-06-26 17:24:23 +0900156
Madan Jampaniafeebbd2015-05-19 15:26:01 -0700157 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Madan Jampaniec1df022015-10-13 21:23:03 -0700158 protected ClusterMetadataService clusterMetadataService;
Madan Jampaniafeebbd2015-05-19 15:26:01 -0700159
160 @Activate
161 public void activate() throws Exception {
Madan Jampaniec1df022015-10-13 21:23:03 -0700162 ControllerNode localNode = clusterMetadataService.getLocalNode();
Jonathan Hartd9df7bd2015-11-10 17:10:25 -0800163 getTlsParameters();
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800164
165 if (started.get()) {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700166 log.warn("Already running at local endpoint: {}", localEndpoint);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800167 return;
168 }
169 this.preamble = clusterMetadataService.getClusterMetadata().getName().hashCode();
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700170 this.localEndpoint = new Endpoint(localNode.ip(), localNode.tcpPort());
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800171 initEventLoopGroup();
172 startAcceptingConnections();
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700173 timeoutExecutor = Executors.newSingleThreadScheduledExecutor(
174 groupedThreads("NettyMessagingEvt", "timeout", log));
175 timeoutFuture = timeoutExecutor.scheduleAtFixedRate(
176 this::timeoutAllCallbacks, TIMEOUT_INTERVAL, TIMEOUT_INTERVAL, TimeUnit.MILLISECONDS);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800177 started.set(true);
Madan Jampaniafeebbd2015-05-19 15:26:01 -0700178 log.info("Started");
179 }
180
181 @Deactivate
182 public void deactivate() throws Exception {
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800183 if (started.get()) {
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800184 serverGroup.shutdownGracefully();
185 clientGroup.shutdownGracefully();
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700186 timeoutFuture.cancel(false);
187 timeoutExecutor.shutdown();
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800188 started.set(false);
189 }
Madan Jampaniafeebbd2015-05-19 15:26:01 -0700190 log.info("Stopped");
191 }
JunHuy Lam39eb4292015-06-26 17:24:23 +0900192
Jonathan Hartd9df7bd2015-11-10 17:10:25 -0800193 private void getTlsParameters() {
Brian O'Connor740e98c2017-06-29 17:07:17 -0700194 // default is TLS enabled unless key stores cannot be loaded
195 enableNettyTls = Boolean.parseBoolean(System.getProperty("enableNettyTLS", Boolean.toString(TLS_ENABLED)));
196
Jonathan Hartd9df7bd2015-11-10 17:10:25 -0800197 if (enableNettyTls) {
Brian O'Connor740e98c2017-06-29 17:07:17 -0700198 enableNettyTls = loadKeyStores();
199 }
200 }
201
202 private boolean loadKeyStores() {
203 // Maintain a local copy of the trust and key managers in case anything goes wrong
204 TrustManagerFactory tmf;
205 KeyManagerFactory kmf;
206 try {
207 String ksLocation = System.getProperty("javax.net.ssl.keyStore", DEFAULT_KS_FILE.toString());
208 String tsLocation = System.getProperty("javax.net.ssl.trustStore", DEFAULT_KS_FILE.toString());
209 char[] ksPwd = System.getProperty("javax.net.ssl.keyStorePassword", DEFAULT_KS_PASSWORD).toCharArray();
210 char[] tsPwd = System.getProperty("javax.net.ssl.trustStorePassword", DEFAULT_KS_PASSWORD).toCharArray();
211
212 tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
213 KeyStore ts = KeyStore.getInstance("JKS");
214 ts.load(new FileInputStream(tsLocation), tsPwd);
215 tmf.init(ts);
216
217 kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
218 KeyStore ks = KeyStore.getInstance("JKS");
219 ks.load(new FileInputStream(ksLocation), ksPwd);
220 kmf.init(ks, ksPwd);
221 if (log.isInfoEnabled()) {
222 logKeyStore(ks, ksLocation, ksPwd);
JunHuy Lam39eb4292015-06-26 17:24:23 +0900223 }
Brian O'Connor740e98c2017-06-29 17:07:17 -0700224 } catch (FileNotFoundException e) {
225 log.warn("Disabling TLS for intra-cluster messaging; Could not load cluster key store: {}", e.getMessage());
226 return TLS_DISABLED;
227 } catch (Exception e) {
228 //TODO we might want to catch exceptions more specifically
229 log.error("Error loading key store; disabling TLS for intra-cluster messaging", e);
230 return TLS_DISABLED;
231 }
232 this.trustManager = tmf;
233 this.keyManager = kmf;
234 return TLS_ENABLED;
235 }
236
237 private void logKeyStore(KeyStore ks, String ksLocation, char[] ksPwd) {
238 if (log.isInfoEnabled()) {
239 log.info("Loaded cluster key store from: {}", ksLocation);
240 try {
241 for (Enumeration<String> e = ks.aliases(); e.hasMoreElements();) {
242 String alias = e.nextElement();
243 Key key = ks.getKey(alias, ksPwd);
244 Certificate[] certs = ks.getCertificateChain(alias);
245 log.debug("{} -> {}", alias, certs);
246 final byte[] encodedKey;
247 if (certs != null && certs.length > 0) {
248 encodedKey = certs[0].getEncoded();
249 } else {
250 log.info("Could not find cert chain for {}, using fingerprint of key instead...", alias);
251 encodedKey = key.getEncoded();
252 }
253 // Compute the certificate's fingerprint (use the key if certificate cannot be found)
254 MessageDigest digest = MessageDigest.getInstance("SHA1");
255 digest.update(encodedKey);
256 StringJoiner fingerprint = new StringJoiner(":");
257 for (byte b : digest.digest()) {
258 fingerprint.add(String.format("%02X", b));
259 }
260 log.info("{} -> {}", alias, fingerprint);
261 }
262 } catch (Exception e) {
263 log.warn("Unable to print contents of key store: {}", ksLocation, e);
JunHuy Lam39eb4292015-06-26 17:24:23 +0900264 }
265 }
266 }
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700267
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800268 private void initEventLoopGroup() {
269 // try Epoll first and if that does work, use nio.
270 try {
Yuta HIGUCHI90a16892016-07-20 20:36:08 -0700271 clientGroup = new EpollEventLoopGroup(0, groupedThreads("NettyMessagingEvt", "epollC-%d", log));
272 serverGroup = new EpollEventLoopGroup(0, groupedThreads("NettyMessagingEvt", "epollS-%d", log));
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800273 serverChannelClass = EpollServerSocketChannel.class;
274 clientChannelClass = EpollSocketChannel.class;
275 return;
276 } catch (Throwable e) {
277 log.debug("Failed to initialize native (epoll) transport. "
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700278 + "Reason: {}. Proceeding with nio.", e.getMessage());
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800279 }
Yuta HIGUCHI90a16892016-07-20 20:36:08 -0700280 clientGroup = new NioEventLoopGroup(0, groupedThreads("NettyMessagingEvt", "nioC-%d", log));
281 serverGroup = new NioEventLoopGroup(0, groupedThreads("NettyMessagingEvt", "nioS-%d", log));
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800282 serverChannelClass = NioServerSocketChannel.class;
283 clientChannelClass = NioSocketChannel.class;
284 }
285
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700286 /**
287 * Times out response callbacks.
288 */
289 private void timeoutAllCallbacks() {
290 // Iterate through all connections and time out callbacks.
291 for (RemoteClientConnection connection : clientConnections.values()) {
292 connection.timeoutCallbacks();
293 }
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700294 }
295
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800296 @Override
297 public CompletableFuture<Void> sendAsync(Endpoint ep, String type, byte[] payload) {
Heedo Kang4a47a302016-02-29 17:40:23 +0900298 checkPermission(CLUSTER_WRITE);
Madan Jampanib825aeb2016-04-01 15:18:25 -0700299 InternalMessage message = new InternalMessage(preamble,
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700300 clockService.timeNow(),
301 messageIdGenerator.incrementAndGet(),
302 localEndpoint,
303 type,
304 payload);
Jordan Halterman66e6e3b2017-07-10 11:26:34 -0700305 return executeOnPooledConnection(ep, type, c -> c.sendAsync(message), MoreExecutors.directExecutor());
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800306 }
307
308 @Override
309 public CompletableFuture<byte[]> sendAndReceive(Endpoint ep, String type, byte[] payload) {
Heedo Kang4a47a302016-02-29 17:40:23 +0900310 checkPermission(CLUSTER_WRITE);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800311 return sendAndReceive(ep, type, payload, MoreExecutors.directExecutor());
312 }
313
314 @Override
315 public CompletableFuture<byte[]> sendAndReceive(Endpoint ep, String type, byte[] payload, Executor executor) {
Heedo Kang4a47a302016-02-29 17:40:23 +0900316 checkPermission(CLUSTER_WRITE);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800317 Long messageId = messageIdGenerator.incrementAndGet();
Madan Jampani05833872016-07-12 23:01:39 -0700318 InternalMessage message = new InternalMessage(preamble,
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700319 clockService.timeNow(),
320 messageId,
321 localEndpoint,
322 type,
323 payload);
Jordan Halterman66e6e3b2017-07-10 11:26:34 -0700324 return executeOnPooledConnection(ep, type, c -> c.sendAndReceive(message), executor);
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700325 }
Jordan Halterman041534b2017-03-21 10:37:33 -0700326
Jordan Halterman66e6e3b2017-07-10 11:26:34 -0700327 private List<CompletableFuture<Channel>> getChannelPool(Endpoint endpoint) {
328 return channels.computeIfAbsent(endpoint, e -> {
329 List<CompletableFuture<Channel>> defaultList = new ArrayList<>(CHANNEL_POOL_SIZE);
330 for (int i = 0; i < CHANNEL_POOL_SIZE; i++) {
331 defaultList.add(null);
332 }
333 return Lists.newCopyOnWriteArrayList(defaultList);
334 });
335 }
336
337 private int getChannelOffset(String messageType) {
338 return Math.abs(messageType.hashCode() % CHANNEL_POOL_SIZE);
339 }
340
341 private CompletableFuture<Channel> getChannel(Endpoint endpoint, String messageType) {
342 List<CompletableFuture<Channel>> channelPool = getChannelPool(endpoint);
343 int offset = getChannelOffset(messageType);
344
345 CompletableFuture<Channel> channelFuture = channelPool.get(offset);
346 if (channelFuture == null || channelFuture.isCompletedExceptionally()) {
347 synchronized (channelPool) {
348 channelFuture = channelPool.get(offset);
349 if (channelFuture == null || channelFuture.isCompletedExceptionally()) {
350 channelFuture = openChannel(endpoint);
351 channelPool.set(offset, channelFuture);
352 }
353 }
354 }
355
356 CompletableFuture<Channel> future = new CompletableFuture<>();
357 final CompletableFuture<Channel> finalFuture = channelFuture;
358 finalFuture.whenComplete((channel, error) -> {
359 if (error == null) {
360 if (!channel.isActive()) {
361 synchronized (channelPool) {
362 CompletableFuture<Channel> currentFuture = channelPool.get(offset);
363 if (currentFuture == finalFuture) {
364 channelPool.set(offset, null);
365 getChannel(endpoint, messageType).whenComplete((recursiveResult, recursiveError) -> {
366 if (recursiveError == null) {
367 future.complete(recursiveResult);
368 } else {
369 future.completeExceptionally(recursiveError);
370 }
371 });
372 } else {
373 currentFuture.whenComplete((recursiveResult, recursiveError) -> {
374 if (recursiveError == null) {
375 future.complete(recursiveResult);
376 } else {
377 future.completeExceptionally(recursiveError);
378 }
379 });
380 }
381 }
382 } else {
383 future.complete(channel);
384 }
385 } else {
386 future.completeExceptionally(error);
387 }
388 });
389 return future;
390 }
391
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700392 private <T> CompletableFuture<T> executeOnPooledConnection(
393 Endpoint endpoint,
Jordan Halterman66e6e3b2017-07-10 11:26:34 -0700394 String type,
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700395 Function<ClientConnection, CompletableFuture<T>> callback,
396 Executor executor) {
Jordan Halterman66e6e3b2017-07-10 11:26:34 -0700397 CompletableFuture<T> future = new CompletableFuture<T>();
398 executeOnPooledConnection(endpoint, type, callback, executor, future);
399 return future;
400 }
401
402 private <T> void executeOnPooledConnection(
403 Endpoint endpoint,
404 String type,
405 Function<ClientConnection, CompletableFuture<T>> callback,
406 Executor executor,
407 CompletableFuture<T> future) {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700408 if (endpoint.equals(localEndpoint)) {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700409 callback.apply(localClientConnection).whenComplete((result, error) -> {
410 if (error == null) {
411 executor.execute(() -> future.complete(result));
412 } else {
413 executor.execute(() -> future.completeExceptionally(error));
414 }
415 });
Jordan Halterman66e6e3b2017-07-10 11:26:34 -0700416 return;
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700417 }
418
Jordan Halterman66e6e3b2017-07-10 11:26:34 -0700419 getChannel(endpoint, type).whenComplete((channel, channelError) -> {
420 if (channelError == null) {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700421 ClientConnection connection = clientConnections.computeIfAbsent(channel, RemoteClientConnection::new);
Jordan Halterman66e6e3b2017-07-10 11:26:34 -0700422 callback.apply(connection).whenComplete((result, sendError) -> {
423 if (sendError == null) {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700424 executor.execute(() -> future.complete(result));
425 } else {
Jordan Halterman66e6e3b2017-07-10 11:26:34 -0700426 executor.execute(() -> future.completeExceptionally(sendError));
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700427 }
428 });
429 } else {
Jordan Halterman66e6e3b2017-07-10 11:26:34 -0700430 executor.execute(() -> future.completeExceptionally(channelError));
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800431 }
Jordan Halterman041534b2017-03-21 10:37:33 -0700432 });
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800433 }
434
435 @Override
436 public void registerHandler(String type, BiConsumer<Endpoint, byte[]> handler, Executor executor) {
Heedo Kang4a47a302016-02-29 17:40:23 +0900437 checkPermission(CLUSTER_WRITE);
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700438 handlers.put(type, (message, connection) -> executor.execute(() ->
439 handler.accept(message.sender(), message.payload())));
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800440 }
441
442 @Override
443 public void registerHandler(String type, BiFunction<Endpoint, byte[], byte[]> handler, Executor executor) {
Heedo Kang4a47a302016-02-29 17:40:23 +0900444 checkPermission(CLUSTER_WRITE);
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700445 handlers.put(type, (message, connection) -> executor.execute(() -> {
Madan Jampania9e70a62016-03-02 16:28:18 -0800446 byte[] responsePayload = null;
447 Status status = Status.OK;
448 try {
449 responsePayload = handler.apply(message.sender(), message.payload());
450 } catch (Exception e) {
Jordan Haltermanb6ee9e92017-06-21 15:26:28 -0700451 log.debug("An error occurred in a message handler: {}", e);
Madan Jampania9e70a62016-03-02 16:28:18 -0800452 status = Status.ERROR_HANDLER_EXCEPTION;
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800453 }
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700454 connection.reply(message, status, Optional.ofNullable(responsePayload));
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800455 }));
456 }
457
458 @Override
459 public void registerHandler(String type, BiFunction<Endpoint, byte[], CompletableFuture<byte[]>> handler) {
Heedo Kang4a47a302016-02-29 17:40:23 +0900460 checkPermission(CLUSTER_WRITE);
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700461 handlers.put(type, (message, connection) -> {
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800462 handler.apply(message.sender(), message.payload()).whenComplete((result, error) -> {
Jordan Haltermanb6ee9e92017-06-21 15:26:28 -0700463 Status status;
464 if (error == null) {
465 status = Status.OK;
466 } else {
467 log.debug("An error occurred in a message handler: {}", error);
468 status = Status.ERROR_HANDLER_EXCEPTION;
469 }
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700470 connection.reply(message, status, Optional.ofNullable(result));
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800471 });
472 });
473 }
474
475 @Override
476 public void unregisterHandler(String type) {
Heedo Kang4a47a302016-02-29 17:40:23 +0900477 checkPermission(CLUSTER_WRITE);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800478 handlers.remove(type);
479 }
480
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700481 private Bootstrap bootstrapClient(Endpoint endpoint) {
482 Bootstrap bootstrap = new Bootstrap();
483 bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
484 bootstrap.option(ChannelOption.WRITE_BUFFER_WATER_MARK,
485 new WriteBufferWaterMark(10 * 32 * 1024, 10 * 64 * 1024));
486 bootstrap.option(ChannelOption.SO_SNDBUF, 1048576);
487 bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000);
488 bootstrap.group(clientGroup);
489 // TODO: Make this faster:
490 // http://normanmaurer.me/presentations/2014-facebook-eng-netty/slides.html#37.0
491 bootstrap.channel(clientChannelClass);
492 bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
493 bootstrap.remoteAddress(endpoint.host().toInetAddress(), endpoint.port());
Jordan Halterman66e6e3b2017-07-10 11:26:34 -0700494 if (enableNettyTls) {
495 bootstrap.handler(new SslClientCommunicationChannelInitializer());
496 } else {
497 bootstrap.handler(new BasicChannelInitializer());
498 }
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700499 return bootstrap;
500 }
501
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800502 private void startAcceptingConnections() throws InterruptedException {
503 ServerBootstrap b = new ServerBootstrap();
Jon Hall9a44d6a2017-03-02 18:14:37 -0800504 b.childOption(ChannelOption.WRITE_BUFFER_WATER_MARK,
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700505 new WriteBufferWaterMark(8 * 1024, 32 * 1024));
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800506 b.option(ChannelOption.SO_RCVBUF, 1048576);
507 b.option(ChannelOption.TCP_NODELAY, true);
Yuta HIGUCHIb47c9532016-08-22 09:41:23 -0700508 b.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800509 b.group(serverGroup, clientGroup);
510 b.channel(serverChannelClass);
511 if (enableNettyTls) {
512 b.childHandler(new SslServerCommunicationChannelInitializer());
513 } else {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700514 b.childHandler(new BasicChannelInitializer());
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800515 }
516 b.option(ChannelOption.SO_BACKLOG, 128);
517 b.childOption(ChannelOption.SO_KEEPALIVE, true);
518
519 // Bind and start to accept incoming connections.
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700520 b.bind(localEndpoint.port()).sync().addListener(future -> {
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800521 if (future.isSuccess()) {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700522 log.info("{} accepting incoming connections on port {}",
523 localEndpoint.host(), localEndpoint.port());
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800524 } else {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700525 log.warn("{} failed to bind to port {} due to {}",
526 localEndpoint.host(), localEndpoint.port(), future.cause());
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800527 }
528 });
529 }
530
Jordan Halterman66e6e3b2017-07-10 11:26:34 -0700531 private CompletableFuture<Channel> openChannel(Endpoint ep) {
532 Bootstrap bootstrap = bootstrapClient(ep);
533 CompletableFuture<Channel> retFuture = new CompletableFuture<>();
534 ChannelFuture f = bootstrap.connect();
535
536 f.addListener(future -> {
537 if (future.isSuccess()) {
538 retFuture.complete(f.channel());
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800539 } else {
Jordan Halterman66e6e3b2017-07-10 11:26:34 -0700540 retFuture.completeExceptionally(future.cause());
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800541 }
Jordan Halterman66e6e3b2017-07-10 11:26:34 -0700542 });
543 log.debug("Established a new connection to {}", ep);
544 return retFuture;
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800545 }
546
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700547 /**
548 * Channel initializer for TLS servers.
549 */
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800550 private class SslServerCommunicationChannelInitializer extends ChannelInitializer<SocketChannel> {
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800551 private final ChannelHandler dispatcher = new InboundMessageDispatcher();
552 private final ChannelHandler encoder = new MessageEncoder(preamble);
553
554 @Override
555 protected void initChannel(SocketChannel channel) throws Exception {
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800556 SSLContext serverContext = SSLContext.getInstance("TLS");
Brian O'Connor740e98c2017-06-29 17:07:17 -0700557 serverContext.init(keyManager.getKeyManagers(), trustManager.getTrustManagers(), null);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800558
559 SSLEngine serverSslEngine = serverContext.createSSLEngine();
560
561 serverSslEngine.setNeedClientAuth(true);
562 serverSslEngine.setUseClientMode(false);
563 serverSslEngine.setEnabledProtocols(serverSslEngine.getSupportedProtocols());
564 serverSslEngine.setEnabledCipherSuites(serverSslEngine.getSupportedCipherSuites());
565 serverSslEngine.setEnableSessionCreation(true);
566
567 channel.pipeline().addLast("ssl", new io.netty.handler.ssl.SslHandler(serverSslEngine))
568 .addLast("encoder", encoder)
Madan Jampanib825aeb2016-04-01 15:18:25 -0700569 .addLast("decoder", new MessageDecoder())
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800570 .addLast("handler", dispatcher);
571 }
572 }
573
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700574 /**
575 * Channel initializer for TLS clients.
576 */
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800577 private class SslClientCommunicationChannelInitializer extends ChannelInitializer<SocketChannel> {
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800578 private final ChannelHandler dispatcher = new InboundMessageDispatcher();
579 private final ChannelHandler encoder = new MessageEncoder(preamble);
580
581 @Override
582 protected void initChannel(SocketChannel channel) throws Exception {
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800583 SSLContext clientContext = SSLContext.getInstance("TLS");
Brian O'Connor740e98c2017-06-29 17:07:17 -0700584 clientContext.init(keyManager.getKeyManagers(), trustManager.getTrustManagers(), null);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800585
586 SSLEngine clientSslEngine = clientContext.createSSLEngine();
587
588 clientSslEngine.setUseClientMode(true);
589 clientSslEngine.setEnabledProtocols(clientSslEngine.getSupportedProtocols());
590 clientSslEngine.setEnabledCipherSuites(clientSslEngine.getSupportedCipherSuites());
591 clientSslEngine.setEnableSessionCreation(true);
592
593 channel.pipeline().addLast("ssl", new io.netty.handler.ssl.SslHandler(clientSslEngine))
594 .addLast("encoder", encoder)
Madan Jampanib825aeb2016-04-01 15:18:25 -0700595 .addLast("decoder", new MessageDecoder())
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800596 .addLast("handler", dispatcher);
597 }
598 }
599
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700600 /**
601 * Channel initializer for basic connections.
602 */
603 private class BasicChannelInitializer extends ChannelInitializer<SocketChannel> {
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800604 private final ChannelHandler dispatcher = new InboundMessageDispatcher();
605 private final ChannelHandler encoder = new MessageEncoder(preamble);
606
607 @Override
608 protected void initChannel(SocketChannel channel) throws Exception {
609 channel.pipeline()
610 .addLast("encoder", encoder)
Madan Jampanib825aeb2016-04-01 15:18:25 -0700611 .addLast("decoder", new MessageDecoder())
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800612 .addLast("handler", dispatcher);
613 }
614 }
615
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700616 /**
617 * Channel inbound handler that dispatches messages to the appropriate handler.
618 */
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800619 @ChannelHandler.Sharable
Yuta HIGUCHIc012dda2016-08-17 00:43:46 -0700620 private class InboundMessageDispatcher extends SimpleChannelInboundHandler<Object> {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700621 // Effectively SimpleChannelInboundHandler<InternalMessage>,
622 // had to specify <Object> to avoid Class Loader not being able to find some classes.
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800623
624 @Override
Yuta HIGUCHIc012dda2016-08-17 00:43:46 -0700625 protected void channelRead0(ChannelHandlerContext ctx, Object rawMessage) throws Exception {
626 InternalMessage message = (InternalMessage) rawMessage;
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800627 try {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700628 if (message.isRequest()) {
629 RemoteServerConnection connection =
630 serverConnections.computeIfAbsent(ctx.channel(), RemoteServerConnection::new);
631 connection.dispatch(message);
632 } else {
633 RemoteClientConnection connection =
634 clientConnections.computeIfAbsent(ctx.channel(), RemoteClientConnection::new);
635 connection.dispatch(message);
636 }
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800637 } catch (RejectedExecutionException e) {
638 log.warn("Unable to dispatch message due to {}", e.getMessage());
639 }
640 }
641
642 @Override
643 public void exceptionCaught(ChannelHandlerContext context, Throwable cause) {
644 log.error("Exception inside channel handling pipeline.", cause);
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700645
646 RemoteClientConnection clientConnection = clientConnections.remove(context.channel());
647 if (clientConnection != null) {
648 clientConnection.close();
649 }
650
651 RemoteServerConnection serverConnection = serverConnections.remove(context.channel());
652 if (serverConnection != null) {
653 serverConnection.close();
654 }
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800655 context.close();
656 }
Yuta HIGUCHIc012dda2016-08-17 00:43:46 -0700657
658 /**
659 * Returns true if the given message should be handled.
660 *
661 * @param msg inbound message
662 * @return true if {@code msg} is {@link InternalMessage} instance.
663 *
664 * @see SimpleChannelInboundHandler#acceptInboundMessage(Object)
665 */
666 @Override
667 public final boolean acceptInboundMessage(Object msg) {
668 return msg instanceof InternalMessage;
669 }
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800670 }
Yuta HIGUCHIc012dda2016-08-17 00:43:46 -0700671
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700672 /**
673 * Wraps a {@link CompletableFuture} and tracks its type and creation time.
674 */
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800675 private final class Callback {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700676 private final String type;
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800677 private final CompletableFuture<byte[]> future;
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700678 private final long time = System.currentTimeMillis();
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800679
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700680 Callback(String type, CompletableFuture<byte[]> future) {
681 this.type = type;
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800682 this.future = future;
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800683 }
684
685 public void complete(byte[] value) {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700686 future.complete(value);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800687 }
688
689 public void completeExceptionally(Throwable error) {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700690 future.completeExceptionally(error);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800691 }
692 }
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800693
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700694 /**
695 * Represents the client side of a connection to a local or remote server.
696 */
697 private interface ClientConnection {
698
699 /**
700 * Sends a message to the other side of the connection.
701 *
702 * @param message the message to send
703 * @return a completable future to be completed once the message has been sent
704 */
705 CompletableFuture<Void> sendAsync(InternalMessage message);
706
707 /**
708 * Sends a message to the other side of the connection, awaiting a reply.
709 *
710 * @param message the message to send
711 * @return a completable future to be completed once a reply is received or the request times out
712 */
713 CompletableFuture<byte[]> sendAndReceive(InternalMessage message);
714
715 /**
716 * Closes the connection.
717 */
718 default void close() {
719 }
720 }
721
722 /**
723 * Represents the server side of a connection.
724 */
725 private interface ServerConnection {
726
727 /**
728 * Sends a reply to the other side of the connection.
729 *
730 * @param message the message to which to reply
731 * @param status the reply status
732 * @param payload the response payload
733 */
734 void reply(InternalMessage message, Status status, Optional<byte[]> payload);
735
736 /**
737 * Closes the connection.
738 */
739 default void close() {
740 }
741 }
742
743 /**
744 * Local connection implementation.
745 */
746 private final class LocalClientConnection implements ClientConnection {
747 @Override
748 public CompletableFuture<Void> sendAsync(InternalMessage message) {
749 BiConsumer<InternalMessage, ServerConnection> handler = handlers.get(message.type());
750 if (handler != null) {
751 handler.accept(message, localServerConnection);
752 } else {
753 log.debug("No handler for message type {} from {}", message.type(), message.sender());
754 }
755 return CompletableFuture.completedFuture(null);
756 }
757
758 @Override
759 public CompletableFuture<byte[]> sendAndReceive(InternalMessage message) {
760 CompletableFuture<byte[]> future = new CompletableFuture<>();
761 BiConsumer<InternalMessage, ServerConnection> handler = handlers.get(message.type());
762 if (handler != null) {
763 handler.accept(message, new LocalServerConnection(future));
764 } else {
765 log.debug("No handler for message type {} from {}", message.type(), message.sender());
766 new LocalServerConnection(future).reply(message, Status.ERROR_NO_HANDLER, Optional.empty());
767 }
768 return future;
769 }
770 }
771
772 /**
773 * Local server connection.
774 */
775 private final class LocalServerConnection implements ServerConnection {
776 private final CompletableFuture<byte[]> future;
777
778 LocalServerConnection(CompletableFuture<byte[]> future) {
779 this.future = future;
780 }
781
782 @Override
783 public void reply(InternalMessage message, Status status, Optional<byte[]> payload) {
784 if (future != null) {
785 if (status == Status.OK) {
786 future.complete(payload.orElse(EMPTY_PAYLOAD));
787 } else if (status == Status.ERROR_NO_HANDLER) {
788 future.completeExceptionally(new MessagingException.NoRemoteHandler());
789 } else if (status == Status.ERROR_HANDLER_EXCEPTION) {
790 future.completeExceptionally(new MessagingException.RemoteHandlerFailure());
791 } else if (status == Status.PROTOCOL_EXCEPTION) {
792 future.completeExceptionally(new MessagingException.ProtocolException());
793 }
794 }
795 }
796 }
797
798 /**
799 * Remote connection implementation.
800 */
801 private final class RemoteClientConnection implements ClientConnection {
802 private final Channel channel;
803 private final Map<Long, Callback> futures = Maps.newConcurrentMap();
804 private final AtomicBoolean closed = new AtomicBoolean(false);
Jordan Halterman66e6e3b2017-07-10 11:26:34 -0700805 private final Cache<String, TimeoutHistory> timeoutHistories = CacheBuilder.newBuilder()
806 .expireAfterAccess(HISTORY_EXPIRE_MILLIS, TimeUnit.MILLISECONDS)
807 .build();
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700808
809 RemoteClientConnection(Channel channel) {
810 this.channel = channel;
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800811 }
812
813 /**
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700814 * Times out callbacks for this connection.
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800815 */
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700816 private void timeoutCallbacks() {
817 // Store the current time.
818 long currentTime = System.currentTimeMillis();
819
820 // Iterate through future callbacks and time out callbacks that have been alive
821 // longer than the current timeout according to the message type.
822 Iterator<Map.Entry<Long, Callback>> iterator = futures.entrySet().iterator();
823 while (iterator.hasNext()) {
824 Callback callback = iterator.next().getValue();
825 try {
826 TimeoutHistory timeoutHistory = timeoutHistories.get(callback.type, TimeoutHistory::new);
827 long currentTimeout = timeoutHistory.currentTimeout;
828 if (currentTime - callback.time > currentTimeout) {
829 iterator.remove();
830 long elapsedTime = currentTime - callback.time;
831 timeoutHistory.addReplyTime(elapsedTime);
832 callback.completeExceptionally(
833 new TimeoutException("Request timed out in " + elapsedTime + " milliseconds"));
834 }
835 } catch (ExecutionException e) {
836 throw new AssertionError();
837 }
838 }
Jordan Halterman66e6e3b2017-07-10 11:26:34 -0700839
840 // Iterate through all timeout histories and recompute the timeout.
841 for (TimeoutHistory timeoutHistory : timeoutHistories.asMap().values()) {
842 timeoutHistory.recomputeTimeoutMillis();
843 }
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700844 }
845
846 @Override
847 public CompletableFuture<Void> sendAsync(InternalMessage message) {
848 CompletableFuture<Void> future = new CompletableFuture<>();
849 channel.writeAndFlush(message).addListener(channelFuture -> {
850 if (!channelFuture.isSuccess()) {
851 future.completeExceptionally(channelFuture.cause());
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800852 } else {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700853 future.complete(null);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800854 }
855 });
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700856 return future;
857 }
858
859 @Override
860 public CompletableFuture<byte[]> sendAndReceive(InternalMessage message) {
861 CompletableFuture<byte[]> future = new CompletableFuture<>();
862 Callback callback = new Callback(message.type(), future);
863 futures.put(message.id(), callback);
864 channel.writeAndFlush(message).addListener(channelFuture -> {
865 if (!channelFuture.isSuccess()) {
866 futures.remove(message.id());
867 callback.completeExceptionally(channelFuture.cause());
868 }
869 });
870 return future;
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800871 }
872
873 /**
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700874 * Dispatches a message to a local handler.
875 *
876 * @param message the message to dispatch
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800877 */
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700878 private void dispatch(InternalMessage message) {
879 if (message.preamble() != preamble) {
880 log.debug("Received {} with invalid preamble from {}", message.type(), message.sender());
881 return;
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800882 }
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700883
884 clockService.recordEventTime(message.time());
885
886 Callback callback = futures.remove(message.id());
887 if (callback != null) {
888 if (message.status() == Status.OK) {
889 callback.complete(message.payload());
890 } else if (message.status() == Status.ERROR_NO_HANDLER) {
891 callback.completeExceptionally(new MessagingException.NoRemoteHandler());
892 } else if (message.status() == Status.ERROR_HANDLER_EXCEPTION) {
893 callback.completeExceptionally(new MessagingException.RemoteHandlerFailure());
894 } else if (message.status() == Status.PROTOCOL_EXCEPTION) {
895 callback.completeExceptionally(new MessagingException.ProtocolException());
896 }
897
898 try {
899 TimeoutHistory timeoutHistory = timeoutHistories.get(callback.type, TimeoutHistory::new);
900 timeoutHistory.addReplyTime(System.currentTimeMillis() - callback.time);
901 } catch (ExecutionException e) {
902 throw new AssertionError();
903 }
904 } else {
905 log.debug("Received a reply for message id:[{}]. "
906 + " from {}. But was unable to locate the"
907 + " request handle", message.id(), message.sender());
908 }
909 }
910
911 @Override
912 public void close() {
913 if (closed.compareAndSet(false, true)) {
914 timeoutFuture.cancel(false);
915 for (Callback callback : futures.values()) {
916 callback.completeExceptionally(new ConnectException());
917 }
918 }
919 }
920 }
921
922 /**
923 * Remote server connection.
924 */
925 private final class RemoteServerConnection implements ServerConnection {
926 private final Channel channel;
927
928 RemoteServerConnection(Channel channel) {
929 this.channel = channel;
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800930 }
931
932 /**
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700933 * Dispatches a message to a local handler.
934 *
935 * @param message the message to dispatch
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800936 */
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700937 private void dispatch(InternalMessage message) {
938 if (message.preamble() != preamble) {
939 log.debug("Received {} with invalid preamble from {}", message.type(), message.sender());
940 reply(message, Status.PROTOCOL_EXCEPTION, Optional.empty());
941 return;
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800942 }
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700943
944 clockService.recordEventTime(message.time());
945
946 BiConsumer<InternalMessage, ServerConnection> handler = handlers.get(message.type());
947 if (handler != null) {
948 handler.accept(message, this);
949 } else {
950 log.debug("No handler for message type {} from {}", message.type(), message.sender());
951 reply(message, Status.ERROR_NO_HANDLER, Optional.empty());
952 }
953 }
954
955 @Override
956 public void reply(InternalMessage message, Status status, Optional<byte[]> payload) {
957 InternalMessage response = new InternalMessage(preamble,
958 clockService.timeNow(),
959 message.id(),
960 localEndpoint,
961 payload.orElse(EMPTY_PAYLOAD),
962 status);
963 channel.writeAndFlush(response);
964 }
965 }
966
967 /**
968 * Request-reply timeout history tracker.
969 */
970 private static final class TimeoutHistory {
971 private final DescriptiveStatistics timeoutHistory = new SynchronizedDescriptiveStatistics(WINDOW_SIZE);
972 private final AtomicLong maxReplyTime = new AtomicLong();
973 private volatile long currentTimeout = DEFAULT_TIMEOUT_MILLIS;
974
975 /**
976 * Adds a reply time to the history.
977 *
978 * @param replyTime the reply time to add to the history
979 */
980 void addReplyTime(long replyTime) {
981 maxReplyTime.getAndAccumulate(replyTime, Math::max);
982 }
983
984 /**
985 * Computes the current timeout.
986 */
987 private void recomputeTimeoutMillis() {
988 double nextTimeout = maxReplyTime.getAndSet(0) * TIMEOUT_MULTIPLIER;
989 timeoutHistory.addValue(
990 Math.min(Math.max(nextTimeout, MIN_TIMEOUT_MILLIS), MAX_TIMEOUT_MILLIS));
991 if (timeoutHistory.getN() == WINDOW_SIZE) {
992 this.currentTimeout = (long) timeoutHistory.getMax();
993 }
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800994 }
995 }
JunHuy Lam39eb4292015-06-26 17:24:23 +0900996}