blob: 80f0a2034aada4ef505d11d04ee61ecac848e35a [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 Haltermanf7c7f6f2017-05-05 03:02:34 -070052import java.util.function.Function;
Aaron Kruglikov1b727382016-02-09 16:17:47 -080053
Jordan Halterman5e32dc92018-01-13 14:10:56 -080054import com.google.common.base.Throwables;
Jordan Halterman66e6e3b2017-07-10 11:26:34 -070055import com.google.common.cache.Cache;
56import com.google.common.cache.CacheBuilder;
57import com.google.common.collect.Lists;
58import com.google.common.collect.Maps;
59import com.google.common.util.concurrent.MoreExecutors;
60import io.netty.bootstrap.Bootstrap;
61import io.netty.bootstrap.ServerBootstrap;
62import io.netty.buffer.PooledByteBufAllocator;
63import io.netty.channel.Channel;
64import io.netty.channel.ChannelFuture;
65import io.netty.channel.ChannelHandler;
66import io.netty.channel.ChannelHandlerContext;
67import io.netty.channel.ChannelInitializer;
68import io.netty.channel.ChannelOption;
69import io.netty.channel.EventLoopGroup;
70import io.netty.channel.ServerChannel;
71import io.netty.channel.SimpleChannelInboundHandler;
72import io.netty.channel.WriteBufferWaterMark;
73import io.netty.channel.epoll.EpollEventLoopGroup;
74import io.netty.channel.epoll.EpollServerSocketChannel;
75import io.netty.channel.epoll.EpollSocketChannel;
76import io.netty.channel.nio.NioEventLoopGroup;
77import io.netty.channel.socket.SocketChannel;
78import io.netty.channel.socket.nio.NioServerSocketChannel;
79import io.netty.channel.socket.nio.NioSocketChannel;
80import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics;
81import org.apache.commons.math3.stat.descriptive.SynchronizedDescriptiveStatistics;
82import org.apache.felix.scr.annotations.Activate;
83import org.apache.felix.scr.annotations.Component;
84import org.apache.felix.scr.annotations.Deactivate;
85import org.apache.felix.scr.annotations.Reference;
86import org.apache.felix.scr.annotations.ReferenceCardinality;
87import org.apache.felix.scr.annotations.Service;
88import org.onosproject.cluster.ClusterMetadataService;
89import org.onosproject.cluster.ControllerNode;
90import org.onosproject.core.HybridLogicalClockService;
91import org.onosproject.store.cluster.messaging.Endpoint;
92import org.onosproject.store.cluster.messaging.MessagingException;
93import org.onosproject.store.cluster.messaging.MessagingService;
Jordan Halterman66e6e3b2017-07-10 11:26:34 -070094import org.slf4j.Logger;
95import org.slf4j.LoggerFactory;
96
Yuta HIGUCHI90a16892016-07-20 20:36:08 -070097import static org.onlab.util.Tools.groupedThreads;
Heedo Kang4a47a302016-02-29 17:40:23 +090098import static org.onosproject.security.AppGuard.checkPermission;
99import static org.onosproject.security.AppPermission.Type.CLUSTER_WRITE;
100
Madan Jampaniafeebbd2015-05-19 15:26:01 -0700101/**
102 * Netty based MessagingService.
103 */
Sho SHIMIZU5c396e32016-08-12 15:19:12 -0700104@Component(immediate = true)
Madan Jampaniafeebbd2015-05-19 15:26:01 -0700105@Service
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800106public class NettyMessagingManager implements MessagingService {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700107 private static final long DEFAULT_TIMEOUT_MILLIS = 500;
Jordan Halterman66e6e3b2017-07-10 11:26:34 -0700108 private static final long HISTORY_EXPIRE_MILLIS = Duration.ofMinutes(1).toMillis();
Jordan Halterman5a5ed592017-09-12 15:09:03 -0700109 private static final long MIN_TIMEOUT_MILLIS = 250;
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700110 private static final long MAX_TIMEOUT_MILLIS = 5000;
111 private static final long TIMEOUT_INTERVAL = 50;
112 private static final int WINDOW_SIZE = 100;
113 private static final double TIMEOUT_MULTIPLIER = 2.5;
Jordan Halterman66e6e3b2017-07-10 11:26:34 -0700114 private static final int CHANNEL_POOL_SIZE = 8;
Madan Jampaniafeebbd2015-05-19 15:26:01 -0700115
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700116 private static final byte[] EMPTY_PAYLOAD = new byte[0];
117
Madan Jampaniafeebbd2015-05-19 15:26:01 -0700118 private final Logger log = LoggerFactory.getLogger(getClass());
119
Jordan Haltermanfe2f93d2017-12-08 23:52:54 -0800120 private final LocalClientConnection localClientConnection = new LocalClientConnection();
121 private final LocalServerConnection localServerConnection = new LocalServerConnection(null);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800122
Brian O'Connor740e98c2017-06-29 17:07:17 -0700123 //TODO CONFIG_DIR is duplicated from ConfigFileBasedClusterMetadataProvider
124 private static final String CONFIG_DIR = "../config";
125 private static final String KS_FILE_NAME = "onos.jks";
126 private static final File DEFAULT_KS_FILE = new File(CONFIG_DIR, KS_FILE_NAME);
127 private static final String DEFAULT_KS_PASSWORD = "changeit";
128
Madan Jampani05833872016-07-12 23:01:39 -0700129 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
130 protected HybridLogicalClockService clockService;
131
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700132 private Endpoint localEndpoint;
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800133 private int preamble;
134 private final AtomicBoolean started = new AtomicBoolean(false);
Jordan Haltermane3813a92017-07-29 14:10:31 -0700135 private final Map<String, BiConsumer<InternalRequest, ServerConnection>> handlers = new ConcurrentHashMap<>();
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700136 private final Map<Channel, RemoteClientConnection> clientConnections = Maps.newConcurrentMap();
137 private final Map<Channel, RemoteServerConnection> serverConnections = Maps.newConcurrentMap();
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800138 private final AtomicLong messageIdGenerator = new AtomicLong(0);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800139
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700140 private ScheduledFuture<?> timeoutFuture;
141
Jordan Halterman66e6e3b2017-07-10 11:26:34 -0700142 private final Map<Endpoint, List<CompletableFuture<Channel>>> channels = Maps.newConcurrentMap();
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800143
144 private EventLoopGroup serverGroup;
145 private EventLoopGroup clientGroup;
146 private Class<? extends ServerChannel> serverChannelClass;
147 private Class<? extends Channel> clientChannelClass;
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700148 private ScheduledExecutorService timeoutExecutor;
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800149
Brian O'Connor740e98c2017-06-29 17:07:17 -0700150 protected static final boolean TLS_ENABLED = true;
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800151 protected static final boolean TLS_DISABLED = false;
Brian O'Connor740e98c2017-06-29 17:07:17 -0700152 protected boolean enableNettyTls = TLS_ENABLED;
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800153
Brian O'Connor740e98c2017-06-29 17:07:17 -0700154 protected TrustManagerFactory trustManager;
155 protected KeyManagerFactory keyManager;
JunHuy Lam39eb4292015-06-26 17:24:23 +0900156
Madan Jampaniafeebbd2015-05-19 15:26:01 -0700157 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Madan Jampaniec1df022015-10-13 21:23:03 -0700158 protected ClusterMetadataService clusterMetadataService;
Madan Jampaniafeebbd2015-05-19 15:26:01 -0700159
160 @Activate
161 public void activate() throws Exception {
Madan Jampaniec1df022015-10-13 21:23:03 -0700162 ControllerNode localNode = clusterMetadataService.getLocalNode();
Jonathan Hartd9df7bd2015-11-10 17:10:25 -0800163 getTlsParameters();
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800164
165 if (started.get()) {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700166 log.warn("Already running at local endpoint: {}", localEndpoint);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800167 return;
168 }
169 this.preamble = clusterMetadataService.getClusterMetadata().getName().hashCode();
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700170 this.localEndpoint = new Endpoint(localNode.ip(), localNode.tcpPort());
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800171 initEventLoopGroup();
172 startAcceptingConnections();
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700173 timeoutExecutor = Executors.newSingleThreadScheduledExecutor(
174 groupedThreads("NettyMessagingEvt", "timeout", log));
175 timeoutFuture = timeoutExecutor.scheduleAtFixedRate(
176 this::timeoutAllCallbacks, TIMEOUT_INTERVAL, TIMEOUT_INTERVAL, TimeUnit.MILLISECONDS);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800177 started.set(true);
Madan Jampaniafeebbd2015-05-19 15:26:01 -0700178 log.info("Started");
179 }
180
181 @Deactivate
182 public void deactivate() throws Exception {
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800183 if (started.get()) {
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800184 serverGroup.shutdownGracefully();
185 clientGroup.shutdownGracefully();
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700186 timeoutFuture.cancel(false);
187 timeoutExecutor.shutdown();
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800188 started.set(false);
189 }
Madan Jampaniafeebbd2015-05-19 15:26:01 -0700190 log.info("Stopped");
191 }
JunHuy Lam39eb4292015-06-26 17:24:23 +0900192
Jonathan Hartd9df7bd2015-11-10 17:10:25 -0800193 private void getTlsParameters() {
Brian O'Connor740e98c2017-06-29 17:07:17 -0700194 // default is TLS enabled unless key stores cannot be loaded
195 enableNettyTls = Boolean.parseBoolean(System.getProperty("enableNettyTLS", Boolean.toString(TLS_ENABLED)));
196
Jonathan Hartd9df7bd2015-11-10 17:10:25 -0800197 if (enableNettyTls) {
Brian O'Connor740e98c2017-06-29 17:07:17 -0700198 enableNettyTls = loadKeyStores();
199 }
200 }
201
202 private boolean loadKeyStores() {
203 // Maintain a local copy of the trust and key managers in case anything goes wrong
204 TrustManagerFactory tmf;
205 KeyManagerFactory kmf;
206 try {
207 String ksLocation = System.getProperty("javax.net.ssl.keyStore", DEFAULT_KS_FILE.toString());
208 String tsLocation = System.getProperty("javax.net.ssl.trustStore", DEFAULT_KS_FILE.toString());
209 char[] ksPwd = System.getProperty("javax.net.ssl.keyStorePassword", DEFAULT_KS_PASSWORD).toCharArray();
210 char[] tsPwd = System.getProperty("javax.net.ssl.trustStorePassword", DEFAULT_KS_PASSWORD).toCharArray();
211
212 tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
213 KeyStore ts = KeyStore.getInstance("JKS");
214 ts.load(new FileInputStream(tsLocation), tsPwd);
215 tmf.init(ts);
216
217 kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
218 KeyStore ks = KeyStore.getInstance("JKS");
219 ks.load(new FileInputStream(ksLocation), ksPwd);
220 kmf.init(ks, ksPwd);
221 if (log.isInfoEnabled()) {
222 logKeyStore(ks, ksLocation, ksPwd);
JunHuy Lam39eb4292015-06-26 17:24:23 +0900223 }
Brian O'Connor740e98c2017-06-29 17:07:17 -0700224 } catch (FileNotFoundException e) {
225 log.warn("Disabling TLS for intra-cluster messaging; Could not load cluster key store: {}", e.getMessage());
226 return TLS_DISABLED;
227 } catch (Exception e) {
228 //TODO we might want to catch exceptions more specifically
229 log.error("Error loading key store; disabling TLS for intra-cluster messaging", e);
230 return TLS_DISABLED;
231 }
232 this.trustManager = tmf;
233 this.keyManager = kmf;
234 return TLS_ENABLED;
235 }
236
237 private void logKeyStore(KeyStore ks, String ksLocation, char[] ksPwd) {
238 if (log.isInfoEnabled()) {
239 log.info("Loaded cluster key store from: {}", ksLocation);
240 try {
241 for (Enumeration<String> e = ks.aliases(); e.hasMoreElements();) {
242 String alias = e.nextElement();
243 Key key = ks.getKey(alias, ksPwd);
244 Certificate[] certs = ks.getCertificateChain(alias);
245 log.debug("{} -> {}", alias, certs);
246 final byte[] encodedKey;
247 if (certs != null && certs.length > 0) {
248 encodedKey = certs[0].getEncoded();
249 } else {
250 log.info("Could not find cert chain for {}, using fingerprint of key instead...", alias);
251 encodedKey = key.getEncoded();
252 }
253 // Compute the certificate's fingerprint (use the key if certificate cannot be found)
254 MessageDigest digest = MessageDigest.getInstance("SHA1");
255 digest.update(encodedKey);
256 StringJoiner fingerprint = new StringJoiner(":");
257 for (byte b : digest.digest()) {
258 fingerprint.add(String.format("%02X", b));
259 }
260 log.info("{} -> {}", alias, fingerprint);
261 }
262 } catch (Exception e) {
263 log.warn("Unable to print contents of key store: {}", ksLocation, e);
JunHuy Lam39eb4292015-06-26 17:24:23 +0900264 }
265 }
266 }
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700267
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800268 private void initEventLoopGroup() {
269 // try Epoll first and if that does work, use nio.
270 try {
Yuta HIGUCHI90a16892016-07-20 20:36:08 -0700271 clientGroup = new EpollEventLoopGroup(0, groupedThreads("NettyMessagingEvt", "epollC-%d", log));
272 serverGroup = new EpollEventLoopGroup(0, groupedThreads("NettyMessagingEvt", "epollS-%d", log));
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800273 serverChannelClass = EpollServerSocketChannel.class;
274 clientChannelClass = EpollSocketChannel.class;
275 return;
276 } catch (Throwable e) {
277 log.debug("Failed to initialize native (epoll) transport. "
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700278 + "Reason: {}. Proceeding with nio.", e.getMessage());
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800279 }
Yuta HIGUCHI90a16892016-07-20 20:36:08 -0700280 clientGroup = new NioEventLoopGroup(0, groupedThreads("NettyMessagingEvt", "nioC-%d", log));
281 serverGroup = new NioEventLoopGroup(0, groupedThreads("NettyMessagingEvt", "nioS-%d", log));
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800282 serverChannelClass = NioServerSocketChannel.class;
283 clientChannelClass = NioSocketChannel.class;
284 }
285
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700286 /**
287 * Times out response callbacks.
288 */
289 private void timeoutAllCallbacks() {
290 // Iterate through all connections and time out callbacks.
Jordan Haltermanfe2f93d2017-12-08 23:52:54 -0800291 localClientConnection.timeoutCallbacks();
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700292 for (RemoteClientConnection connection : clientConnections.values()) {
293 connection.timeoutCallbacks();
294 }
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700295 }
296
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800297 @Override
298 public CompletableFuture<Void> sendAsync(Endpoint ep, String type, byte[] payload) {
Heedo Kang4a47a302016-02-29 17:40:23 +0900299 checkPermission(CLUSTER_WRITE);
Jordan Haltermane3813a92017-07-29 14:10:31 -0700300 InternalRequest message = new InternalRequest(preamble,
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700301 clockService.timeNow(),
302 messageIdGenerator.incrementAndGet(),
303 localEndpoint,
304 type,
305 payload);
Jordan Halterman66e6e3b2017-07-10 11:26:34 -0700306 return executeOnPooledConnection(ep, type, c -> c.sendAsync(message), MoreExecutors.directExecutor());
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800307 }
308
309 @Override
310 public CompletableFuture<byte[]> sendAndReceive(Endpoint ep, String type, byte[] payload) {
Heedo Kang4a47a302016-02-29 17:40:23 +0900311 checkPermission(CLUSTER_WRITE);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800312 return sendAndReceive(ep, type, payload, MoreExecutors.directExecutor());
313 }
314
315 @Override
316 public CompletableFuture<byte[]> sendAndReceive(Endpoint ep, String type, byte[] payload, Executor executor) {
Heedo Kang4a47a302016-02-29 17:40:23 +0900317 checkPermission(CLUSTER_WRITE);
Jordan Haltermanb34d30b2017-08-28 15:35:03 -0700318 long messageId = messageIdGenerator.incrementAndGet();
Jordan Haltermane3813a92017-07-29 14:10:31 -0700319 InternalRequest message = new InternalRequest(preamble,
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700320 clockService.timeNow(),
321 messageId,
322 localEndpoint,
323 type,
324 payload);
Jordan Halterman66e6e3b2017-07-10 11:26:34 -0700325 return executeOnPooledConnection(ep, type, c -> c.sendAndReceive(message), executor);
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700326 }
Jordan Halterman041534b2017-03-21 10:37:33 -0700327
Jordan Halterman66e6e3b2017-07-10 11:26:34 -0700328 private List<CompletableFuture<Channel>> getChannelPool(Endpoint endpoint) {
329 return channels.computeIfAbsent(endpoint, e -> {
330 List<CompletableFuture<Channel>> defaultList = new ArrayList<>(CHANNEL_POOL_SIZE);
331 for (int i = 0; i < CHANNEL_POOL_SIZE; i++) {
332 defaultList.add(null);
333 }
334 return Lists.newCopyOnWriteArrayList(defaultList);
335 });
336 }
337
338 private int getChannelOffset(String messageType) {
339 return Math.abs(messageType.hashCode() % CHANNEL_POOL_SIZE);
340 }
341
Jordan Halterman7bf921c2018-02-08 14:45:20 -0800342 private CompletableFuture<Channel> getChannel(Endpoint endpoint, String messageType) {
Jordan Halterman5e32dc92018-01-13 14:10:56 -0800343 List<CompletableFuture<Channel>> channelPool = getChannelPool(endpoint);
Jordan Halterman7bf921c2018-02-08 14:45:20 -0800344 int offset = getChannelOffset(messageType);
Jordan Halterman5e32dc92018-01-13 14:10:56 -0800345
Jordan Halterman5e32dc92018-01-13 14:10:56 -0800346 CompletableFuture<Channel> channelFuture = channelPool.get(offset);
347 if (channelFuture == null || channelFuture.isCompletedExceptionally()) {
348 synchronized (channelPool) {
349 channelFuture = channelPool.get(offset);
350 if (channelFuture == null || channelFuture.isCompletedExceptionally()) {
351 channelFuture = openChannel(endpoint);
352 channelPool.set(offset, channelFuture);
353 }
354 }
355 }
356
Jordan Halterman7bf921c2018-02-08 14:45:20 -0800357 CompletableFuture<Channel> future = new CompletableFuture<>();
Jordan Halterman5e32dc92018-01-13 14:10:56 -0800358 final CompletableFuture<Channel> finalFuture = channelFuture;
359 finalFuture.whenComplete((channel, error) -> {
360 if (error == null) {
361 if (!channel.isActive()) {
Jordan Halterman7bf921c2018-02-08 14:45:20 -0800362 CompletableFuture<Channel> currentFuture;
Jordan Halterman5e32dc92018-01-13 14:10:56 -0800363 synchronized (channelPool) {
364 currentFuture = channelPool.get(offset);
365 if (currentFuture == finalFuture) {
366 channelPool.set(offset, null);
367 }
368 }
Jordan Halterman7bf921c2018-02-08 14:45:20 -0800369
370 ClientConnection connection = clientConnections.remove(channel);
371 if (connection != null) {
372 connection.close();
373 }
374
Jordan Halterman5e32dc92018-01-13 14:10:56 -0800375 if (currentFuture == finalFuture) {
Jordan Halterman7bf921c2018-02-08 14:45:20 -0800376 getChannel(endpoint, messageType).whenComplete((recursiveResult, recursiveError) -> {
377 if (recursiveError == null) {
378 future.complete(recursiveResult);
379 } else {
380 future.completeExceptionally(recursiveError);
381 }
382 });
Jordan Halterman5e32dc92018-01-13 14:10:56 -0800383 } else {
384 currentFuture.whenComplete((recursiveResult, recursiveError) -> {
385 if (recursiveError == null) {
Jordan Halterman7bf921c2018-02-08 14:45:20 -0800386 future.complete(recursiveResult);
Jordan Halterman5e32dc92018-01-13 14:10:56 -0800387 } else {
388 future.completeExceptionally(recursiveError);
389 }
390 });
391 }
392 } else {
Jordan Halterman7bf921c2018-02-08 14:45:20 -0800393 future.complete(channel);
Jordan Halterman5e32dc92018-01-13 14:10:56 -0800394 }
Ray Milkey8df1f442018-01-23 23:32:20 +0000395 } else {
Jordan Halterman5e32dc92018-01-13 14:10:56 -0800396 future.completeExceptionally(error);
Ray Milkey8df1f442018-01-23 23:32:20 +0000397 }
398 });
Jordan Halterman7bf921c2018-02-08 14:45:20 -0800399 return future;
400 }
401
402 private <T> CompletableFuture<T> executeOnPooledConnection(
403 Endpoint endpoint,
404 String type,
405 Function<ClientConnection, CompletableFuture<T>> callback,
406 Executor executor) {
407 CompletableFuture<T> future = new CompletableFuture<T>();
408 executeOnPooledConnection(endpoint, type, callback, executor, future);
409 return future;
410 }
411
412 private <T> void executeOnPooledConnection(
413 Endpoint endpoint,
414 String type,
415 Function<ClientConnection, CompletableFuture<T>> callback,
416 Executor executor,
417 CompletableFuture<T> future) {
418 if (endpoint.equals(localEndpoint)) {
419 callback.apply(localClientConnection).whenComplete((result, error) -> {
420 if (error == null) {
421 executor.execute(() -> future.complete(result));
422 } else {
423 executor.execute(() -> future.completeExceptionally(error));
424 }
425 });
426 return;
427 }
428
429 getChannel(endpoint, type).whenComplete((channel, channelError) -> {
430 if (channelError == null) {
431 ClientConnection connection = clientConnections.computeIfAbsent(channel, RemoteClientConnection::new);
432 callback.apply(connection).whenComplete((result, sendError) -> {
433 if (sendError == null) {
434 executor.execute(() -> future.complete(result));
435 } else {
436 Throwable cause = Throwables.getRootCause(sendError);
437 if (!(cause instanceof TimeoutException) && !(cause instanceof MessagingException)) {
438 channel.close().addListener(f -> {
439 connection.close();
440 clientConnections.remove(channel);
441 });
442 }
443 executor.execute(() -> future.completeExceptionally(sendError));
444 }
445 });
446 } else {
447 executor.execute(() -> future.completeExceptionally(channelError));
448 }
449 });
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800450 }
451
452 @Override
453 public void registerHandler(String type, BiConsumer<Endpoint, byte[]> handler, Executor executor) {
Heedo Kang4a47a302016-02-29 17:40:23 +0900454 checkPermission(CLUSTER_WRITE);
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700455 handlers.put(type, (message, connection) -> executor.execute(() ->
456 handler.accept(message.sender(), message.payload())));
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800457 }
458
459 @Override
460 public void registerHandler(String type, BiFunction<Endpoint, byte[], byte[]> handler, Executor executor) {
Heedo Kang4a47a302016-02-29 17:40:23 +0900461 checkPermission(CLUSTER_WRITE);
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700462 handlers.put(type, (message, connection) -> executor.execute(() -> {
Madan Jampania9e70a62016-03-02 16:28:18 -0800463 byte[] responsePayload = null;
Jordan Haltermane3813a92017-07-29 14:10:31 -0700464 InternalReply.Status status = InternalReply.Status.OK;
Madan Jampania9e70a62016-03-02 16:28:18 -0800465 try {
466 responsePayload = handler.apply(message.sender(), message.payload());
467 } catch (Exception e) {
Jordan Haltermanb6ee9e92017-06-21 15:26:28 -0700468 log.debug("An error occurred in a message handler: {}", e);
Jordan Haltermane3813a92017-07-29 14:10:31 -0700469 status = InternalReply.Status.ERROR_HANDLER_EXCEPTION;
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800470 }
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700471 connection.reply(message, status, Optional.ofNullable(responsePayload));
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800472 }));
473 }
474
475 @Override
476 public void registerHandler(String type, BiFunction<Endpoint, byte[], CompletableFuture<byte[]>> handler) {
Heedo Kang4a47a302016-02-29 17:40:23 +0900477 checkPermission(CLUSTER_WRITE);
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700478 handlers.put(type, (message, connection) -> {
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800479 handler.apply(message.sender(), message.payload()).whenComplete((result, error) -> {
Jordan Haltermane3813a92017-07-29 14:10:31 -0700480 InternalReply.Status status;
Jordan Haltermanb6ee9e92017-06-21 15:26:28 -0700481 if (error == null) {
Jordan Haltermane3813a92017-07-29 14:10:31 -0700482 status = InternalReply.Status.OK;
Jordan Haltermanb6ee9e92017-06-21 15:26:28 -0700483 } else {
484 log.debug("An error occurred in a message handler: {}", error);
Jordan Haltermane3813a92017-07-29 14:10:31 -0700485 status = InternalReply.Status.ERROR_HANDLER_EXCEPTION;
Jordan Haltermanb6ee9e92017-06-21 15:26:28 -0700486 }
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700487 connection.reply(message, status, Optional.ofNullable(result));
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800488 });
489 });
490 }
491
492 @Override
493 public void unregisterHandler(String type) {
Heedo Kang4a47a302016-02-29 17:40:23 +0900494 checkPermission(CLUSTER_WRITE);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800495 handlers.remove(type);
496 }
497
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700498 private Bootstrap bootstrapClient(Endpoint endpoint) {
499 Bootstrap bootstrap = new Bootstrap();
500 bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
501 bootstrap.option(ChannelOption.WRITE_BUFFER_WATER_MARK,
502 new WriteBufferWaterMark(10 * 32 * 1024, 10 * 64 * 1024));
503 bootstrap.option(ChannelOption.SO_SNDBUF, 1048576);
504 bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000);
505 bootstrap.group(clientGroup);
506 // TODO: Make this faster:
507 // http://normanmaurer.me/presentations/2014-facebook-eng-netty/slides.html#37.0
508 bootstrap.channel(clientChannelClass);
509 bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
510 bootstrap.remoteAddress(endpoint.host().toInetAddress(), endpoint.port());
Jordan Halterman66e6e3b2017-07-10 11:26:34 -0700511 if (enableNettyTls) {
512 bootstrap.handler(new SslClientCommunicationChannelInitializer());
513 } else {
514 bootstrap.handler(new BasicChannelInitializer());
515 }
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700516 return bootstrap;
517 }
518
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800519 private void startAcceptingConnections() throws InterruptedException {
520 ServerBootstrap b = new ServerBootstrap();
Jon Hall9a44d6a2017-03-02 18:14:37 -0800521 b.childOption(ChannelOption.WRITE_BUFFER_WATER_MARK,
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700522 new WriteBufferWaterMark(8 * 1024, 32 * 1024));
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800523 b.option(ChannelOption.SO_RCVBUF, 1048576);
524 b.option(ChannelOption.TCP_NODELAY, true);
Yuta HIGUCHIb47c9532016-08-22 09:41:23 -0700525 b.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800526 b.group(serverGroup, clientGroup);
527 b.channel(serverChannelClass);
528 if (enableNettyTls) {
529 b.childHandler(new SslServerCommunicationChannelInitializer());
530 } else {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700531 b.childHandler(new BasicChannelInitializer());
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800532 }
533 b.option(ChannelOption.SO_BACKLOG, 128);
534 b.childOption(ChannelOption.SO_KEEPALIVE, true);
535
536 // Bind and start to accept incoming connections.
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700537 b.bind(localEndpoint.port()).sync().addListener(future -> {
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800538 if (future.isSuccess()) {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700539 log.info("{} accepting incoming connections on port {}",
540 localEndpoint.host(), localEndpoint.port());
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800541 } else {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700542 log.warn("{} failed to bind to port {} due to {}",
543 localEndpoint.host(), localEndpoint.port(), future.cause());
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800544 }
545 });
546 }
547
Jordan Halterman66e6e3b2017-07-10 11:26:34 -0700548 private CompletableFuture<Channel> openChannel(Endpoint ep) {
549 Bootstrap bootstrap = bootstrapClient(ep);
550 CompletableFuture<Channel> retFuture = new CompletableFuture<>();
551 ChannelFuture f = bootstrap.connect();
552
553 f.addListener(future -> {
554 if (future.isSuccess()) {
555 retFuture.complete(f.channel());
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800556 } else {
Jordan Halterman66e6e3b2017-07-10 11:26:34 -0700557 retFuture.completeExceptionally(future.cause());
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800558 }
Jordan Halterman66e6e3b2017-07-10 11:26:34 -0700559 });
560 log.debug("Established a new connection to {}", ep);
561 return retFuture;
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800562 }
563
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700564 /**
565 * Channel initializer for TLS servers.
566 */
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800567 private class SslServerCommunicationChannelInitializer extends ChannelInitializer<SocketChannel> {
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800568 private final ChannelHandler dispatcher = new InboundMessageDispatcher();
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800569
570 @Override
571 protected void initChannel(SocketChannel channel) throws Exception {
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800572 SSLContext serverContext = SSLContext.getInstance("TLS");
Brian O'Connor740e98c2017-06-29 17:07:17 -0700573 serverContext.init(keyManager.getKeyManagers(), trustManager.getTrustManagers(), null);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800574
575 SSLEngine serverSslEngine = serverContext.createSSLEngine();
576
577 serverSslEngine.setNeedClientAuth(true);
578 serverSslEngine.setUseClientMode(false);
579 serverSslEngine.setEnabledProtocols(serverSslEngine.getSupportedProtocols());
580 serverSslEngine.setEnabledCipherSuites(serverSslEngine.getSupportedCipherSuites());
581 serverSslEngine.setEnableSessionCreation(true);
582
583 channel.pipeline().addLast("ssl", new io.netty.handler.ssl.SslHandler(serverSslEngine))
Jordan Haltermane3813a92017-07-29 14:10:31 -0700584 .addLast("encoder", new MessageEncoder(localEndpoint, preamble))
Madan Jampanib825aeb2016-04-01 15:18:25 -0700585 .addLast("decoder", new MessageDecoder())
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800586 .addLast("handler", dispatcher);
587 }
588 }
589
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700590 /**
591 * Channel initializer for TLS clients.
592 */
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800593 private class SslClientCommunicationChannelInitializer extends ChannelInitializer<SocketChannel> {
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800594 private final ChannelHandler dispatcher = new InboundMessageDispatcher();
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800595
596 @Override
597 protected void initChannel(SocketChannel channel) throws Exception {
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800598 SSLContext clientContext = SSLContext.getInstance("TLS");
Brian O'Connor740e98c2017-06-29 17:07:17 -0700599 clientContext.init(keyManager.getKeyManagers(), trustManager.getTrustManagers(), null);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800600
601 SSLEngine clientSslEngine = clientContext.createSSLEngine();
602
603 clientSslEngine.setUseClientMode(true);
604 clientSslEngine.setEnabledProtocols(clientSslEngine.getSupportedProtocols());
605 clientSslEngine.setEnabledCipherSuites(clientSslEngine.getSupportedCipherSuites());
606 clientSslEngine.setEnableSessionCreation(true);
607
608 channel.pipeline().addLast("ssl", new io.netty.handler.ssl.SslHandler(clientSslEngine))
Jordan Haltermane3813a92017-07-29 14:10:31 -0700609 .addLast("encoder", new MessageEncoder(localEndpoint, preamble))
Madan Jampanib825aeb2016-04-01 15:18:25 -0700610 .addLast("decoder", new MessageDecoder())
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800611 .addLast("handler", dispatcher);
612 }
613 }
614
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700615 /**
616 * Channel initializer for basic connections.
617 */
618 private class BasicChannelInitializer extends ChannelInitializer<SocketChannel> {
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800619 private final ChannelHandler dispatcher = new InboundMessageDispatcher();
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800620
621 @Override
622 protected void initChannel(SocketChannel channel) throws Exception {
623 channel.pipeline()
Jordan Haltermane3813a92017-07-29 14:10:31 -0700624 .addLast("encoder", new MessageEncoder(localEndpoint, preamble))
Madan Jampanib825aeb2016-04-01 15:18:25 -0700625 .addLast("decoder", new MessageDecoder())
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800626 .addLast("handler", dispatcher);
627 }
628 }
629
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700630 /**
631 * Channel inbound handler that dispatches messages to the appropriate handler.
632 */
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800633 @ChannelHandler.Sharable
Yuta HIGUCHIc012dda2016-08-17 00:43:46 -0700634 private class InboundMessageDispatcher extends SimpleChannelInboundHandler<Object> {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700635 // Effectively SimpleChannelInboundHandler<InternalMessage>,
636 // had to specify <Object> to avoid Class Loader not being able to find some classes.
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800637
638 @Override
Yuta HIGUCHIc012dda2016-08-17 00:43:46 -0700639 protected void channelRead0(ChannelHandlerContext ctx, Object rawMessage) throws Exception {
640 InternalMessage message = (InternalMessage) rawMessage;
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800641 try {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700642 if (message.isRequest()) {
643 RemoteServerConnection connection =
644 serverConnections.computeIfAbsent(ctx.channel(), RemoteServerConnection::new);
Jordan Haltermane3813a92017-07-29 14:10:31 -0700645 connection.dispatch((InternalRequest) message);
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700646 } else {
647 RemoteClientConnection connection =
648 clientConnections.computeIfAbsent(ctx.channel(), RemoteClientConnection::new);
Jordan Haltermane3813a92017-07-29 14:10:31 -0700649 connection.dispatch((InternalReply) message);
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700650 }
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800651 } catch (RejectedExecutionException e) {
652 log.warn("Unable to dispatch message due to {}", e.getMessage());
653 }
654 }
655
656 @Override
657 public void exceptionCaught(ChannelHandlerContext context, Throwable cause) {
658 log.error("Exception inside channel handling pipeline.", cause);
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700659
660 RemoteClientConnection clientConnection = clientConnections.remove(context.channel());
661 if (clientConnection != null) {
662 clientConnection.close();
663 }
664
665 RemoteServerConnection serverConnection = serverConnections.remove(context.channel());
666 if (serverConnection != null) {
667 serverConnection.close();
668 }
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800669 context.close();
670 }
Yuta HIGUCHIc012dda2016-08-17 00:43:46 -0700671
Jordan Halterman5e32dc92018-01-13 14:10:56 -0800672 @Override
673 public void channelInactive(ChannelHandlerContext context) throws Exception {
674 RemoteClientConnection clientConnection = clientConnections.remove(context.channel());
675 if (clientConnection != null) {
676 clientConnection.close();
677 }
678
679 RemoteServerConnection serverConnection = serverConnections.remove(context.channel());
680 if (serverConnection != null) {
681 serverConnection.close();
682 }
683 context.close();
684 }
685
Yuta HIGUCHIc012dda2016-08-17 00:43:46 -0700686 /**
687 * Returns true if the given message should be handled.
688 *
689 * @param msg inbound message
690 * @return true if {@code msg} is {@link InternalMessage} instance.
Yuta HIGUCHIc012dda2016-08-17 00:43:46 -0700691 * @see SimpleChannelInboundHandler#acceptInboundMessage(Object)
692 */
693 @Override
694 public final boolean acceptInboundMessage(Object msg) {
695 return msg instanceof InternalMessage;
696 }
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800697 }
Yuta HIGUCHIc012dda2016-08-17 00:43:46 -0700698
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700699 /**
700 * Wraps a {@link CompletableFuture} and tracks its type and creation time.
701 */
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800702 private final class Callback {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700703 private final String type;
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800704 private final CompletableFuture<byte[]> future;
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700705 private final long time = System.currentTimeMillis();
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800706
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700707 Callback(String type, CompletableFuture<byte[]> future) {
708 this.type = type;
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800709 this.future = future;
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800710 }
711
712 public void complete(byte[] value) {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700713 future.complete(value);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800714 }
715
716 public void completeExceptionally(Throwable error) {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700717 future.completeExceptionally(error);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800718 }
719 }
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800720
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700721 /**
722 * Represents the client side of a connection to a local or remote server.
723 */
724 private interface ClientConnection {
725
726 /**
727 * Sends a message to the other side of the connection.
728 *
729 * @param message the message to send
730 * @return a completable future to be completed once the message has been sent
731 */
Jordan Haltermane3813a92017-07-29 14:10:31 -0700732 CompletableFuture<Void> sendAsync(InternalRequest message);
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700733
734 /**
735 * Sends a message to the other side of the connection, awaiting a reply.
736 *
737 * @param message the message to send
738 * @return a completable future to be completed once a reply is received or the request times out
739 */
Jordan Haltermane3813a92017-07-29 14:10:31 -0700740 CompletableFuture<byte[]> sendAndReceive(InternalRequest message);
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700741
742 /**
743 * Closes the connection.
744 */
745 default void close() {
746 }
747 }
748
749 /**
750 * Represents the server side of a connection.
751 */
752 private interface ServerConnection {
753
754 /**
755 * Sends a reply to the other side of the connection.
756 *
757 * @param message the message to which to reply
Jordan Haltermanfe2f93d2017-12-08 23:52:54 -0800758 * @param status the reply status
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700759 * @param payload the response payload
760 */
Jordan Haltermane3813a92017-07-29 14:10:31 -0700761 void reply(InternalRequest message, InternalReply.Status status, Optional<byte[]> payload);
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700762
763 /**
764 * Closes the connection.
765 */
766 default void close() {
767 }
768 }
769
770 /**
Jordan Haltermanfe2f93d2017-12-08 23:52:54 -0800771 * Remote connection implementation.
772 */
773 private abstract class AbstractClientConnection implements ClientConnection {
774 private final Map<Long, Callback> futures = Maps.newConcurrentMap();
775 private final AtomicBoolean closed = new AtomicBoolean(false);
776 private final Cache<String, TimeoutHistory> timeoutHistories = CacheBuilder.newBuilder()
777 .expireAfterAccess(HISTORY_EXPIRE_MILLIS, TimeUnit.MILLISECONDS)
778 .build();
779
780 /**
781 * Times out callbacks for this connection.
782 */
783 protected void timeoutCallbacks() {
784 // Store the current time.
785 long currentTime = System.currentTimeMillis();
786
787 // Iterate through future callbacks and time out callbacks that have been alive
788 // longer than the current timeout according to the message type.
789 Iterator<Map.Entry<Long, Callback>> iterator = futures.entrySet().iterator();
790 while (iterator.hasNext()) {
791 Callback callback = iterator.next().getValue();
792 try {
793 TimeoutHistory timeoutHistory = timeoutHistories.get(callback.type, TimeoutHistory::new);
794 long currentTimeout = timeoutHistory.currentTimeout;
795 if (currentTime - callback.time > currentTimeout) {
796 iterator.remove();
797 long elapsedTime = currentTime - callback.time;
798 timeoutHistory.addReplyTime(elapsedTime);
799 callback.completeExceptionally(
800 new TimeoutException("Request timed out in " + elapsedTime + " milliseconds"));
801 }
802 } catch (ExecutionException e) {
803 throw new AssertionError();
804 }
805 }
806
807 // Iterate through all timeout histories and recompute the timeout.
808 for (TimeoutHistory timeoutHistory : timeoutHistories.asMap().values()) {
809 timeoutHistory.recomputeTimeoutMillis();
810 }
811 }
812
813 protected void registerCallback(long id, String subject, CompletableFuture<byte[]> future) {
814 futures.put(id, new Callback(subject, future));
815 }
816
817 protected Callback completeCallback(long id) {
818 Callback callback = futures.remove(id);
819 if (callback != null) {
820 try {
821 TimeoutHistory timeoutHistory = timeoutHistories.get(callback.type, TimeoutHistory::new);
822 timeoutHistory.addReplyTime(System.currentTimeMillis() - callback.time);
823 } catch (ExecutionException e) {
824 throw new AssertionError();
825 }
826 }
827 return callback;
828 }
829
830 protected Callback failCallback(long id) {
831 return futures.remove(id);
832 }
833
834 @Override
835 public void close() {
836 if (closed.compareAndSet(false, true)) {
Jordan Haltermanfe2f93d2017-12-08 23:52:54 -0800837 for (Callback callback : futures.values()) {
838 callback.completeExceptionally(new ConnectException());
839 }
840 }
841 }
842 }
843
844 /**
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700845 * Local connection implementation.
846 */
Jordan Haltermanfe2f93d2017-12-08 23:52:54 -0800847 private final class LocalClientConnection extends AbstractClientConnection {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700848 @Override
Jordan Haltermane3813a92017-07-29 14:10:31 -0700849 public CompletableFuture<Void> sendAsync(InternalRequest message) {
850 BiConsumer<InternalRequest, ServerConnection> handler = handlers.get(message.subject());
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700851 if (handler != null) {
852 handler.accept(message, localServerConnection);
853 } else {
854 log.debug("No handler for message type {} from {}", message.type(), message.sender());
855 }
856 return CompletableFuture.completedFuture(null);
857 }
858
859 @Override
Jordan Haltermane3813a92017-07-29 14:10:31 -0700860 public CompletableFuture<byte[]> sendAndReceive(InternalRequest message) {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700861 CompletableFuture<byte[]> future = new CompletableFuture<>();
Jordan Haltermanfe2f93d2017-12-08 23:52:54 -0800862 future.whenComplete((r, e) -> completeCallback(message.id()));
863 registerCallback(message.id(), message.subject(), future);
Jordan Haltermane3813a92017-07-29 14:10:31 -0700864 BiConsumer<InternalRequest, ServerConnection> handler = handlers.get(message.subject());
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700865 if (handler != null) {
866 handler.accept(message, new LocalServerConnection(future));
867 } else {
868 log.debug("No handler for message type {} from {}", message.type(), message.sender());
Jordan Haltermane3813a92017-07-29 14:10:31 -0700869 new LocalServerConnection(future)
870 .reply(message, InternalReply.Status.ERROR_NO_HANDLER, Optional.empty());
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700871 }
872 return future;
873 }
874 }
875
876 /**
877 * Local server connection.
878 */
879 private final class LocalServerConnection implements ServerConnection {
880 private final CompletableFuture<byte[]> future;
881
882 LocalServerConnection(CompletableFuture<byte[]> future) {
883 this.future = future;
884 }
885
886 @Override
Jordan Haltermane3813a92017-07-29 14:10:31 -0700887 public void reply(InternalRequest message, InternalReply.Status status, Optional<byte[]> payload) {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700888 if (future != null) {
Jordan Haltermane3813a92017-07-29 14:10:31 -0700889 if (status == InternalReply.Status.OK) {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700890 future.complete(payload.orElse(EMPTY_PAYLOAD));
Jordan Haltermane3813a92017-07-29 14:10:31 -0700891 } else if (status == InternalReply.Status.ERROR_NO_HANDLER) {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700892 future.completeExceptionally(new MessagingException.NoRemoteHandler());
Jordan Haltermane3813a92017-07-29 14:10:31 -0700893 } else if (status == InternalReply.Status.ERROR_HANDLER_EXCEPTION) {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700894 future.completeExceptionally(new MessagingException.RemoteHandlerFailure());
Jordan Haltermane3813a92017-07-29 14:10:31 -0700895 } else if (status == InternalReply.Status.PROTOCOL_EXCEPTION) {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700896 future.completeExceptionally(new MessagingException.ProtocolException());
897 }
898 }
899 }
900 }
901
902 /**
903 * Remote connection implementation.
904 */
Jordan Haltermanfe2f93d2017-12-08 23:52:54 -0800905 private final class RemoteClientConnection extends AbstractClientConnection {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700906 private final Channel channel;
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700907
908 RemoteClientConnection(Channel channel) {
909 this.channel = channel;
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800910 }
911
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700912 @Override
Jordan Haltermane3813a92017-07-29 14:10:31 -0700913 public CompletableFuture<Void> sendAsync(InternalRequest message) {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700914 CompletableFuture<Void> future = new CompletableFuture<>();
915 channel.writeAndFlush(message).addListener(channelFuture -> {
916 if (!channelFuture.isSuccess()) {
917 future.completeExceptionally(channelFuture.cause());
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800918 } else {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700919 future.complete(null);
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800920 }
921 });
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700922 return future;
923 }
924
925 @Override
Jordan Haltermane3813a92017-07-29 14:10:31 -0700926 public CompletableFuture<byte[]> sendAndReceive(InternalRequest message) {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700927 CompletableFuture<byte[]> future = new CompletableFuture<>();
Jordan Haltermanfe2f93d2017-12-08 23:52:54 -0800928 registerCallback(message.id(), message.subject(), future);
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700929 channel.writeAndFlush(message).addListener(channelFuture -> {
930 if (!channelFuture.isSuccess()) {
Jordan Haltermanfe2f93d2017-12-08 23:52:54 -0800931 Callback callback = failCallback(message.id());
932 if (callback != null) {
933 callback.completeExceptionally(channelFuture.cause());
934 }
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700935 }
936 });
937 return future;
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800938 }
939
940 /**
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700941 * Dispatches a message to a local handler.
942 *
943 * @param message the message to dispatch
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800944 */
Jordan Haltermane3813a92017-07-29 14:10:31 -0700945 private void dispatch(InternalReply message) {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700946 if (message.preamble() != preamble) {
Jordan Haltermane3813a92017-07-29 14:10:31 -0700947 log.debug("Received {} with invalid preamble", message.type());
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700948 return;
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800949 }
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700950
951 clockService.recordEventTime(message.time());
952
Jordan Haltermanfe2f93d2017-12-08 23:52:54 -0800953 Callback callback = completeCallback(message.id());
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700954 if (callback != null) {
Jordan Haltermane3813a92017-07-29 14:10:31 -0700955 if (message.status() == InternalReply.Status.OK) {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700956 callback.complete(message.payload());
Jordan Haltermane3813a92017-07-29 14:10:31 -0700957 } else if (message.status() == InternalReply.Status.ERROR_NO_HANDLER) {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700958 callback.completeExceptionally(new MessagingException.NoRemoteHandler());
Jordan Haltermane3813a92017-07-29 14:10:31 -0700959 } else if (message.status() == InternalReply.Status.ERROR_HANDLER_EXCEPTION) {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700960 callback.completeExceptionally(new MessagingException.RemoteHandlerFailure());
Jordan Haltermane3813a92017-07-29 14:10:31 -0700961 } else if (message.status() == InternalReply.Status.PROTOCOL_EXCEPTION) {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700962 callback.completeExceptionally(new MessagingException.ProtocolException());
963 }
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700964 } else {
Jordan Haltermane3813a92017-07-29 14:10:31 -0700965 log.debug("Received a reply for message id:[{}] "
966 + "but was unable to locate the"
967 + " request handle", message.id());
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700968 }
969 }
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700970 }
971
972 /**
973 * Remote server connection.
974 */
975 private final class RemoteServerConnection implements ServerConnection {
976 private final Channel channel;
977
978 RemoteServerConnection(Channel channel) {
979 this.channel = channel;
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800980 }
981
982 /**
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700983 * Dispatches a message to a local handler.
984 *
985 * @param message the message to dispatch
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800986 */
Jordan Haltermane3813a92017-07-29 14:10:31 -0700987 private void dispatch(InternalRequest message) {
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700988 if (message.preamble() != preamble) {
989 log.debug("Received {} with invalid preamble from {}", message.type(), message.sender());
Jordan Haltermane3813a92017-07-29 14:10:31 -0700990 reply(message, InternalReply.Status.PROTOCOL_EXCEPTION, Optional.empty());
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700991 return;
Aaron Kruglikov1b727382016-02-09 16:17:47 -0800992 }
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700993
994 clockService.recordEventTime(message.time());
995
Jordan Haltermane3813a92017-07-29 14:10:31 -0700996 BiConsumer<InternalRequest, ServerConnection> handler = handlers.get(message.subject());
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -0700997 if (handler != null) {
998 handler.accept(message, this);
999 } else {
1000 log.debug("No handler for message type {} from {}", message.type(), message.sender());
Jordan Haltermane3813a92017-07-29 14:10:31 -07001001 reply(message, InternalReply.Status.ERROR_NO_HANDLER, Optional.empty());
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -07001002 }
1003 }
1004
1005 @Override
Jordan Haltermane3813a92017-07-29 14:10:31 -07001006 public void reply(InternalRequest message, InternalReply.Status status, Optional<byte[]> payload) {
1007 InternalReply response = new InternalReply(preamble,
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -07001008 clockService.timeNow(),
1009 message.id(),
Jordan Haltermanf7c7f6f2017-05-05 03:02:34 -07001010 payload.orElse(EMPTY_PAYLOAD),
1011 status);
1012 channel.writeAndFlush(response);
1013 }
1014 }
1015
1016 /**
1017 * Request-reply timeout history tracker.
1018 */
1019 private static final class TimeoutHistory {
1020 private final DescriptiveStatistics timeoutHistory = new SynchronizedDescriptiveStatistics(WINDOW_SIZE);
1021 private final AtomicLong maxReplyTime = new AtomicLong();
1022 private volatile long currentTimeout = DEFAULT_TIMEOUT_MILLIS;
1023
1024 /**
1025 * Adds a reply time to the history.
1026 *
1027 * @param replyTime the reply time to add to the history
1028 */
1029 void addReplyTime(long replyTime) {
1030 maxReplyTime.getAndAccumulate(replyTime, Math::max);
1031 }
1032
1033 /**
1034 * Computes the current timeout.
1035 */
1036 private void recomputeTimeoutMillis() {
1037 double nextTimeout = maxReplyTime.getAndSet(0) * TIMEOUT_MULTIPLIER;
1038 timeoutHistory.addValue(
1039 Math.min(Math.max(nextTimeout, MIN_TIMEOUT_MILLIS), MAX_TIMEOUT_MILLIS));
1040 if (timeoutHistory.getN() == WINDOW_SIZE) {
1041 this.currentTimeout = (long) timeoutHistory.getMax();
1042 }
Aaron Kruglikov1b727382016-02-09 16:17:47 -08001043 }
1044 }
JunHuy Lam39eb4292015-06-26 17:24:23 +09001045}