blob: 20c38e04a575bca376c14644a6f420273c975d91 [file] [log] [blame]
Thomas Vachuska58de4162015-09-10 16:15:33 -07001/*
Brian O'Connora09fe5b2017-08-03 21:12:30 -07002 * Copyright 2015-present Open Networking Foundation
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 Halterman5e32dc92018-01-13 14:10:56 -080052import java.util.function.Consumer;
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -070053import java.util.function.Function;
Aaron Kruglikov1b727382016-02-09 16:17:47 -080054
Jordan Halterman5e32dc92018-01-13 14:10:56 -080055import com.google.common.base.Throwables;
Jordan Halterman66e6e3b2017-07-10 11:26:34 -070056import com.google.common.cache.Cache;
57import com.google.common.cache.CacheBuilder;
58import com.google.common.collect.Lists;
59import com.google.common.collect.Maps;
60import com.google.common.util.concurrent.MoreExecutors;
61import io.netty.bootstrap.Bootstrap;
62import io.netty.bootstrap.ServerBootstrap;
63import io.netty.buffer.PooledByteBufAllocator;
64import io.netty.channel.Channel;
65import io.netty.channel.ChannelFuture;
66import io.netty.channel.ChannelHandler;
67import io.netty.channel.ChannelHandlerContext;
68import io.netty.channel.ChannelInitializer;
69import io.netty.channel.ChannelOption;
70import io.netty.channel.EventLoopGroup;
71import io.netty.channel.ServerChannel;
72import io.netty.channel.SimpleChannelInboundHandler;
73import io.netty.channel.WriteBufferWaterMark;
74import io.netty.channel.epoll.EpollEventLoopGroup;
75import io.netty.channel.epoll.EpollServerSocketChannel;
76import io.netty.channel.epoll.EpollSocketChannel;
77import io.netty.channel.nio.NioEventLoopGroup;
78import io.netty.channel.socket.SocketChannel;
79import io.netty.channel.socket.nio.NioServerSocketChannel;
80import io.netty.channel.socket.nio.NioSocketChannel;
81import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics;
82import org.apache.commons.math3.stat.descriptive.SynchronizedDescriptiveStatistics;
83import org.apache.felix.scr.annotations.Activate;
84import org.apache.felix.scr.annotations.Component;
85import org.apache.felix.scr.annotations.Deactivate;
86import org.apache.felix.scr.annotations.Reference;
87import org.apache.felix.scr.annotations.ReferenceCardinality;
88import org.apache.felix.scr.annotations.Service;
89import org.onosproject.cluster.ClusterMetadataService;
90import org.onosproject.cluster.ControllerNode;
91import org.onosproject.core.HybridLogicalClockService;
92import org.onosproject.store.cluster.messaging.Endpoint;
93import org.onosproject.store.cluster.messaging.MessagingException;
94import org.onosproject.store.cluster.messaging.MessagingService;
Jordan Halterman66e6e3b2017-07-10 11:26:34 -070095import org.slf4j.Logger;
96import org.slf4j.LoggerFactory;
97
Yuta HIGUCHI90a16892016-07-20 20:36:08 -070098import static org.onlab.util.Tools.groupedThreads;
Heedo Kang4a47a302016-02-29 17:40:23 +090099import static org.onosproject.security.AppGuard.checkPermission;
100import static org.onosproject.security.AppPermission.Type.CLUSTER_WRITE;
101
Madan Jampaniafeebbd2015-05-19 15:26:01 -0700102/**
103 * Netty based MessagingService.
104 */
Sho SHIMIZU5c396e32016-08-12 15:19:12 -0700105@Component(immediate = true)
Madan Jampaniafeebbd2015-05-19 15:26:01 -0700106@Service
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800107public class NettyMessagingManager implements MessagingService {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700108 private static final long DEFAULT_TIMEOUT_MILLIS = 500;
Jordan Halterman66e6e3b2017-07-10 11:26:34 -0700109 private static final long HISTORY_EXPIRE_MILLIS = Duration.ofMinutes(1).toMillis();
Jordan Halterman5a5ed592017-09-12 15:09:03 -0700110 private static final long MIN_TIMEOUT_MILLIS = 250;
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700111 private static final long MAX_TIMEOUT_MILLIS = 5000;
112 private static final long TIMEOUT_INTERVAL = 50;
113 private static final int WINDOW_SIZE = 100;
114 private static final double TIMEOUT_MULTIPLIER = 2.5;
Jordan Halterman66e6e3b2017-07-10 11:26:34 -0700115 private static final int CHANNEL_POOL_SIZE = 8;
Madan Jampaniafeebbd2015-05-19 15:26:01 -0700116
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700117 private static final byte[] EMPTY_PAYLOAD = new byte[0];
118
Madan Jampaniafeebbd2015-05-19 15:26:01 -0700119 private final Logger log = LoggerFactory.getLogger(getClass());
120
Jordan Haltermanfe2f93d2017-12-08 23:52:54 -0800121 private final LocalClientConnection localClientConnection = new LocalClientConnection();
122 private final LocalServerConnection localServerConnection = new LocalServerConnection(null);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800123
Brian O'Connor740e98c2017-06-29 17:07:17 -0700124 //TODO CONFIG_DIR is duplicated from ConfigFileBasedClusterMetadataProvider
125 private static final String CONFIG_DIR = "../config";
126 private static final String KS_FILE_NAME = "onos.jks";
127 private static final File DEFAULT_KS_FILE = new File(CONFIG_DIR, KS_FILE_NAME);
128 private static final String DEFAULT_KS_PASSWORD = "changeit";
129
Madan Jampani05833872016-07-12 23:01:39 -0700130 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
131 protected HybridLogicalClockService clockService;
132
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700133 private Endpoint localEndpoint;
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800134 private int preamble;
135 private final AtomicBoolean started = new AtomicBoolean(false);
Jordan Haltermane3813a92017-07-29 14:10:31 -0700136 private final Map<String, BiConsumer<InternalRequest, ServerConnection>> handlers = new ConcurrentHashMap<>();
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700137 private final Map<Channel, RemoteClientConnection> clientConnections = Maps.newConcurrentMap();
138 private final Map<Channel, RemoteServerConnection> serverConnections = Maps.newConcurrentMap();
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800139 private final AtomicLong messageIdGenerator = new AtomicLong(0);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800140
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700141 private ScheduledFuture<?> timeoutFuture;
142
Jordan Halterman66e6e3b2017-07-10 11:26:34 -0700143 private final Map<Endpoint, List<CompletableFuture<Channel>>> channels = Maps.newConcurrentMap();
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800144
145 private EventLoopGroup serverGroup;
146 private EventLoopGroup clientGroup;
147 private Class<? extends ServerChannel> serverChannelClass;
148 private Class<? extends Channel> clientChannelClass;
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700149 private ScheduledExecutorService timeoutExecutor;
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800150
Brian O'Connor740e98c2017-06-29 17:07:17 -0700151 protected static final boolean TLS_ENABLED = true;
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800152 protected static final boolean TLS_DISABLED = false;
Brian O'Connor740e98c2017-06-29 17:07:17 -0700153 protected boolean enableNettyTls = TLS_ENABLED;
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800154
Brian O'Connor740e98c2017-06-29 17:07:17 -0700155 protected TrustManagerFactory trustManager;
156 protected KeyManagerFactory keyManager;
JunHuy Lam39eb4292015-06-26 17:24:23 +0900157
Madan Jampaniafeebbd2015-05-19 15:26:01 -0700158 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Madan Jampaniec1df022015-10-13 21:23:03 -0700159 protected ClusterMetadataService clusterMetadataService;
Madan Jampaniafeebbd2015-05-19 15:26:01 -0700160
161 @Activate
162 public void activate() throws Exception {
Madan Jampaniec1df022015-10-13 21:23:03 -0700163 ControllerNode localNode = clusterMetadataService.getLocalNode();
Jonathan Hartd9df7bd2015-11-10 17:10:25 -0800164 getTlsParameters();
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800165
166 if (started.get()) {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700167 log.warn("Already running at local endpoint: {}", localEndpoint);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800168 return;
169 }
170 this.preamble = clusterMetadataService.getClusterMetadata().getName().hashCode();
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700171 this.localEndpoint = new Endpoint(localNode.ip(), localNode.tcpPort());
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800172 initEventLoopGroup();
173 startAcceptingConnections();
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700174 timeoutExecutor = Executors.newSingleThreadScheduledExecutor(
175 groupedThreads("NettyMessagingEvt", "timeout", log));
176 timeoutFuture = timeoutExecutor.scheduleAtFixedRate(
177 this::timeoutAllCallbacks, TIMEOUT_INTERVAL, TIMEOUT_INTERVAL, TimeUnit.MILLISECONDS);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800178 started.set(true);
Madan Jampaniafeebbd2015-05-19 15:26:01 -0700179 log.info("Started");
180 }
181
182 @Deactivate
183 public void deactivate() throws Exception {
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800184 if (started.get()) {
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800185 serverGroup.shutdownGracefully();
186 clientGroup.shutdownGracefully();
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700187 timeoutFuture.cancel(false);
188 timeoutExecutor.shutdown();
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800189 started.set(false);
190 }
Madan Jampaniafeebbd2015-05-19 15:26:01 -0700191 log.info("Stopped");
192 }
JunHuy Lam39eb4292015-06-26 17:24:23 +0900193
Jonathan Hartd9df7bd2015-11-10 17:10:25 -0800194 private void getTlsParameters() {
Brian O'Connor740e98c2017-06-29 17:07:17 -0700195 // default is TLS enabled unless key stores cannot be loaded
196 enableNettyTls = Boolean.parseBoolean(System.getProperty("enableNettyTLS", Boolean.toString(TLS_ENABLED)));
197
Jonathan Hartd9df7bd2015-11-10 17:10:25 -0800198 if (enableNettyTls) {
Brian O'Connor740e98c2017-06-29 17:07:17 -0700199 enableNettyTls = loadKeyStores();
200 }
201 }
202
203 private boolean loadKeyStores() {
204 // Maintain a local copy of the trust and key managers in case anything goes wrong
205 TrustManagerFactory tmf;
206 KeyManagerFactory kmf;
207 try {
208 String ksLocation = System.getProperty("javax.net.ssl.keyStore", DEFAULT_KS_FILE.toString());
209 String tsLocation = System.getProperty("javax.net.ssl.trustStore", DEFAULT_KS_FILE.toString());
210 char[] ksPwd = System.getProperty("javax.net.ssl.keyStorePassword", DEFAULT_KS_PASSWORD).toCharArray();
211 char[] tsPwd = System.getProperty("javax.net.ssl.trustStorePassword", DEFAULT_KS_PASSWORD).toCharArray();
212
213 tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
214 KeyStore ts = KeyStore.getInstance("JKS");
215 ts.load(new FileInputStream(tsLocation), tsPwd);
216 tmf.init(ts);
217
218 kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
219 KeyStore ks = KeyStore.getInstance("JKS");
220 ks.load(new FileInputStream(ksLocation), ksPwd);
221 kmf.init(ks, ksPwd);
222 if (log.isInfoEnabled()) {
223 logKeyStore(ks, ksLocation, ksPwd);
JunHuy Lam39eb4292015-06-26 17:24:23 +0900224 }
Brian O'Connor740e98c2017-06-29 17:07:17 -0700225 } catch (FileNotFoundException e) {
226 log.warn("Disabling TLS for intra-cluster messaging; Could not load cluster key store: {}", e.getMessage());
227 return TLS_DISABLED;
228 } catch (Exception e) {
229 //TODO we might want to catch exceptions more specifically
230 log.error("Error loading key store; disabling TLS for intra-cluster messaging", e);
231 return TLS_DISABLED;
232 }
233 this.trustManager = tmf;
234 this.keyManager = kmf;
235 return TLS_ENABLED;
236 }
237
238 private void logKeyStore(KeyStore ks, String ksLocation, char[] ksPwd) {
239 if (log.isInfoEnabled()) {
240 log.info("Loaded cluster key store from: {}", ksLocation);
241 try {
242 for (Enumeration<String> e = ks.aliases(); e.hasMoreElements();) {
243 String alias = e.nextElement();
244 Key key = ks.getKey(alias, ksPwd);
245 Certificate[] certs = ks.getCertificateChain(alias);
246 log.debug("{} -> {}", alias, certs);
247 final byte[] encodedKey;
248 if (certs != null && certs.length > 0) {
249 encodedKey = certs[0].getEncoded();
250 } else {
251 log.info("Could not find cert chain for {}, using fingerprint of key instead...", alias);
252 encodedKey = key.getEncoded();
253 }
254 // Compute the certificate's fingerprint (use the key if certificate cannot be found)
255 MessageDigest digest = MessageDigest.getInstance("SHA1");
256 digest.update(encodedKey);
257 StringJoiner fingerprint = new StringJoiner(":");
258 for (byte b : digest.digest()) {
259 fingerprint.add(String.format("%02X", b));
260 }
261 log.info("{} -> {}", alias, fingerprint);
262 }
263 } catch (Exception e) {
264 log.warn("Unable to print contents of key store: {}", ksLocation, e);
JunHuy Lam39eb4292015-06-26 17:24:23 +0900265 }
266 }
267 }
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700268
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800269 private void initEventLoopGroup() {
270 // try Epoll first and if that does work, use nio.
271 try {
Yuta HIGUCHI90a16892016-07-20 20:36:08 -0700272 clientGroup = new EpollEventLoopGroup(0, groupedThreads("NettyMessagingEvt", "epollC-%d", log));
273 serverGroup = new EpollEventLoopGroup(0, groupedThreads("NettyMessagingEvt", "epollS-%d", log));
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800274 serverChannelClass = EpollServerSocketChannel.class;
275 clientChannelClass = EpollSocketChannel.class;
276 return;
277 } catch (Throwable e) {
278 log.debug("Failed to initialize native (epoll) transport. "
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700279 + "Reason: {}. Proceeding with nio.", e.getMessage());
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800280 }
Yuta HIGUCHI90a16892016-07-20 20:36:08 -0700281 clientGroup = new NioEventLoopGroup(0, groupedThreads("NettyMessagingEvt", "nioC-%d", log));
282 serverGroup = new NioEventLoopGroup(0, groupedThreads("NettyMessagingEvt", "nioS-%d", log));
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800283 serverChannelClass = NioServerSocketChannel.class;
284 clientChannelClass = NioSocketChannel.class;
285 }
286
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700287 /**
288 * Times out response callbacks.
289 */
290 private void timeoutAllCallbacks() {
291 // Iterate through all connections and time out callbacks.
Jordan Haltermanfe2f93d2017-12-08 23:52:54 -0800292 localClientConnection.timeoutCallbacks();
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700293 for (RemoteClientConnection connection : clientConnections.values()) {
294 connection.timeoutCallbacks();
295 }
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700296 }
297
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800298 @Override
299 public CompletableFuture<Void> sendAsync(Endpoint ep, String type, byte[] payload) {
Heedo Kang4a47a302016-02-29 17:40:23 +0900300 checkPermission(CLUSTER_WRITE);
Jordan Haltermane3813a92017-07-29 14:10:31 -0700301 InternalRequest message = new InternalRequest(preamble,
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700302 clockService.timeNow(),
303 messageIdGenerator.incrementAndGet(),
304 localEndpoint,
305 type,
306 payload);
Jordan Halterman66e6e3b2017-07-10 11:26:34 -0700307 return executeOnPooledConnection(ep, type, c -> c.sendAsync(message), MoreExecutors.directExecutor());
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800308 }
309
310 @Override
311 public CompletableFuture<byte[]> sendAndReceive(Endpoint ep, String type, byte[] payload) {
Heedo Kang4a47a302016-02-29 17:40:23 +0900312 checkPermission(CLUSTER_WRITE);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800313 return sendAndReceive(ep, type, payload, MoreExecutors.directExecutor());
314 }
315
316 @Override
317 public CompletableFuture<byte[]> sendAndReceive(Endpoint ep, String type, byte[] payload, Executor executor) {
Heedo Kang4a47a302016-02-29 17:40:23 +0900318 checkPermission(CLUSTER_WRITE);
Jordan Haltermanb34d30b2017-08-28 15:35:03 -0700319 long messageId = messageIdGenerator.incrementAndGet();
Jordan Haltermane3813a92017-07-29 14:10:31 -0700320 InternalRequest message = new InternalRequest(preamble,
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700321 clockService.timeNow(),
322 messageId,
323 localEndpoint,
324 type,
325 payload);
Jordan Halterman66e6e3b2017-07-10 11:26:34 -0700326 return executeOnPooledConnection(ep, type, c -> c.sendAndReceive(message), executor);
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700327 }
Jordan Halterman041534b2017-03-21 10:37:33 -0700328
Jordan Halterman66e6e3b2017-07-10 11:26:34 -0700329 private List<CompletableFuture<Channel>> getChannelPool(Endpoint endpoint) {
330 return channels.computeIfAbsent(endpoint, e -> {
331 List<CompletableFuture<Channel>> defaultList = new ArrayList<>(CHANNEL_POOL_SIZE);
332 for (int i = 0; i < CHANNEL_POOL_SIZE; i++) {
333 defaultList.add(null);
334 }
335 return Lists.newCopyOnWriteArrayList(defaultList);
336 });
337 }
338
339 private int getChannelOffset(String messageType) {
340 return Math.abs(messageType.hashCode() % CHANNEL_POOL_SIZE);
341 }
342
Ray Milkey8df1f442018-01-23 23:32:20 +0000343 private <T> CompletableFuture<T> executeOnPooledConnection(
344 Endpoint endpoint,
345 String type,
346 Function<ClientConnection, CompletableFuture<T>> callback,
347 Executor executor) {
348 CompletableFuture<T> future = new CompletableFuture<T>();
349 executeOnPooledConnection(endpoint, type, callback, executor, future);
350 return future;
351 }
352
353 private <T> void executeOnPooledConnection(
Jordan Halterman5e32dc92018-01-13 14:10:56 -0800354 Endpoint endpoint,
355 String type,
356 Function<ClientConnection, CompletableFuture<T>> callback,
357 Executor executor,
358 CompletableFuture<T> future) {
359
360 // If the endpoint is the local node, avoid the loopback interface and use the singleton local connection.
Ray Milkey8df1f442018-01-23 23:32:20 +0000361 if (endpoint.equals(localEndpoint)) {
362 callback.apply(localClientConnection).whenComplete((result, error) -> {
363 if (error == null) {
364 executor.execute(() -> future.complete(result));
365 } else {
366 executor.execute(() -> future.completeExceptionally(error));
367 }
368 });
369 return;
370 }
371
Jordan Halterman5e32dc92018-01-13 14:10:56 -0800372 // Get the channel pool and the offset for this message type.
373 List<CompletableFuture<Channel>> channelPool = getChannelPool(endpoint);
374 int offset = getChannelOffset(type);
375
376 // If the channel future is completed exceptionally, open a new channel.
377 CompletableFuture<Channel> channelFuture = channelPool.get(offset);
378 if (channelFuture == null || channelFuture.isCompletedExceptionally()) {
379 synchronized (channelPool) {
380 channelFuture = channelPool.get(offset);
381 if (channelFuture == null || channelFuture.isCompletedExceptionally()) {
382 channelFuture = openChannel(endpoint);
383 channelPool.set(offset, channelFuture);
384 }
385 }
386 }
387
388 // Create a consumer with which to complete the send operation on a given channel.
389 final Consumer<Channel> runner = channel -> {
390 ClientConnection connection = clientConnections.computeIfAbsent(channel, RemoteClientConnection::new);
391 callback.apply(connection).whenComplete((result, sendError) -> {
392 if (sendError == null) {
393 executor.execute(() -> future.complete(result));
394 } else {
395 // If an exception other than a TimeoutException occurred, close the connection and
396 // remove the channel from the pool.
397 Throwable cause = Throwables.getRootCause(sendError);
398 if (!(cause instanceof TimeoutException) && !(cause instanceof MessagingException)) {
399 synchronized (channelPool) {
400 channelPool.set(offset, null);
401 }
402 channel.close();
403 clientConnections.remove(channel);
404 connection.close();
Ray Milkey8df1f442018-01-23 23:32:20 +0000405 }
Jordan Halterman5e32dc92018-01-13 14:10:56 -0800406 executor.execute(() -> future.completeExceptionally(sendError));
407 }
408 });
409 };
410
411 // Wait for the channel future to be completed. Once it's complete, if the channel is active then
412 // attempt to send the message. Otherwise, if the channel is inactive then attempt to open a new channel.
413 final CompletableFuture<Channel> finalFuture = channelFuture;
414 finalFuture.whenComplete((channel, error) -> {
415 if (error == null) {
416 if (!channel.isActive()) {
417 final CompletableFuture<Channel> currentFuture;
418 synchronized (channelPool) {
419 currentFuture = channelPool.get(offset);
420 if (currentFuture == finalFuture) {
421 channelPool.set(offset, null);
422 }
423 }
424 if (currentFuture == finalFuture) {
425 executeOnPooledConnection(endpoint, type, callback, executor);
426 } else {
427 currentFuture.whenComplete((recursiveResult, recursiveError) -> {
428 if (recursiveError == null) {
429 runner.accept(recursiveResult);
430 } else {
431 future.completeExceptionally(recursiveError);
432 }
433 });
434 }
435 } else {
436 runner.accept(channel);
437 }
Ray Milkey8df1f442018-01-23 23:32:20 +0000438 } else {
Jordan Halterman5e32dc92018-01-13 14:10:56 -0800439 future.completeExceptionally(error);
Ray Milkey8df1f442018-01-23 23:32:20 +0000440 }
441 });
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800442 }
443
444 @Override
445 public void registerHandler(String type, BiConsumer<Endpoint, byte[]> handler, Executor executor) {
Heedo Kang4a47a302016-02-29 17:40:23 +0900446 checkPermission(CLUSTER_WRITE);
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700447 handlers.put(type, (message, connection) -> executor.execute(() ->
448 handler.accept(message.sender(), message.payload())));
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800449 }
450
451 @Override
452 public void registerHandler(String type, BiFunction<Endpoint, byte[], byte[]> handler, Executor executor) {
Heedo Kang4a47a302016-02-29 17:40:23 +0900453 checkPermission(CLUSTER_WRITE);
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700454 handlers.put(type, (message, connection) -> executor.execute(() -> {
Madan Jampania9e70a62016-03-02 16:28:18 -0800455 byte[] responsePayload = null;
Jordan Haltermane3813a92017-07-29 14:10:31 -0700456 InternalReply.Status status = InternalReply.Status.OK;
Madan Jampania9e70a62016-03-02 16:28:18 -0800457 try {
458 responsePayload = handler.apply(message.sender(), message.payload());
459 } catch (Exception e) {
Jordan Haltermanb6ee9e92017-06-21 15:26:28 -0700460 log.debug("An error occurred in a message handler: {}", e);
Jordan Haltermane3813a92017-07-29 14:10:31 -0700461 status = InternalReply.Status.ERROR_HANDLER_EXCEPTION;
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800462 }
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700463 connection.reply(message, status, Optional.ofNullable(responsePayload));
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800464 }));
465 }
466
467 @Override
468 public void registerHandler(String type, BiFunction<Endpoint, byte[], CompletableFuture<byte[]>> handler) {
Heedo Kang4a47a302016-02-29 17:40:23 +0900469 checkPermission(CLUSTER_WRITE);
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700470 handlers.put(type, (message, connection) -> {
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800471 handler.apply(message.sender(), message.payload()).whenComplete((result, error) -> {
Jordan Haltermane3813a92017-07-29 14:10:31 -0700472 InternalReply.Status status;
Jordan Haltermanb6ee9e92017-06-21 15:26:28 -0700473 if (error == null) {
Jordan Haltermane3813a92017-07-29 14:10:31 -0700474 status = InternalReply.Status.OK;
Jordan Haltermanb6ee9e92017-06-21 15:26:28 -0700475 } else {
476 log.debug("An error occurred in a message handler: {}", error);
Jordan Haltermane3813a92017-07-29 14:10:31 -0700477 status = InternalReply.Status.ERROR_HANDLER_EXCEPTION;
Jordan Haltermanb6ee9e92017-06-21 15:26:28 -0700478 }
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700479 connection.reply(message, status, Optional.ofNullable(result));
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800480 });
481 });
482 }
483
484 @Override
485 public void unregisterHandler(String type) {
Heedo Kang4a47a302016-02-29 17:40:23 +0900486 checkPermission(CLUSTER_WRITE);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800487 handlers.remove(type);
488 }
489
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700490 private Bootstrap bootstrapClient(Endpoint endpoint) {
491 Bootstrap bootstrap = new Bootstrap();
492 bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
493 bootstrap.option(ChannelOption.WRITE_BUFFER_WATER_MARK,
494 new WriteBufferWaterMark(10 * 32 * 1024, 10 * 64 * 1024));
495 bootstrap.option(ChannelOption.SO_SNDBUF, 1048576);
496 bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000);
497 bootstrap.group(clientGroup);
498 // TODO: Make this faster:
499 // http://normanmaurer.me/presentations/2014-facebook-eng-netty/slides.html#37.0
500 bootstrap.channel(clientChannelClass);
501 bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
502 bootstrap.remoteAddress(endpoint.host().toInetAddress(), endpoint.port());
Jordan Halterman66e6e3b2017-07-10 11:26:34 -0700503 if (enableNettyTls) {
504 bootstrap.handler(new SslClientCommunicationChannelInitializer());
505 } else {
506 bootstrap.handler(new BasicChannelInitializer());
507 }
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700508 return bootstrap;
509 }
510
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800511 private void startAcceptingConnections() throws InterruptedException {
512 ServerBootstrap b = new ServerBootstrap();
Jon Hall9a44d6a2017-03-02 18:14:37 -0800513 b.childOption(ChannelOption.WRITE_BUFFER_WATER_MARK,
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700514 new WriteBufferWaterMark(8 * 1024, 32 * 1024));
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800515 b.option(ChannelOption.SO_RCVBUF, 1048576);
516 b.option(ChannelOption.TCP_NODELAY, true);
Yuta HIGUCHIb47c9532016-08-22 09:41:23 -0700517 b.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800518 b.group(serverGroup, clientGroup);
519 b.channel(serverChannelClass);
520 if (enableNettyTls) {
521 b.childHandler(new SslServerCommunicationChannelInitializer());
522 } else {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700523 b.childHandler(new BasicChannelInitializer());
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800524 }
525 b.option(ChannelOption.SO_BACKLOG, 128);
526 b.childOption(ChannelOption.SO_KEEPALIVE, true);
527
528 // Bind and start to accept incoming connections.
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700529 b.bind(localEndpoint.port()).sync().addListener(future -> {
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800530 if (future.isSuccess()) {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700531 log.info("{} accepting incoming connections on port {}",
532 localEndpoint.host(), localEndpoint.port());
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800533 } else {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700534 log.warn("{} failed to bind to port {} due to {}",
535 localEndpoint.host(), localEndpoint.port(), future.cause());
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800536 }
537 });
538 }
539
Jordan Halterman66e6e3b2017-07-10 11:26:34 -0700540 private CompletableFuture<Channel> openChannel(Endpoint ep) {
541 Bootstrap bootstrap = bootstrapClient(ep);
542 CompletableFuture<Channel> retFuture = new CompletableFuture<>();
543 ChannelFuture f = bootstrap.connect();
544
545 f.addListener(future -> {
546 if (future.isSuccess()) {
547 retFuture.complete(f.channel());
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800548 } else {
Jordan Halterman66e6e3b2017-07-10 11:26:34 -0700549 retFuture.completeExceptionally(future.cause());
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800550 }
Jordan Halterman66e6e3b2017-07-10 11:26:34 -0700551 });
552 log.debug("Established a new connection to {}", ep);
553 return retFuture;
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800554 }
555
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700556 /**
557 * Channel initializer for TLS servers.
558 */
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800559 private class SslServerCommunicationChannelInitializer extends ChannelInitializer<SocketChannel> {
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800560 private final ChannelHandler dispatcher = new InboundMessageDispatcher();
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800561
562 @Override
563 protected void initChannel(SocketChannel channel) throws Exception {
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800564 SSLContext serverContext = SSLContext.getInstance("TLS");
Brian O'Connor740e98c2017-06-29 17:07:17 -0700565 serverContext.init(keyManager.getKeyManagers(), trustManager.getTrustManagers(), null);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800566
567 SSLEngine serverSslEngine = serverContext.createSSLEngine();
568
569 serverSslEngine.setNeedClientAuth(true);
570 serverSslEngine.setUseClientMode(false);
571 serverSslEngine.setEnabledProtocols(serverSslEngine.getSupportedProtocols());
572 serverSslEngine.setEnabledCipherSuites(serverSslEngine.getSupportedCipherSuites());
573 serverSslEngine.setEnableSessionCreation(true);
574
575 channel.pipeline().addLast("ssl", new io.netty.handler.ssl.SslHandler(serverSslEngine))
Jordan Haltermane3813a92017-07-29 14:10:31 -0700576 .addLast("encoder", new MessageEncoder(localEndpoint, preamble))
Madan Jampanib825aeb2016-04-01 15:18:25 -0700577 .addLast("decoder", new MessageDecoder())
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800578 .addLast("handler", dispatcher);
579 }
580 }
581
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700582 /**
583 * Channel initializer for TLS clients.
584 */
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800585 private class SslClientCommunicationChannelInitializer extends ChannelInitializer<SocketChannel> {
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800586 private final ChannelHandler dispatcher = new InboundMessageDispatcher();
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800587
588 @Override
589 protected void initChannel(SocketChannel channel) throws Exception {
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800590 SSLContext clientContext = SSLContext.getInstance("TLS");
Brian O'Connor740e98c2017-06-29 17:07:17 -0700591 clientContext.init(keyManager.getKeyManagers(), trustManager.getTrustManagers(), null);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800592
593 SSLEngine clientSslEngine = clientContext.createSSLEngine();
594
595 clientSslEngine.setUseClientMode(true);
596 clientSslEngine.setEnabledProtocols(clientSslEngine.getSupportedProtocols());
597 clientSslEngine.setEnabledCipherSuites(clientSslEngine.getSupportedCipherSuites());
598 clientSslEngine.setEnableSessionCreation(true);
599
600 channel.pipeline().addLast("ssl", new io.netty.handler.ssl.SslHandler(clientSslEngine))
Jordan Haltermane3813a92017-07-29 14:10:31 -0700601 .addLast("encoder", new MessageEncoder(localEndpoint, preamble))
Madan Jampanib825aeb2016-04-01 15:18:25 -0700602 .addLast("decoder", new MessageDecoder())
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800603 .addLast("handler", dispatcher);
604 }
605 }
606
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700607 /**
608 * Channel initializer for basic connections.
609 */
610 private class BasicChannelInitializer extends ChannelInitializer<SocketChannel> {
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800611 private final ChannelHandler dispatcher = new InboundMessageDispatcher();
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800612
613 @Override
614 protected void initChannel(SocketChannel channel) throws Exception {
615 channel.pipeline()
Jordan Haltermane3813a92017-07-29 14:10:31 -0700616 .addLast("encoder", new MessageEncoder(localEndpoint, preamble))
Madan Jampanib825aeb2016-04-01 15:18:25 -0700617 .addLast("decoder", new MessageDecoder())
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800618 .addLast("handler", dispatcher);
619 }
620 }
621
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700622 /**
623 * Channel inbound handler that dispatches messages to the appropriate handler.
624 */
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800625 @ChannelHandler.Sharable
Yuta HIGUCHIc012dda2016-08-17 00:43:46 -0700626 private class InboundMessageDispatcher extends SimpleChannelInboundHandler<Object> {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700627 // Effectively SimpleChannelInboundHandler<InternalMessage>,
628 // had to specify <Object> to avoid Class Loader not being able to find some classes.
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800629
630 @Override
Yuta HIGUCHIc012dda2016-08-17 00:43:46 -0700631 protected void channelRead0(ChannelHandlerContext ctx, Object rawMessage) throws Exception {
632 InternalMessage message = (InternalMessage) rawMessage;
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800633 try {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700634 if (message.isRequest()) {
635 RemoteServerConnection connection =
636 serverConnections.computeIfAbsent(ctx.channel(), RemoteServerConnection::new);
Jordan Haltermane3813a92017-07-29 14:10:31 -0700637 connection.dispatch((InternalRequest) message);
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700638 } else {
639 RemoteClientConnection connection =
640 clientConnections.computeIfAbsent(ctx.channel(), RemoteClientConnection::new);
Jordan Haltermane3813a92017-07-29 14:10:31 -0700641 connection.dispatch((InternalReply) message);
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700642 }
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800643 } catch (RejectedExecutionException e) {
644 log.warn("Unable to dispatch message due to {}", e.getMessage());
645 }
646 }
647
648 @Override
649 public void exceptionCaught(ChannelHandlerContext context, Throwable cause) {
650 log.error("Exception inside channel handling pipeline.", cause);
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700651
652 RemoteClientConnection clientConnection = clientConnections.remove(context.channel());
653 if (clientConnection != null) {
654 clientConnection.close();
655 }
656
657 RemoteServerConnection serverConnection = serverConnections.remove(context.channel());
658 if (serverConnection != null) {
659 serverConnection.close();
660 }
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800661 context.close();
662 }
Yuta HIGUCHIc012dda2016-08-17 00:43:46 -0700663
Jordan Halterman5e32dc92018-01-13 14:10:56 -0800664 @Override
665 public void channelInactive(ChannelHandlerContext context) throws Exception {
666 RemoteClientConnection clientConnection = clientConnections.remove(context.channel());
667 if (clientConnection != null) {
668 clientConnection.close();
669 }
670
671 RemoteServerConnection serverConnection = serverConnections.remove(context.channel());
672 if (serverConnection != null) {
673 serverConnection.close();
674 }
675 context.close();
676 }
677
Yuta HIGUCHIc012dda2016-08-17 00:43:46 -0700678 /**
679 * Returns true if the given message should be handled.
680 *
681 * @param msg inbound message
682 * @return true if {@code msg} is {@link InternalMessage} instance.
Yuta HIGUCHIc012dda2016-08-17 00:43:46 -0700683 * @see SimpleChannelInboundHandler#acceptInboundMessage(Object)
684 */
685 @Override
686 public final boolean acceptInboundMessage(Object msg) {
687 return msg instanceof InternalMessage;
688 }
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800689 }
Yuta HIGUCHIc012dda2016-08-17 00:43:46 -0700690
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700691 /**
692 * Wraps a {@link CompletableFuture} and tracks its type and creation time.
693 */
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800694 private final class Callback {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700695 private final String type;
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800696 private final CompletableFuture<byte[]> future;
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700697 private final long time = System.currentTimeMillis();
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800698
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700699 Callback(String type, CompletableFuture<byte[]> future) {
700 this.type = type;
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800701 this.future = future;
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800702 }
703
704 public void complete(byte[] value) {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700705 future.complete(value);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800706 }
707
708 public void completeExceptionally(Throwable error) {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700709 future.completeExceptionally(error);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800710 }
711 }
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800712
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700713 /**
714 * Represents the client side of a connection to a local or remote server.
715 */
716 private interface ClientConnection {
717
718 /**
719 * Sends a message to the other side of the connection.
720 *
721 * @param message the message to send
722 * @return a completable future to be completed once the message has been sent
723 */
Jordan Haltermane3813a92017-07-29 14:10:31 -0700724 CompletableFuture<Void> sendAsync(InternalRequest message);
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700725
726 /**
727 * Sends a message to the other side of the connection, awaiting a reply.
728 *
729 * @param message the message to send
730 * @return a completable future to be completed once a reply is received or the request times out
731 */
Jordan Haltermane3813a92017-07-29 14:10:31 -0700732 CompletableFuture<byte[]> sendAndReceive(InternalRequest message);
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700733
734 /**
735 * Closes the connection.
736 */
737 default void close() {
738 }
739 }
740
741 /**
742 * Represents the server side of a connection.
743 */
744 private interface ServerConnection {
745
746 /**
747 * Sends a reply to the other side of the connection.
748 *
749 * @param message the message to which to reply
Jordan Haltermanfe2f93d2017-12-08 23:52:54 -0800750 * @param status the reply status
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700751 * @param payload the response payload
752 */
Jordan Haltermane3813a92017-07-29 14:10:31 -0700753 void reply(InternalRequest message, InternalReply.Status status, Optional<byte[]> payload);
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700754
755 /**
756 * Closes the connection.
757 */
758 default void close() {
759 }
760 }
761
762 /**
Jordan Haltermanfe2f93d2017-12-08 23:52:54 -0800763 * Remote connection implementation.
764 */
765 private abstract class AbstractClientConnection implements ClientConnection {
766 private final Map<Long, Callback> futures = Maps.newConcurrentMap();
767 private final AtomicBoolean closed = new AtomicBoolean(false);
768 private final Cache<String, TimeoutHistory> timeoutHistories = CacheBuilder.newBuilder()
769 .expireAfterAccess(HISTORY_EXPIRE_MILLIS, TimeUnit.MILLISECONDS)
770 .build();
771
772 /**
773 * Times out callbacks for this connection.
774 */
775 protected void timeoutCallbacks() {
776 // Store the current time.
777 long currentTime = System.currentTimeMillis();
778
779 // Iterate through future callbacks and time out callbacks that have been alive
780 // longer than the current timeout according to the message type.
781 Iterator<Map.Entry<Long, Callback>> iterator = futures.entrySet().iterator();
782 while (iterator.hasNext()) {
783 Callback callback = iterator.next().getValue();
784 try {
785 TimeoutHistory timeoutHistory = timeoutHistories.get(callback.type, TimeoutHistory::new);
786 long currentTimeout = timeoutHistory.currentTimeout;
787 if (currentTime - callback.time > currentTimeout) {
788 iterator.remove();
789 long elapsedTime = currentTime - callback.time;
790 timeoutHistory.addReplyTime(elapsedTime);
791 callback.completeExceptionally(
792 new TimeoutException("Request timed out in " + elapsedTime + " milliseconds"));
793 }
794 } catch (ExecutionException e) {
795 throw new AssertionError();
796 }
797 }
798
799 // Iterate through all timeout histories and recompute the timeout.
800 for (TimeoutHistory timeoutHistory : timeoutHistories.asMap().values()) {
801 timeoutHistory.recomputeTimeoutMillis();
802 }
803 }
804
805 protected void registerCallback(long id, String subject, CompletableFuture<byte[]> future) {
806 futures.put(id, new Callback(subject, future));
807 }
808
809 protected Callback completeCallback(long id) {
810 Callback callback = futures.remove(id);
811 if (callback != null) {
812 try {
813 TimeoutHistory timeoutHistory = timeoutHistories.get(callback.type, TimeoutHistory::new);
814 timeoutHistory.addReplyTime(System.currentTimeMillis() - callback.time);
815 } catch (ExecutionException e) {
816 throw new AssertionError();
817 }
818 }
819 return callback;
820 }
821
822 protected Callback failCallback(long id) {
823 return futures.remove(id);
824 }
825
826 @Override
827 public void close() {
828 if (closed.compareAndSet(false, true)) {
829 timeoutFuture.cancel(false);
830 for (Callback callback : futures.values()) {
831 callback.completeExceptionally(new ConnectException());
832 }
833 }
834 }
835 }
836
837 /**
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700838 * Local connection implementation.
839 */
Jordan Haltermanfe2f93d2017-12-08 23:52:54 -0800840 private final class LocalClientConnection extends AbstractClientConnection {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700841 @Override
Jordan Haltermane3813a92017-07-29 14:10:31 -0700842 public CompletableFuture<Void> sendAsync(InternalRequest message) {
843 BiConsumer<InternalRequest, ServerConnection> handler = handlers.get(message.subject());
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700844 if (handler != null) {
845 handler.accept(message, localServerConnection);
846 } else {
847 log.debug("No handler for message type {} from {}", message.type(), message.sender());
848 }
849 return CompletableFuture.completedFuture(null);
850 }
851
852 @Override
Jordan Haltermane3813a92017-07-29 14:10:31 -0700853 public CompletableFuture<byte[]> sendAndReceive(InternalRequest message) {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700854 CompletableFuture<byte[]> future = new CompletableFuture<>();
Jordan Haltermanfe2f93d2017-12-08 23:52:54 -0800855 future.whenComplete((r, e) -> completeCallback(message.id()));
856 registerCallback(message.id(), message.subject(), future);
Jordan Haltermane3813a92017-07-29 14:10:31 -0700857 BiConsumer<InternalRequest, ServerConnection> handler = handlers.get(message.subject());
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700858 if (handler != null) {
859 handler.accept(message, new LocalServerConnection(future));
860 } else {
861 log.debug("No handler for message type {} from {}", message.type(), message.sender());
Jordan Haltermane3813a92017-07-29 14:10:31 -0700862 new LocalServerConnection(future)
863 .reply(message, InternalReply.Status.ERROR_NO_HANDLER, Optional.empty());
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700864 }
865 return future;
866 }
867 }
868
869 /**
870 * Local server connection.
871 */
872 private final class LocalServerConnection implements ServerConnection {
873 private final CompletableFuture<byte[]> future;
874
875 LocalServerConnection(CompletableFuture<byte[]> future) {
876 this.future = future;
877 }
878
879 @Override
Jordan Haltermane3813a92017-07-29 14:10:31 -0700880 public void reply(InternalRequest message, InternalReply.Status status, Optional<byte[]> payload) {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700881 if (future != null) {
Jordan Haltermane3813a92017-07-29 14:10:31 -0700882 if (status == InternalReply.Status.OK) {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700883 future.complete(payload.orElse(EMPTY_PAYLOAD));
Jordan Haltermane3813a92017-07-29 14:10:31 -0700884 } else if (status == InternalReply.Status.ERROR_NO_HANDLER) {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700885 future.completeExceptionally(new MessagingException.NoRemoteHandler());
Jordan Haltermane3813a92017-07-29 14:10:31 -0700886 } else if (status == InternalReply.Status.ERROR_HANDLER_EXCEPTION) {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700887 future.completeExceptionally(new MessagingException.RemoteHandlerFailure());
Jordan Haltermane3813a92017-07-29 14:10:31 -0700888 } else if (status == InternalReply.Status.PROTOCOL_EXCEPTION) {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700889 future.completeExceptionally(new MessagingException.ProtocolException());
890 }
891 }
892 }
893 }
894
895 /**
896 * Remote connection implementation.
897 */
Jordan Haltermanfe2f93d2017-12-08 23:52:54 -0800898 private final class RemoteClientConnection extends AbstractClientConnection {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700899 private final Channel channel;
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700900
901 RemoteClientConnection(Channel channel) {
902 this.channel = channel;
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800903 }
904
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700905 @Override
Jordan Haltermane3813a92017-07-29 14:10:31 -0700906 public CompletableFuture<Void> sendAsync(InternalRequest message) {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700907 CompletableFuture<Void> future = new CompletableFuture<>();
908 channel.writeAndFlush(message).addListener(channelFuture -> {
909 if (!channelFuture.isSuccess()) {
910 future.completeExceptionally(channelFuture.cause());
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800911 } else {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700912 future.complete(null);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800913 }
914 });
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700915 return future;
916 }
917
918 @Override
Jordan Haltermane3813a92017-07-29 14:10:31 -0700919 public CompletableFuture<byte[]> sendAndReceive(InternalRequest message) {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700920 CompletableFuture<byte[]> future = new CompletableFuture<>();
Jordan Haltermanfe2f93d2017-12-08 23:52:54 -0800921 registerCallback(message.id(), message.subject(), future);
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700922 channel.writeAndFlush(message).addListener(channelFuture -> {
923 if (!channelFuture.isSuccess()) {
Jordan Haltermanfe2f93d2017-12-08 23:52:54 -0800924 Callback callback = failCallback(message.id());
925 if (callback != null) {
926 callback.completeExceptionally(channelFuture.cause());
927 }
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700928 }
929 });
930 return future;
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800931 }
932
933 /**
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700934 * Dispatches a message to a local handler.
935 *
936 * @param message the message to dispatch
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800937 */
Jordan Haltermane3813a92017-07-29 14:10:31 -0700938 private void dispatch(InternalReply message) {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700939 if (message.preamble() != preamble) {
Jordan Haltermane3813a92017-07-29 14:10:31 -0700940 log.debug("Received {} with invalid preamble", message.type());
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700941 return;
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800942 }
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700943
944 clockService.recordEventTime(message.time());
945
Jordan Haltermanfe2f93d2017-12-08 23:52:54 -0800946 Callback callback = completeCallback(message.id());
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700947 if (callback != null) {
Jordan Haltermane3813a92017-07-29 14:10:31 -0700948 if (message.status() == InternalReply.Status.OK) {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700949 callback.complete(message.payload());
Jordan Haltermane3813a92017-07-29 14:10:31 -0700950 } else if (message.status() == InternalReply.Status.ERROR_NO_HANDLER) {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700951 callback.completeExceptionally(new MessagingException.NoRemoteHandler());
Jordan Haltermane3813a92017-07-29 14:10:31 -0700952 } else if (message.status() == InternalReply.Status.ERROR_HANDLER_EXCEPTION) {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700953 callback.completeExceptionally(new MessagingException.RemoteHandlerFailure());
Jordan Haltermane3813a92017-07-29 14:10:31 -0700954 } else if (message.status() == InternalReply.Status.PROTOCOL_EXCEPTION) {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700955 callback.completeExceptionally(new MessagingException.ProtocolException());
956 }
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700957 } else {
Jordan Haltermane3813a92017-07-29 14:10:31 -0700958 log.debug("Received a reply for message id:[{}] "
959 + "but was unable to locate the"
960 + " request handle", message.id());
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700961 }
962 }
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700963 }
964
965 /**
966 * Remote server connection.
967 */
968 private final class RemoteServerConnection implements ServerConnection {
969 private final Channel channel;
970
971 RemoteServerConnection(Channel channel) {
972 this.channel = channel;
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800973 }
974
975 /**
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700976 * Dispatches a message to a local handler.
977 *
978 * @param message the message to dispatch
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800979 */
Jordan Haltermane3813a92017-07-29 14:10:31 -0700980 private void dispatch(InternalRequest message) {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700981 if (message.preamble() != preamble) {
982 log.debug("Received {} with invalid preamble from {}", message.type(), message.sender());
Jordan Haltermane3813a92017-07-29 14:10:31 -0700983 reply(message, InternalReply.Status.PROTOCOL_EXCEPTION, Optional.empty());
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700984 return;
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800985 }
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700986
987 clockService.recordEventTime(message.time());
988
Jordan Haltermane3813a92017-07-29 14:10:31 -0700989 BiConsumer<InternalRequest, ServerConnection> handler = handlers.get(message.subject());
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700990 if (handler != null) {
991 handler.accept(message, this);
992 } else {
993 log.debug("No handler for message type {} from {}", message.type(), message.sender());
Jordan Haltermane3813a92017-07-29 14:10:31 -0700994 reply(message, InternalReply.Status.ERROR_NO_HANDLER, Optional.empty());
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700995 }
996 }
997
998 @Override
Jordan Haltermane3813a92017-07-29 14:10:31 -0700999 public void reply(InternalRequest message, InternalReply.Status status, Optional<byte[]> payload) {
1000 InternalReply response = new InternalReply(preamble,
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -07001001 clockService.timeNow(),
1002 message.id(),
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -07001003 payload.orElse(EMPTY_PAYLOAD),
1004 status);
1005 channel.writeAndFlush(response);
1006 }
1007 }
1008
1009 /**
1010 * Request-reply timeout history tracker.
1011 */
1012 private static final class TimeoutHistory {
1013 private final DescriptiveStatistics timeoutHistory = new SynchronizedDescriptiveStatistics(WINDOW_SIZE);
1014 private final AtomicLong maxReplyTime = new AtomicLong();
1015 private volatile long currentTimeout = DEFAULT_TIMEOUT_MILLIS;
1016
1017 /**
1018 * Adds a reply time to the history.
1019 *
1020 * @param replyTime the reply time to add to the history
1021 */
1022 void addReplyTime(long replyTime) {
1023 maxReplyTime.getAndAccumulate(replyTime, Math::max);
1024 }
1025
1026 /**
1027 * Computes the current timeout.
1028 */
1029 private void recomputeTimeoutMillis() {
1030 double nextTimeout = maxReplyTime.getAndSet(0) * TIMEOUT_MULTIPLIER;
1031 timeoutHistory.addValue(
1032 Math.min(Math.max(nextTimeout, MIN_TIMEOUT_MILLIS), MAX_TIMEOUT_MILLIS));
1033 if (timeoutHistory.getN() == WINDOW_SIZE) {
1034 this.currentTimeout = (long) timeoutHistory.getMax();
1035 }
Aaron Kruglikov1b727382016-02-09 16:17:47 -08001036 }
1037 }
JunHuy Lam39eb4292015-06-26 17:24:23 +09001038}