blob: 50c8fc6f65514205972d545179be103de914f396 [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 Halterman83b1d932018-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 Halterman83b1d932018-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 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 TIMEOUT_INTERVAL = 50;
110 private static final int WINDOW_SIZE = 100;
Jordan Haltermanef92f192017-12-21 11:59:38 -0800111 private static final int MIN_SAMPLES = 25;
112 private static final double PHI_FACTOR = 1.0 / Math.log(10.0);
113 private static final int PHI_FAILURE_THRESHOLD = 5;
Jordan Halterman111aab72018-01-12 16:28:57 -0800114 private static final long MIN_TIMEOUT_MILLIS = 100;
Jordan Haltermanef92f192017-12-21 11:59:38 -0800115 private static final long MAX_TIMEOUT_MILLIS = 15000;
Jordan Halterman66e6e3b2017-07-10 11:26:34 -0700116 private static final int CHANNEL_POOL_SIZE = 8;
Madan Jampaniafeebbd2015-05-19 15:26:01 -0700117
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700118 private static final byte[] EMPTY_PAYLOAD = new byte[0];
119
Madan Jampaniafeebbd2015-05-19 15:26:01 -0700120 private final Logger log = LoggerFactory.getLogger(getClass());
121
Jordan Halterman1cf233c2017-12-08 23:52:54 -0800122 private final LocalClientConnection localClientConnection = new LocalClientConnection();
123 private final LocalServerConnection localServerConnection = new LocalServerConnection(null);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800124
Brian O'Connor740e98c2017-06-29 17:07:17 -0700125 //TODO CONFIG_DIR is duplicated from ConfigFileBasedClusterMetadataProvider
126 private static final String CONFIG_DIR = "../config";
127 private static final String KS_FILE_NAME = "onos.jks";
128 private static final File DEFAULT_KS_FILE = new File(CONFIG_DIR, KS_FILE_NAME);
129 private static final String DEFAULT_KS_PASSWORD = "changeit";
130
Madan Jampani05833872016-07-12 23:01:39 -0700131 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
132 protected HybridLogicalClockService clockService;
133
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700134 private Endpoint localEndpoint;
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800135 private int preamble;
136 private final AtomicBoolean started = new AtomicBoolean(false);
Jordan Haltermane3813a92017-07-29 14:10:31 -0700137 private final Map<String, BiConsumer<InternalRequest, ServerConnection>> handlers = new ConcurrentHashMap<>();
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700138 private final Map<Channel, RemoteClientConnection> clientConnections = Maps.newConcurrentMap();
139 private final Map<Channel, RemoteServerConnection> serverConnections = Maps.newConcurrentMap();
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800140 private final AtomicLong messageIdGenerator = new AtomicLong(0);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800141
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700142 private ScheduledFuture<?> timeoutFuture;
143
Jordan Halterman66e6e3b2017-07-10 11:26:34 -0700144 private final Map<Endpoint, List<CompletableFuture<Channel>>> channels = Maps.newConcurrentMap();
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800145
146 private EventLoopGroup serverGroup;
147 private EventLoopGroup clientGroup;
148 private Class<? extends ServerChannel> serverChannelClass;
149 private Class<? extends Channel> clientChannelClass;
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700150 private ScheduledExecutorService timeoutExecutor;
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800151
Brian O'Connor740e98c2017-06-29 17:07:17 -0700152 protected static final boolean TLS_ENABLED = true;
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800153 protected static final boolean TLS_DISABLED = false;
Brian O'Connor740e98c2017-06-29 17:07:17 -0700154 protected boolean enableNettyTls = TLS_ENABLED;
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800155
Brian O'Connor740e98c2017-06-29 17:07:17 -0700156 protected TrustManagerFactory trustManager;
157 protected KeyManagerFactory keyManager;
JunHuy Lam39eb4292015-06-26 17:24:23 +0900158
Madan Jampaniafeebbd2015-05-19 15:26:01 -0700159 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Madan Jampaniec1df022015-10-13 21:23:03 -0700160 protected ClusterMetadataService clusterMetadataService;
Madan Jampaniafeebbd2015-05-19 15:26:01 -0700161
162 @Activate
163 public void activate() throws Exception {
Madan Jampaniec1df022015-10-13 21:23:03 -0700164 ControllerNode localNode = clusterMetadataService.getLocalNode();
Jonathan Hartd9df7bd2015-11-10 17:10:25 -0800165 getTlsParameters();
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800166
167 if (started.get()) {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700168 log.warn("Already running at local endpoint: {}", localEndpoint);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800169 return;
170 }
171 this.preamble = clusterMetadataService.getClusterMetadata().getName().hashCode();
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700172 this.localEndpoint = new Endpoint(localNode.ip(), localNode.tcpPort());
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800173 initEventLoopGroup();
174 startAcceptingConnections();
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700175 timeoutExecutor = Executors.newSingleThreadScheduledExecutor(
176 groupedThreads("NettyMessagingEvt", "timeout", log));
177 timeoutFuture = timeoutExecutor.scheduleAtFixedRate(
178 this::timeoutAllCallbacks, TIMEOUT_INTERVAL, TIMEOUT_INTERVAL, TimeUnit.MILLISECONDS);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800179 started.set(true);
Madan Jampaniafeebbd2015-05-19 15:26:01 -0700180 log.info("Started");
181 }
182
183 @Deactivate
184 public void deactivate() throws Exception {
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800185 if (started.get()) {
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800186 serverGroup.shutdownGracefully();
187 clientGroup.shutdownGracefully();
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700188 timeoutFuture.cancel(false);
189 timeoutExecutor.shutdown();
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800190 started.set(false);
191 }
Madan Jampaniafeebbd2015-05-19 15:26:01 -0700192 log.info("Stopped");
193 }
JunHuy Lam39eb4292015-06-26 17:24:23 +0900194
Jonathan Hartd9df7bd2015-11-10 17:10:25 -0800195 private void getTlsParameters() {
Brian O'Connor740e98c2017-06-29 17:07:17 -0700196 // default is TLS enabled unless key stores cannot be loaded
197 enableNettyTls = Boolean.parseBoolean(System.getProperty("enableNettyTLS", Boolean.toString(TLS_ENABLED)));
198
Jonathan Hartd9df7bd2015-11-10 17:10:25 -0800199 if (enableNettyTls) {
Brian O'Connor740e98c2017-06-29 17:07:17 -0700200 enableNettyTls = loadKeyStores();
201 }
202 }
203
204 private boolean loadKeyStores() {
205 // Maintain a local copy of the trust and key managers in case anything goes wrong
206 TrustManagerFactory tmf;
207 KeyManagerFactory kmf;
208 try {
209 String ksLocation = System.getProperty("javax.net.ssl.keyStore", DEFAULT_KS_FILE.toString());
210 String tsLocation = System.getProperty("javax.net.ssl.trustStore", DEFAULT_KS_FILE.toString());
211 char[] ksPwd = System.getProperty("javax.net.ssl.keyStorePassword", DEFAULT_KS_PASSWORD).toCharArray();
212 char[] tsPwd = System.getProperty("javax.net.ssl.trustStorePassword", DEFAULT_KS_PASSWORD).toCharArray();
213
214 tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
215 KeyStore ts = KeyStore.getInstance("JKS");
216 ts.load(new FileInputStream(tsLocation), tsPwd);
217 tmf.init(ts);
218
219 kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
220 KeyStore ks = KeyStore.getInstance("JKS");
221 ks.load(new FileInputStream(ksLocation), ksPwd);
222 kmf.init(ks, ksPwd);
223 if (log.isInfoEnabled()) {
224 logKeyStore(ks, ksLocation, ksPwd);
JunHuy Lam39eb4292015-06-26 17:24:23 +0900225 }
Brian O'Connor740e98c2017-06-29 17:07:17 -0700226 } catch (FileNotFoundException e) {
227 log.warn("Disabling TLS for intra-cluster messaging; Could not load cluster key store: {}", e.getMessage());
228 return TLS_DISABLED;
229 } catch (Exception e) {
230 //TODO we might want to catch exceptions more specifically
231 log.error("Error loading key store; disabling TLS for intra-cluster messaging", e);
232 return TLS_DISABLED;
233 }
234 this.trustManager = tmf;
235 this.keyManager = kmf;
236 return TLS_ENABLED;
237 }
238
239 private void logKeyStore(KeyStore ks, String ksLocation, char[] ksPwd) {
240 if (log.isInfoEnabled()) {
241 log.info("Loaded cluster key store from: {}", ksLocation);
242 try {
243 for (Enumeration<String> e = ks.aliases(); e.hasMoreElements();) {
244 String alias = e.nextElement();
245 Key key = ks.getKey(alias, ksPwd);
246 Certificate[] certs = ks.getCertificateChain(alias);
247 log.debug("{} -> {}", alias, certs);
248 final byte[] encodedKey;
249 if (certs != null && certs.length > 0) {
250 encodedKey = certs[0].getEncoded();
251 } else {
252 log.info("Could not find cert chain for {}, using fingerprint of key instead...", alias);
253 encodedKey = key.getEncoded();
254 }
255 // Compute the certificate's fingerprint (use the key if certificate cannot be found)
256 MessageDigest digest = MessageDigest.getInstance("SHA1");
257 digest.update(encodedKey);
258 StringJoiner fingerprint = new StringJoiner(":");
259 for (byte b : digest.digest()) {
260 fingerprint.add(String.format("%02X", b));
261 }
262 log.info("{} -> {}", alias, fingerprint);
263 }
264 } catch (Exception e) {
265 log.warn("Unable to print contents of key store: {}", ksLocation, e);
JunHuy Lam39eb4292015-06-26 17:24:23 +0900266 }
267 }
268 }
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700269
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800270 private void initEventLoopGroup() {
271 // try Epoll first and if that does work, use nio.
272 try {
Yuta HIGUCHI90a16892016-07-20 20:36:08 -0700273 clientGroup = new EpollEventLoopGroup(0, groupedThreads("NettyMessagingEvt", "epollC-%d", log));
274 serverGroup = new EpollEventLoopGroup(0, groupedThreads("NettyMessagingEvt", "epollS-%d", log));
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800275 serverChannelClass = EpollServerSocketChannel.class;
276 clientChannelClass = EpollSocketChannel.class;
277 return;
278 } catch (Throwable e) {
279 log.debug("Failed to initialize native (epoll) transport. "
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700280 + "Reason: {}. Proceeding with nio.", e.getMessage());
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800281 }
Yuta HIGUCHI90a16892016-07-20 20:36:08 -0700282 clientGroup = new NioEventLoopGroup(0, groupedThreads("NettyMessagingEvt", "nioC-%d", log));
283 serverGroup = new NioEventLoopGroup(0, groupedThreads("NettyMessagingEvt", "nioS-%d", log));
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800284 serverChannelClass = NioServerSocketChannel.class;
285 clientChannelClass = NioSocketChannel.class;
286 }
287
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700288 /**
289 * Times out response callbacks.
290 */
291 private void timeoutAllCallbacks() {
292 // Iterate through all connections and time out callbacks.
Jordan Halterman1cf233c2017-12-08 23:52:54 -0800293 localClientConnection.timeoutCallbacks();
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700294 for (RemoteClientConnection connection : clientConnections.values()) {
295 connection.timeoutCallbacks();
296 }
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700297 }
298
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800299 @Override
300 public CompletableFuture<Void> sendAsync(Endpoint ep, String type, byte[] payload) {
Heedo Kang4a47a302016-02-29 17:40:23 +0900301 checkPermission(CLUSTER_WRITE);
Jordan Haltermane3813a92017-07-29 14:10:31 -0700302 InternalRequest message = new InternalRequest(preamble,
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700303 clockService.timeNow(),
304 messageIdGenerator.incrementAndGet(),
305 localEndpoint,
306 type,
307 payload);
Jordan Halterman66e6e3b2017-07-10 11:26:34 -0700308 return executeOnPooledConnection(ep, type, c -> c.sendAsync(message), MoreExecutors.directExecutor());
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800309 }
310
311 @Override
312 public CompletableFuture<byte[]> sendAndReceive(Endpoint ep, String type, byte[] payload) {
Heedo Kang4a47a302016-02-29 17:40:23 +0900313 checkPermission(CLUSTER_WRITE);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800314 return sendAndReceive(ep, type, payload, MoreExecutors.directExecutor());
315 }
316
317 @Override
318 public CompletableFuture<byte[]> sendAndReceive(Endpoint ep, String type, byte[] payload, Executor executor) {
Heedo Kang4a47a302016-02-29 17:40:23 +0900319 checkPermission(CLUSTER_WRITE);
Jordan Halterman5ceb3892017-08-28 15:35:03 -0700320 long messageId = messageIdGenerator.incrementAndGet();
Jordan Haltermane3813a92017-07-29 14:10:31 -0700321 InternalRequest message = new InternalRequest(preamble,
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700322 clockService.timeNow(),
323 messageId,
324 localEndpoint,
325 type,
326 payload);
Jordan Halterman66e6e3b2017-07-10 11:26:34 -0700327 return executeOnPooledConnection(ep, type, c -> c.sendAndReceive(message), executor);
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700328 }
Jordan Halterman041534b2017-03-21 10:37:33 -0700329
Jordan Halterman66e6e3b2017-07-10 11:26:34 -0700330 private List<CompletableFuture<Channel>> getChannelPool(Endpoint endpoint) {
331 return channels.computeIfAbsent(endpoint, e -> {
332 List<CompletableFuture<Channel>> defaultList = new ArrayList<>(CHANNEL_POOL_SIZE);
333 for (int i = 0; i < CHANNEL_POOL_SIZE; i++) {
334 defaultList.add(null);
335 }
336 return Lists.newCopyOnWriteArrayList(defaultList);
337 });
338 }
339
340 private int getChannelOffset(String messageType) {
341 return Math.abs(messageType.hashCode() % CHANNEL_POOL_SIZE);
342 }
343
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700344 private <T> CompletableFuture<T> executeOnPooledConnection(
345 Endpoint endpoint,
Jordan Halterman66e6e3b2017-07-10 11:26:34 -0700346 String type,
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700347 Function<ClientConnection, CompletableFuture<T>> callback,
348 Executor executor) {
Jordan Halterman66e6e3b2017-07-10 11:26:34 -0700349 CompletableFuture<T> future = new CompletableFuture<T>();
350 executeOnPooledConnection(endpoint, type, callback, executor, future);
351 return future;
352 }
353
354 private <T> void executeOnPooledConnection(
Jordan Halterman83b1d932018-01-13 14:10:56 -0800355 Endpoint endpoint,
356 String type,
357 Function<ClientConnection, CompletableFuture<T>> callback,
358 Executor executor,
359 CompletableFuture<T> future) {
360
361 // If the endpoint is the local node, avoid the loopback interface and use the singleton local connection.
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700362 if (endpoint.equals(localEndpoint)) {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700363 callback.apply(localClientConnection).whenComplete((result, error) -> {
Jordan Halterman1cf233c2017-12-08 23:52:54 -0800364 if (error == null) {
365 executor.execute(() -> future.complete(result));
366 } else {
367 executor.execute(() -> future.completeExceptionally(error));
368 }
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700369 });
Jordan Halterman66e6e3b2017-07-10 11:26:34 -0700370 return;
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700371 }
372
Jordan Halterman83b1d932018-01-13 14:10:56 -0800373 // Get the channel pool and the offset for this message type.
374 List<CompletableFuture<Channel>> channelPool = getChannelPool(endpoint);
375 int offset = getChannelOffset(type);
376
377 // If the channel future is completed exceptionally, open a new channel.
378 CompletableFuture<Channel> channelFuture = channelPool.get(offset);
379 if (channelFuture == null || channelFuture.isCompletedExceptionally()) {
380 synchronized (channelPool) {
381 channelFuture = channelPool.get(offset);
382 if (channelFuture == null || channelFuture.isCompletedExceptionally()) {
383 channelFuture = openChannel(endpoint);
384 channelPool.set(offset, channelFuture);
385 }
386 }
387 }
388
389 // Create a consumer with which to complete the send operation on a given channel.
390 final Consumer<Channel> runner = channel -> {
391 ClientConnection connection = clientConnections.computeIfAbsent(channel, RemoteClientConnection::new);
392 callback.apply(connection).whenComplete((result, sendError) -> {
393 if (sendError == null) {
394 executor.execute(() -> future.complete(result));
395 } else {
396 // If an exception other than a TimeoutException occurred, close the connection and
397 // remove the channel from the pool.
398 if (!(Throwables.getRootCause(sendError) instanceof TimeoutException)) {
399 synchronized (channelPool) {
400 channelPool.set(offset, null);
401 }
402 connection.close();
403 channel.close();
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700404 }
Jordan Halterman83b1d932018-01-13 14:10:56 -0800405 executor.execute(() -> future.completeExceptionally(sendError));
406 }
407 });
408 };
409
410 // Wait for the channel future to be completed. Once it's complete, if the channel is active then
411 // attempt to send the message. Otherwise, if the channel is inactive then attempt to open a new channel.
412 final CompletableFuture<Channel> finalFuture = channelFuture;
413 finalFuture.whenComplete((channel, error) -> {
414 if (error == null) {
415 if (!channel.isActive()) {
416 synchronized (channelPool) {
417 CompletableFuture<Channel> currentFuture = channelPool.get(offset);
418 if (currentFuture == finalFuture) {
419 channelPool.set(offset, null);
420 executeOnPooledConnection(endpoint, type, callback, executor);
421 } else {
422 currentFuture.whenComplete((recursiveResult, recursiveError) -> {
423 if (recursiveError == null) {
424 runner.accept(recursiveResult);
425 } else {
426 future.completeExceptionally(recursiveError);
427 }
428 });
429 }
430 }
431 } else {
432 runner.accept(channel);
433 }
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700434 } else {
Jordan Halterman83b1d932018-01-13 14:10:56 -0800435 future.completeExceptionally(error);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800436 }
Jordan Halterman041534b2017-03-21 10:37:33 -0700437 });
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800438 }
439
440 @Override
441 public void registerHandler(String type, BiConsumer<Endpoint, byte[]> handler, Executor executor) {
Heedo Kang4a47a302016-02-29 17:40:23 +0900442 checkPermission(CLUSTER_WRITE);
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700443 handlers.put(type, (message, connection) -> executor.execute(() ->
444 handler.accept(message.sender(), message.payload())));
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800445 }
446
447 @Override
448 public void registerHandler(String type, BiFunction<Endpoint, byte[], byte[]> handler, Executor executor) {
Heedo Kang4a47a302016-02-29 17:40:23 +0900449 checkPermission(CLUSTER_WRITE);
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700450 handlers.put(type, (message, connection) -> executor.execute(() -> {
Madan Jampania9e70a62016-03-02 16:28:18 -0800451 byte[] responsePayload = null;
Jordan Haltermane3813a92017-07-29 14:10:31 -0700452 InternalReply.Status status = InternalReply.Status.OK;
Madan Jampania9e70a62016-03-02 16:28:18 -0800453 try {
454 responsePayload = handler.apply(message.sender(), message.payload());
455 } catch (Exception e) {
Jordan Haltermanb6ee9e92017-06-21 15:26:28 -0700456 log.debug("An error occurred in a message handler: {}", e);
Jordan Haltermane3813a92017-07-29 14:10:31 -0700457 status = InternalReply.Status.ERROR_HANDLER_EXCEPTION;
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800458 }
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700459 connection.reply(message, status, Optional.ofNullable(responsePayload));
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800460 }));
461 }
462
463 @Override
464 public void registerHandler(String type, BiFunction<Endpoint, byte[], CompletableFuture<byte[]>> handler) {
Heedo Kang4a47a302016-02-29 17:40:23 +0900465 checkPermission(CLUSTER_WRITE);
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700466 handlers.put(type, (message, connection) -> {
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800467 handler.apply(message.sender(), message.payload()).whenComplete((result, error) -> {
Jordan Haltermane3813a92017-07-29 14:10:31 -0700468 InternalReply.Status status;
Jordan Haltermanb6ee9e92017-06-21 15:26:28 -0700469 if (error == null) {
Jordan Haltermane3813a92017-07-29 14:10:31 -0700470 status = InternalReply.Status.OK;
Jordan Haltermanb6ee9e92017-06-21 15:26:28 -0700471 } else {
472 log.debug("An error occurred in a message handler: {}", error);
Jordan Haltermane3813a92017-07-29 14:10:31 -0700473 status = InternalReply.Status.ERROR_HANDLER_EXCEPTION;
Jordan Haltermanb6ee9e92017-06-21 15:26:28 -0700474 }
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700475 connection.reply(message, status, Optional.ofNullable(result));
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800476 });
477 });
478 }
479
480 @Override
481 public void unregisterHandler(String type) {
Heedo Kang4a47a302016-02-29 17:40:23 +0900482 checkPermission(CLUSTER_WRITE);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800483 handlers.remove(type);
484 }
485
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700486 private Bootstrap bootstrapClient(Endpoint endpoint) {
487 Bootstrap bootstrap = new Bootstrap();
488 bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
489 bootstrap.option(ChannelOption.WRITE_BUFFER_WATER_MARK,
490 new WriteBufferWaterMark(10 * 32 * 1024, 10 * 64 * 1024));
491 bootstrap.option(ChannelOption.SO_SNDBUF, 1048576);
492 bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000);
493 bootstrap.group(clientGroup);
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700494 bootstrap.channel(clientChannelClass);
495 bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
496 bootstrap.remoteAddress(endpoint.host().toInetAddress(), endpoint.port());
Jordan Halterman66e6e3b2017-07-10 11:26:34 -0700497 if (enableNettyTls) {
498 bootstrap.handler(new SslClientCommunicationChannelInitializer());
499 } else {
500 bootstrap.handler(new BasicChannelInitializer());
501 }
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700502 return bootstrap;
503 }
504
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800505 private void startAcceptingConnections() throws InterruptedException {
506 ServerBootstrap b = new ServerBootstrap();
Jon Hall9a44d6a2017-03-02 18:14:37 -0800507 b.childOption(ChannelOption.WRITE_BUFFER_WATER_MARK,
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700508 new WriteBufferWaterMark(8 * 1024, 32 * 1024));
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800509 b.option(ChannelOption.SO_RCVBUF, 1048576);
Jordan Halterman153dbd52017-12-21 11:08:19 -0800510 b.childOption(ChannelOption.SO_KEEPALIVE, true);
511 b.childOption(ChannelOption.TCP_NODELAY, true);
Yuta HIGUCHIb47c9532016-08-22 09:41:23 -0700512 b.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800513 b.group(serverGroup, clientGroup);
514 b.channel(serverChannelClass);
515 if (enableNettyTls) {
516 b.childHandler(new SslServerCommunicationChannelInitializer());
517 } else {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700518 b.childHandler(new BasicChannelInitializer());
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800519 }
520 b.option(ChannelOption.SO_BACKLOG, 128);
521 b.childOption(ChannelOption.SO_KEEPALIVE, true);
522
523 // Bind and start to accept incoming connections.
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700524 b.bind(localEndpoint.port()).sync().addListener(future -> {
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800525 if (future.isSuccess()) {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700526 log.info("{} accepting incoming connections on port {}",
527 localEndpoint.host(), localEndpoint.port());
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800528 } else {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700529 log.warn("{} failed to bind to port {} due to {}",
530 localEndpoint.host(), localEndpoint.port(), future.cause());
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800531 }
532 });
533 }
534
Jordan Halterman66e6e3b2017-07-10 11:26:34 -0700535 private CompletableFuture<Channel> openChannel(Endpoint ep) {
536 Bootstrap bootstrap = bootstrapClient(ep);
537 CompletableFuture<Channel> retFuture = new CompletableFuture<>();
538 ChannelFuture f = bootstrap.connect();
539
540 f.addListener(future -> {
541 if (future.isSuccess()) {
542 retFuture.complete(f.channel());
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800543 } else {
Jordan Halterman66e6e3b2017-07-10 11:26:34 -0700544 retFuture.completeExceptionally(future.cause());
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800545 }
Jordan Halterman66e6e3b2017-07-10 11:26:34 -0700546 });
547 log.debug("Established a new connection to {}", ep);
548 return retFuture;
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800549 }
550
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700551 /**
552 * Channel initializer for TLS servers.
553 */
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800554 private class SslServerCommunicationChannelInitializer extends ChannelInitializer<SocketChannel> {
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800555 private final ChannelHandler dispatcher = new InboundMessageDispatcher();
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800556
557 @Override
558 protected void initChannel(SocketChannel channel) throws Exception {
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800559 SSLContext serverContext = SSLContext.getInstance("TLS");
Brian O'Connor740e98c2017-06-29 17:07:17 -0700560 serverContext.init(keyManager.getKeyManagers(), trustManager.getTrustManagers(), null);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800561
562 SSLEngine serverSslEngine = serverContext.createSSLEngine();
563
564 serverSslEngine.setNeedClientAuth(true);
565 serverSslEngine.setUseClientMode(false);
566 serverSslEngine.setEnabledProtocols(serverSslEngine.getSupportedProtocols());
567 serverSslEngine.setEnabledCipherSuites(serverSslEngine.getSupportedCipherSuites());
568 serverSslEngine.setEnableSessionCreation(true);
569
570 channel.pipeline().addLast("ssl", new io.netty.handler.ssl.SslHandler(serverSslEngine))
Jordan Haltermane3813a92017-07-29 14:10:31 -0700571 .addLast("encoder", new MessageEncoder(localEndpoint, preamble))
Madan Jampanib825aeb2016-04-01 15:18:25 -0700572 .addLast("decoder", new MessageDecoder())
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800573 .addLast("handler", dispatcher);
574 }
575 }
576
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700577 /**
578 * Channel initializer for TLS clients.
579 */
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800580 private class SslClientCommunicationChannelInitializer extends ChannelInitializer<SocketChannel> {
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800581 private final ChannelHandler dispatcher = new InboundMessageDispatcher();
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800582
583 @Override
584 protected void initChannel(SocketChannel channel) throws Exception {
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800585 SSLContext clientContext = SSLContext.getInstance("TLS");
Brian O'Connor740e98c2017-06-29 17:07:17 -0700586 clientContext.init(keyManager.getKeyManagers(), trustManager.getTrustManagers(), null);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800587
588 SSLEngine clientSslEngine = clientContext.createSSLEngine();
589
590 clientSslEngine.setUseClientMode(true);
591 clientSslEngine.setEnabledProtocols(clientSslEngine.getSupportedProtocols());
592 clientSslEngine.setEnabledCipherSuites(clientSslEngine.getSupportedCipherSuites());
593 clientSslEngine.setEnableSessionCreation(true);
594
595 channel.pipeline().addLast("ssl", new io.netty.handler.ssl.SslHandler(clientSslEngine))
Jordan Haltermane3813a92017-07-29 14:10:31 -0700596 .addLast("encoder", new MessageEncoder(localEndpoint, preamble))
Madan Jampanib825aeb2016-04-01 15:18:25 -0700597 .addLast("decoder", new MessageDecoder())
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800598 .addLast("handler", dispatcher);
599 }
600 }
601
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700602 /**
603 * Channel initializer for basic connections.
604 */
605 private class BasicChannelInitializer extends ChannelInitializer<SocketChannel> {
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800606 private final ChannelHandler dispatcher = new InboundMessageDispatcher();
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800607
608 @Override
609 protected void initChannel(SocketChannel channel) throws Exception {
610 channel.pipeline()
Jordan Haltermane3813a92017-07-29 14:10:31 -0700611 .addLast("encoder", new MessageEncoder(localEndpoint, preamble))
Madan Jampanib825aeb2016-04-01 15:18:25 -0700612 .addLast("decoder", new MessageDecoder())
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800613 .addLast("handler", dispatcher);
614 }
615 }
616
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700617 /**
618 * Channel inbound handler that dispatches messages to the appropriate handler.
619 */
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800620 @ChannelHandler.Sharable
Yuta HIGUCHIc012dda2016-08-17 00:43:46 -0700621 private class InboundMessageDispatcher extends SimpleChannelInboundHandler<Object> {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700622 // Effectively SimpleChannelInboundHandler<InternalMessage>,
623 // had to specify <Object> to avoid Class Loader not being able to find some classes.
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800624
625 @Override
Yuta HIGUCHIc012dda2016-08-17 00:43:46 -0700626 protected void channelRead0(ChannelHandlerContext ctx, Object rawMessage) throws Exception {
627 InternalMessage message = (InternalMessage) rawMessage;
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800628 try {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700629 if (message.isRequest()) {
630 RemoteServerConnection connection =
631 serverConnections.computeIfAbsent(ctx.channel(), RemoteServerConnection::new);
Jordan Haltermane3813a92017-07-29 14:10:31 -0700632 connection.dispatch((InternalRequest) message);
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700633 } else {
634 RemoteClientConnection connection =
635 clientConnections.computeIfAbsent(ctx.channel(), RemoteClientConnection::new);
Jordan Haltermane3813a92017-07-29 14:10:31 -0700636 connection.dispatch((InternalReply) message);
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700637 }
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800638 } catch (RejectedExecutionException e) {
639 log.warn("Unable to dispatch message due to {}", e.getMessage());
640 }
641 }
642
643 @Override
644 public void exceptionCaught(ChannelHandlerContext context, Throwable cause) {
645 log.error("Exception inside channel handling pipeline.", cause);
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700646
647 RemoteClientConnection clientConnection = clientConnections.remove(context.channel());
648 if (clientConnection != null) {
649 clientConnection.close();
650 }
651
652 RemoteServerConnection serverConnection = serverConnections.remove(context.channel());
653 if (serverConnection != null) {
654 serverConnection.close();
655 }
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800656 context.close();
657 }
Yuta HIGUCHIc012dda2016-08-17 00:43:46 -0700658
659 /**
660 * Returns true if the given message should be handled.
661 *
662 * @param msg inbound message
663 * @return true if {@code msg} is {@link InternalMessage} instance.
Yuta HIGUCHIc012dda2016-08-17 00:43:46 -0700664 * @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 */
Jordan Haltermane3813a92017-07-29 14:10:31 -0700705 CompletableFuture<Void> sendAsync(InternalRequest message);
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700706
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 */
Jordan Haltermane3813a92017-07-29 14:10:31 -0700713 CompletableFuture<byte[]> sendAndReceive(InternalRequest message);
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700714
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
Jordan Halterman1cf233c2017-12-08 23:52:54 -0800731 * @param status the reply status
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700732 * @param payload the response payload
733 */
Jordan Haltermane3813a92017-07-29 14:10:31 -0700734 void reply(InternalRequest message, InternalReply.Status status, Optional<byte[]> payload);
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700735
736 /**
737 * Closes the connection.
738 */
739 default void close() {
740 }
741 }
742
743 /**
Jordan Halterman1cf233c2017-12-08 23:52:54 -0800744 * Remote connection implementation.
745 */
746 private abstract class AbstractClientConnection implements ClientConnection {
747 private final Map<Long, Callback> futures = Maps.newConcurrentMap();
748 private final AtomicBoolean closed = new AtomicBoolean(false);
Jordan Haltermanef92f192017-12-21 11:59:38 -0800749 private final Cache<String, RequestMonitor> requestMonitors = CacheBuilder.newBuilder()
Jordan Halterman1cf233c2017-12-08 23:52:54 -0800750 .expireAfterAccess(HISTORY_EXPIRE_MILLIS, TimeUnit.MILLISECONDS)
751 .build();
752
753 /**
754 * Times out callbacks for this connection.
755 */
Jordan Haltermanef92f192017-12-21 11:59:38 -0800756 void timeoutCallbacks() {
Jordan Halterman1cf233c2017-12-08 23:52:54 -0800757 // Store the current time.
758 long currentTime = System.currentTimeMillis();
759
760 // Iterate through future callbacks and time out callbacks that have been alive
761 // longer than the current timeout according to the message type.
762 Iterator<Map.Entry<Long, Callback>> iterator = futures.entrySet().iterator();
763 while (iterator.hasNext()) {
764 Callback callback = iterator.next().getValue();
765 try {
Jordan Haltermanef92f192017-12-21 11:59:38 -0800766 RequestMonitor requestMonitor = requestMonitors.get(callback.type, RequestMonitor::new);
767 long elapsedTime = currentTime - callback.time;
Jordan Halterman111aab72018-01-12 16:28:57 -0800768 if (elapsedTime > MAX_TIMEOUT_MILLIS ||
769 (elapsedTime > MIN_TIMEOUT_MILLIS && requestMonitor.isTimedOut(elapsedTime))) {
Jordan Halterman1cf233c2017-12-08 23:52:54 -0800770 iterator.remove();
Jordan Haltermanef92f192017-12-21 11:59:38 -0800771 requestMonitor.addReplyTime(elapsedTime);
Jordan Halterman1cf233c2017-12-08 23:52:54 -0800772 callback.completeExceptionally(
773 new TimeoutException("Request timed out in " + elapsedTime + " milliseconds"));
774 }
775 } catch (ExecutionException e) {
776 throw new AssertionError();
777 }
778 }
Jordan Halterman1cf233c2017-12-08 23:52:54 -0800779 }
780
781 protected void registerCallback(long id, String subject, CompletableFuture<byte[]> future) {
782 futures.put(id, new Callback(subject, future));
783 }
784
785 protected Callback completeCallback(long id) {
786 Callback callback = futures.remove(id);
787 if (callback != null) {
788 try {
Jordan Haltermanef92f192017-12-21 11:59:38 -0800789 RequestMonitor requestMonitor = requestMonitors.get(callback.type, RequestMonitor::new);
790 requestMonitor.addReplyTime(System.currentTimeMillis() - callback.time);
Jordan Halterman1cf233c2017-12-08 23:52:54 -0800791 } catch (ExecutionException e) {
792 throw new AssertionError();
793 }
794 }
795 return callback;
796 }
797
798 protected Callback failCallback(long id) {
799 return futures.remove(id);
800 }
801
802 @Override
803 public void close() {
804 if (closed.compareAndSet(false, true)) {
805 timeoutFuture.cancel(false);
806 for (Callback callback : futures.values()) {
807 callback.completeExceptionally(new ConnectException());
808 }
809 }
810 }
811 }
812
813 /**
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700814 * Local connection implementation.
815 */
Jordan Halterman1cf233c2017-12-08 23:52:54 -0800816 private final class LocalClientConnection extends AbstractClientConnection {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700817 @Override
Jordan Haltermane3813a92017-07-29 14:10:31 -0700818 public CompletableFuture<Void> sendAsync(InternalRequest message) {
819 BiConsumer<InternalRequest, ServerConnection> handler = handlers.get(message.subject());
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700820 if (handler != null) {
821 handler.accept(message, localServerConnection);
822 } else {
823 log.debug("No handler for message type {} from {}", message.type(), message.sender());
824 }
825 return CompletableFuture.completedFuture(null);
826 }
827
828 @Override
Jordan Haltermane3813a92017-07-29 14:10:31 -0700829 public CompletableFuture<byte[]> sendAndReceive(InternalRequest message) {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700830 CompletableFuture<byte[]> future = new CompletableFuture<>();
Jordan Halterman1cf233c2017-12-08 23:52:54 -0800831 future.whenComplete((r, e) -> completeCallback(message.id()));
832 registerCallback(message.id(), message.subject(), future);
Jordan Haltermane3813a92017-07-29 14:10:31 -0700833 BiConsumer<InternalRequest, ServerConnection> handler = handlers.get(message.subject());
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700834 if (handler != null) {
835 handler.accept(message, new LocalServerConnection(future));
836 } else {
837 log.debug("No handler for message type {} from {}", message.type(), message.sender());
Jordan Haltermane3813a92017-07-29 14:10:31 -0700838 new LocalServerConnection(future)
839 .reply(message, InternalReply.Status.ERROR_NO_HANDLER, Optional.empty());
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700840 }
841 return future;
842 }
843 }
844
845 /**
846 * Local server connection.
847 */
848 private final class LocalServerConnection implements ServerConnection {
849 private final CompletableFuture<byte[]> future;
850
851 LocalServerConnection(CompletableFuture<byte[]> future) {
852 this.future = future;
853 }
854
855 @Override
Jordan Haltermane3813a92017-07-29 14:10:31 -0700856 public void reply(InternalRequest message, InternalReply.Status status, Optional<byte[]> payload) {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700857 if (future != null) {
Jordan Haltermane3813a92017-07-29 14:10:31 -0700858 if (status == InternalReply.Status.OK) {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700859 future.complete(payload.orElse(EMPTY_PAYLOAD));
Jordan Haltermane3813a92017-07-29 14:10:31 -0700860 } else if (status == InternalReply.Status.ERROR_NO_HANDLER) {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700861 future.completeExceptionally(new MessagingException.NoRemoteHandler());
Jordan Haltermane3813a92017-07-29 14:10:31 -0700862 } else if (status == InternalReply.Status.ERROR_HANDLER_EXCEPTION) {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700863 future.completeExceptionally(new MessagingException.RemoteHandlerFailure());
Jordan Haltermane3813a92017-07-29 14:10:31 -0700864 } else if (status == InternalReply.Status.PROTOCOL_EXCEPTION) {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700865 future.completeExceptionally(new MessagingException.ProtocolException());
866 }
867 }
868 }
869 }
870
871 /**
872 * Remote connection implementation.
873 */
Jordan Halterman1cf233c2017-12-08 23:52:54 -0800874 private final class RemoteClientConnection extends AbstractClientConnection {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700875 private final Channel channel;
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700876
877 RemoteClientConnection(Channel channel) {
878 this.channel = channel;
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800879 }
880
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700881 @Override
Jordan Haltermane3813a92017-07-29 14:10:31 -0700882 public CompletableFuture<Void> sendAsync(InternalRequest message) {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700883 CompletableFuture<Void> future = new CompletableFuture<>();
884 channel.writeAndFlush(message).addListener(channelFuture -> {
885 if (!channelFuture.isSuccess()) {
886 future.completeExceptionally(channelFuture.cause());
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800887 } else {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700888 future.complete(null);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800889 }
890 });
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700891 return future;
892 }
893
894 @Override
Jordan Haltermane3813a92017-07-29 14:10:31 -0700895 public CompletableFuture<byte[]> sendAndReceive(InternalRequest message) {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700896 CompletableFuture<byte[]> future = new CompletableFuture<>();
Jordan Halterman1cf233c2017-12-08 23:52:54 -0800897 registerCallback(message.id(), message.subject(), future);
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700898 channel.writeAndFlush(message).addListener(channelFuture -> {
899 if (!channelFuture.isSuccess()) {
Jordan Halterman1cf233c2017-12-08 23:52:54 -0800900 Callback callback = failCallback(message.id());
901 if (callback != null) {
902 callback.completeExceptionally(channelFuture.cause());
903 }
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700904 }
905 });
906 return future;
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800907 }
908
909 /**
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700910 * Dispatches a message to a local handler.
911 *
912 * @param message the message to dispatch
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800913 */
Jordan Haltermane3813a92017-07-29 14:10:31 -0700914 private void dispatch(InternalReply message) {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700915 if (message.preamble() != preamble) {
Jordan Haltermane3813a92017-07-29 14:10:31 -0700916 log.debug("Received {} with invalid preamble", message.type());
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700917 return;
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800918 }
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700919
920 clockService.recordEventTime(message.time());
921
Jordan Halterman1cf233c2017-12-08 23:52:54 -0800922 Callback callback = completeCallback(message.id());
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700923 if (callback != null) {
Jordan Haltermane3813a92017-07-29 14:10:31 -0700924 if (message.status() == InternalReply.Status.OK) {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700925 callback.complete(message.payload());
Jordan Haltermane3813a92017-07-29 14:10:31 -0700926 } else if (message.status() == InternalReply.Status.ERROR_NO_HANDLER) {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700927 callback.completeExceptionally(new MessagingException.NoRemoteHandler());
Jordan Haltermane3813a92017-07-29 14:10:31 -0700928 } else if (message.status() == InternalReply.Status.ERROR_HANDLER_EXCEPTION) {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700929 callback.completeExceptionally(new MessagingException.RemoteHandlerFailure());
Jordan Haltermane3813a92017-07-29 14:10:31 -0700930 } else if (message.status() == InternalReply.Status.PROTOCOL_EXCEPTION) {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700931 callback.completeExceptionally(new MessagingException.ProtocolException());
932 }
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700933 } else {
Jordan Haltermane3813a92017-07-29 14:10:31 -0700934 log.debug("Received a reply for message id:[{}] "
935 + "but was unable to locate the"
936 + " request handle", message.id());
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700937 }
938 }
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700939 }
940
941 /**
942 * Remote server connection.
943 */
944 private final class RemoteServerConnection implements ServerConnection {
945 private final Channel channel;
946
947 RemoteServerConnection(Channel channel) {
948 this.channel = channel;
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800949 }
950
951 /**
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700952 * Dispatches a message to a local handler.
953 *
954 * @param message the message to dispatch
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800955 */
Jordan Haltermane3813a92017-07-29 14:10:31 -0700956 private void dispatch(InternalRequest message) {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700957 if (message.preamble() != preamble) {
958 log.debug("Received {} with invalid preamble from {}", message.type(), message.sender());
Jordan Haltermane3813a92017-07-29 14:10:31 -0700959 reply(message, InternalReply.Status.PROTOCOL_EXCEPTION, Optional.empty());
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700960 return;
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800961 }
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700962
963 clockService.recordEventTime(message.time());
964
Jordan Haltermane3813a92017-07-29 14:10:31 -0700965 BiConsumer<InternalRequest, ServerConnection> handler = handlers.get(message.subject());
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700966 if (handler != null) {
967 handler.accept(message, this);
968 } else {
969 log.debug("No handler for message type {} from {}", message.type(), message.sender());
Jordan Haltermane3813a92017-07-29 14:10:31 -0700970 reply(message, InternalReply.Status.ERROR_NO_HANDLER, Optional.empty());
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700971 }
972 }
973
974 @Override
Jordan Haltermane3813a92017-07-29 14:10:31 -0700975 public void reply(InternalRequest message, InternalReply.Status status, Optional<byte[]> payload) {
976 InternalReply response = new InternalReply(preamble,
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700977 clockService.timeNow(),
978 message.id(),
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700979 payload.orElse(EMPTY_PAYLOAD),
980 status);
981 channel.writeAndFlush(response);
982 }
983 }
984
985 /**
986 * Request-reply timeout history tracker.
987 */
Jordan Haltermanef92f192017-12-21 11:59:38 -0800988 private static final class RequestMonitor {
989 private final DescriptiveStatistics samples = new SynchronizedDescriptiveStatistics(WINDOW_SIZE);
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700990
991 /**
992 * Adds a reply time to the history.
993 *
994 * @param replyTime the reply time to add to the history
995 */
996 void addReplyTime(long replyTime) {
Jordan Haltermanef92f192017-12-21 11:59:38 -0800997 samples.addValue(replyTime);
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700998 }
999
1000 /**
Jordan Haltermanef92f192017-12-21 11:59:38 -08001001 * Returns a boolean indicating whether the given request should be timed out according to the elapsed time.
1002 *
1003 * @param elapsedTime the elapsed request time
1004 * @return indicates whether the request should be timed out
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -07001005 */
Jordan Haltermanef92f192017-12-21 11:59:38 -08001006 boolean isTimedOut(long elapsedTime) {
1007 return phi(elapsedTime) >= PHI_FAILURE_THRESHOLD;
1008 }
1009
1010 /**
1011 * Compute phi for the specified node id.
1012 *
1013 * @param elapsedTime the duration since the request was sent
1014 * @return phi value
1015 */
1016 private double phi(long elapsedTime) {
1017 if (samples.getN() < MIN_SAMPLES) {
1018 return 0.0;
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -07001019 }
Jordan Haltermanef92f192017-12-21 11:59:38 -08001020 return computePhi(samples, elapsedTime);
1021 }
1022
1023 /**
1024 * Computes the phi value from the given samples.
1025 *
1026 * @param samples the samples from which to compute phi
1027 * @param elapsedTime the duration since the request was sent
1028 * @return phi
1029 */
1030 private double computePhi(DescriptiveStatistics samples, long elapsedTime) {
1031 return samples.getN() > 0 ? PHI_FACTOR * elapsedTime / samples.getMean() : 100;
Aaron Kruglikov1b727382016-02-09 16:17:47 -08001032 }
1033 }
JunHuy Lam39eb4292015-06-26 17:24:23 +09001034}