Thomas Vachuska | 58de416 | 2015-09-10 16:15:33 -0700 | [diff] [blame] | 1 | /* |
Brian O'Connor | a09fe5b | 2017-08-03 21:12:30 -0700 | [diff] [blame] | 2 | * Copyright 2015-present Open Networking Foundation |
Thomas Vachuska | 58de416 | 2015-09-10 16:15:33 -0700 | [diff] [blame] | 3 | * |
| 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 Jampani | afeebbd | 2015-05-19 15:26:01 -0700 | [diff] [blame] | 16 | package org.onosproject.store.cluster.messaging.impl; |
| 17 | |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 18 | import javax.net.ssl.KeyManagerFactory; |
| 19 | import javax.net.ssl.SSLContext; |
| 20 | import javax.net.ssl.SSLEngine; |
| 21 | import javax.net.ssl.TrustManagerFactory; |
Brian O'Connor | 740e98c | 2017-06-29 17:07:17 -0700 | [diff] [blame] | 22 | import java.io.File; |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 23 | import java.io.FileInputStream; |
Brian O'Connor | 740e98c | 2017-06-29 17:07:17 -0700 | [diff] [blame] | 24 | import java.io.FileNotFoundException; |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 25 | import java.net.ConnectException; |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 26 | import java.security.KeyStore; |
Brian O'Connor | 740e98c | 2017-06-29 17:07:17 -0700 | [diff] [blame] | 27 | import java.security.MessageDigest; |
Brian O'Connor | f69e3e3 | 2018-05-10 02:25:09 -0700 | [diff] [blame] | 28 | import java.security.PublicKey; |
Brian O'Connor | 740e98c | 2017-06-29 17:07:17 -0700 | [diff] [blame] | 29 | import java.security.cert.Certificate; |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 30 | import java.time.Duration; |
Jordan Halterman | 66e6e3b | 2017-07-10 11:26:34 -0700 | [diff] [blame] | 31 | import java.util.ArrayList; |
Brian O'Connor | 740e98c | 2017-06-29 17:07:17 -0700 | [diff] [blame] | 32 | import java.util.Enumeration; |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 33 | import java.util.Iterator; |
Jordan Halterman | 66e6e3b | 2017-07-10 11:26:34 -0700 | [diff] [blame] | 34 | import java.util.List; |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 35 | import java.util.Map; |
Madan Jampani | a9e70a6 | 2016-03-02 16:28:18 -0800 | [diff] [blame] | 36 | import java.util.Optional; |
Brian O'Connor | 740e98c | 2017-06-29 17:07:17 -0700 | [diff] [blame] | 37 | import java.util.StringJoiner; |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 38 | import java.util.concurrent.CompletableFuture; |
| 39 | import java.util.concurrent.ConcurrentHashMap; |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 40 | import java.util.concurrent.ExecutionException; |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 41 | import java.util.concurrent.Executor; |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 42 | import java.util.concurrent.Executors; |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 43 | import java.util.concurrent.RejectedExecutionException; |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 44 | import java.util.concurrent.ScheduledExecutorService; |
| 45 | import java.util.concurrent.ScheduledFuture; |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 46 | import java.util.concurrent.TimeUnit; |
| 47 | import java.util.concurrent.TimeoutException; |
| 48 | import java.util.concurrent.atomic.AtomicBoolean; |
| 49 | import java.util.concurrent.atomic.AtomicLong; |
| 50 | import java.util.function.BiConsumer; |
| 51 | import java.util.function.BiFunction; |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 52 | import java.util.function.Function; |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 53 | |
Jordan Halterman | 23e73c5 | 2018-01-13 14:10:56 -0800 | [diff] [blame] | 54 | import com.google.common.base.Throwables; |
Jordan Halterman | 66e6e3b | 2017-07-10 11:26:34 -0700 | [diff] [blame] | 55 | import com.google.common.cache.Cache; |
| 56 | import com.google.common.cache.CacheBuilder; |
| 57 | import com.google.common.collect.Lists; |
| 58 | import com.google.common.collect.Maps; |
| 59 | import com.google.common.util.concurrent.MoreExecutors; |
| 60 | import io.netty.bootstrap.Bootstrap; |
| 61 | import io.netty.bootstrap.ServerBootstrap; |
| 62 | import io.netty.buffer.PooledByteBufAllocator; |
| 63 | import io.netty.channel.Channel; |
| 64 | import io.netty.channel.ChannelFuture; |
| 65 | import io.netty.channel.ChannelHandler; |
| 66 | import io.netty.channel.ChannelHandlerContext; |
| 67 | import io.netty.channel.ChannelInitializer; |
| 68 | import io.netty.channel.ChannelOption; |
| 69 | import io.netty.channel.EventLoopGroup; |
| 70 | import io.netty.channel.ServerChannel; |
| 71 | import io.netty.channel.SimpleChannelInboundHandler; |
| 72 | import io.netty.channel.WriteBufferWaterMark; |
| 73 | import io.netty.channel.epoll.EpollEventLoopGroup; |
| 74 | import io.netty.channel.epoll.EpollServerSocketChannel; |
| 75 | import io.netty.channel.epoll.EpollSocketChannel; |
| 76 | import io.netty.channel.nio.NioEventLoopGroup; |
| 77 | import io.netty.channel.socket.SocketChannel; |
| 78 | import io.netty.channel.socket.nio.NioServerSocketChannel; |
| 79 | import io.netty.channel.socket.nio.NioSocketChannel; |
| 80 | import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; |
| 81 | import org.apache.commons.math3.stat.descriptive.SynchronizedDescriptiveStatistics; |
| 82 | import org.apache.felix.scr.annotations.Activate; |
| 83 | import org.apache.felix.scr.annotations.Component; |
| 84 | import org.apache.felix.scr.annotations.Deactivate; |
| 85 | import org.apache.felix.scr.annotations.Reference; |
| 86 | import org.apache.felix.scr.annotations.ReferenceCardinality; |
| 87 | import org.apache.felix.scr.annotations.Service; |
| 88 | import org.onosproject.cluster.ClusterMetadataService; |
| 89 | import org.onosproject.cluster.ControllerNode; |
| 90 | import org.onosproject.core.HybridLogicalClockService; |
| 91 | import org.onosproject.store.cluster.messaging.Endpoint; |
| 92 | import org.onosproject.store.cluster.messaging.MessagingException; |
| 93 | import org.onosproject.store.cluster.messaging.MessagingService; |
Jordan Halterman | 66e6e3b | 2017-07-10 11:26:34 -0700 | [diff] [blame] | 94 | import org.slf4j.Logger; |
| 95 | import org.slf4j.LoggerFactory; |
| 96 | |
Yuta HIGUCHI | 90a1689 | 2016-07-20 20:36:08 -0700 | [diff] [blame] | 97 | import static org.onlab.util.Tools.groupedThreads; |
Heedo Kang | 4a47a30 | 2016-02-29 17:40:23 +0900 | [diff] [blame] | 98 | import static org.onosproject.security.AppGuard.checkPermission; |
| 99 | import static org.onosproject.security.AppPermission.Type.CLUSTER_WRITE; |
| 100 | |
Madan Jampani | afeebbd | 2015-05-19 15:26:01 -0700 | [diff] [blame] | 101 | /** |
| 102 | * Netty based MessagingService. |
| 103 | */ |
Sho SHIMIZU | 5c396e3 | 2016-08-12 15:19:12 -0700 | [diff] [blame] | 104 | @Component(immediate = true) |
Madan Jampani | afeebbd | 2015-05-19 15:26:01 -0700 | [diff] [blame] | 105 | @Service |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 106 | public class NettyMessagingManager implements MessagingService { |
Jordan Halterman | 66e6e3b | 2017-07-10 11:26:34 -0700 | [diff] [blame] | 107 | private static final long HISTORY_EXPIRE_MILLIS = Duration.ofMinutes(1).toMillis(); |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 108 | private static final long TIMEOUT_INTERVAL = 50; |
Jordan Halterman | 0529908 | 2018-05-14 14:45:20 -0700 | [diff] [blame^] | 109 | private static final int WINDOW_SIZE = 60; |
| 110 | private static final int WINDOW_UPDATE_SAMPLE_SIZE = 100; |
| 111 | private static final long WINDOW_UPDATE_MILLIS = 10000; |
Jordan Halterman | ef92f19 | 2017-12-21 11:59:38 -0800 | [diff] [blame] | 112 | private static final int MIN_SAMPLES = 25; |
Jordan Halterman | 0529908 | 2018-05-14 14:45:20 -0700 | [diff] [blame^] | 113 | private static final int MIN_STANDARD_DEVIATION = 100; |
| 114 | private static final int PHI_FAILURE_THRESHOLD = 12; |
Jordan Halterman | 111aab7 | 2018-01-12 16:28:57 -0800 | [diff] [blame] | 115 | private static final long MIN_TIMEOUT_MILLIS = 100; |
Jordan Halterman | 0529908 | 2018-05-14 14:45:20 -0700 | [diff] [blame^] | 116 | private static final long MAX_TIMEOUT_MILLIS = 5000; |
Jordan Halterman | 66e6e3b | 2017-07-10 11:26:34 -0700 | [diff] [blame] | 117 | private static final int CHANNEL_POOL_SIZE = 8; |
Madan Jampani | afeebbd | 2015-05-19 15:26:01 -0700 | [diff] [blame] | 118 | |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 119 | private static final byte[] EMPTY_PAYLOAD = new byte[0]; |
| 120 | |
Madan Jampani | afeebbd | 2015-05-19 15:26:01 -0700 | [diff] [blame] | 121 | private final Logger log = LoggerFactory.getLogger(getClass()); |
| 122 | |
Jordan Halterman | 1cf233c | 2017-12-08 23:52:54 -0800 | [diff] [blame] | 123 | private final LocalClientConnection localClientConnection = new LocalClientConnection(); |
| 124 | private final LocalServerConnection localServerConnection = new LocalServerConnection(null); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 125 | |
Brian O'Connor | 740e98c | 2017-06-29 17:07:17 -0700 | [diff] [blame] | 126 | //TODO CONFIG_DIR is duplicated from ConfigFileBasedClusterMetadataProvider |
| 127 | private static final String CONFIG_DIR = "../config"; |
| 128 | private static final String KS_FILE_NAME = "onos.jks"; |
| 129 | private static final File DEFAULT_KS_FILE = new File(CONFIG_DIR, KS_FILE_NAME); |
| 130 | private static final String DEFAULT_KS_PASSWORD = "changeit"; |
| 131 | |
Madan Jampani | 0583387 | 2016-07-12 23:01:39 -0700 | [diff] [blame] | 132 | @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) |
| 133 | protected HybridLogicalClockService clockService; |
| 134 | |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 135 | private Endpoint localEndpoint; |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 136 | private int preamble; |
| 137 | private final AtomicBoolean started = new AtomicBoolean(false); |
Jordan Halterman | e3813a9 | 2017-07-29 14:10:31 -0700 | [diff] [blame] | 138 | private final Map<String, BiConsumer<InternalRequest, ServerConnection>> handlers = new ConcurrentHashMap<>(); |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 139 | private final Map<Channel, RemoteClientConnection> clientConnections = Maps.newConcurrentMap(); |
| 140 | private final Map<Channel, RemoteServerConnection> serverConnections = Maps.newConcurrentMap(); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 141 | private final AtomicLong messageIdGenerator = new AtomicLong(0); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 142 | |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 143 | private ScheduledFuture<?> timeoutFuture; |
| 144 | |
Jordan Halterman | 66e6e3b | 2017-07-10 11:26:34 -0700 | [diff] [blame] | 145 | private final Map<Endpoint, List<CompletableFuture<Channel>>> channels = Maps.newConcurrentMap(); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 146 | |
| 147 | private EventLoopGroup serverGroup; |
| 148 | private EventLoopGroup clientGroup; |
| 149 | private Class<? extends ServerChannel> serverChannelClass; |
| 150 | private Class<? extends Channel> clientChannelClass; |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 151 | private ScheduledExecutorService timeoutExecutor; |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 152 | |
Brian O'Connor | 740e98c | 2017-06-29 17:07:17 -0700 | [diff] [blame] | 153 | protected static final boolean TLS_ENABLED = true; |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 154 | protected static final boolean TLS_DISABLED = false; |
Brian O'Connor | 740e98c | 2017-06-29 17:07:17 -0700 | [diff] [blame] | 155 | protected boolean enableNettyTls = TLS_ENABLED; |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 156 | |
Brian O'Connor | 740e98c | 2017-06-29 17:07:17 -0700 | [diff] [blame] | 157 | protected TrustManagerFactory trustManager; |
| 158 | protected KeyManagerFactory keyManager; |
JunHuy Lam | 39eb429 | 2015-06-26 17:24:23 +0900 | [diff] [blame] | 159 | |
Madan Jampani | afeebbd | 2015-05-19 15:26:01 -0700 | [diff] [blame] | 160 | @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) |
Madan Jampani | ec1df02 | 2015-10-13 21:23:03 -0700 | [diff] [blame] | 161 | protected ClusterMetadataService clusterMetadataService; |
Madan Jampani | afeebbd | 2015-05-19 15:26:01 -0700 | [diff] [blame] | 162 | |
| 163 | @Activate |
Ray Milkey | 986a47a | 2018-01-25 11:38:51 -0800 | [diff] [blame] | 164 | public void activate() throws InterruptedException { |
Madan Jampani | ec1df02 | 2015-10-13 21:23:03 -0700 | [diff] [blame] | 165 | ControllerNode localNode = clusterMetadataService.getLocalNode(); |
Jonathan Hart | d9df7bd | 2015-11-10 17:10:25 -0800 | [diff] [blame] | 166 | getTlsParameters(); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 167 | |
| 168 | if (started.get()) { |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 169 | log.warn("Already running at local endpoint: {}", localEndpoint); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 170 | return; |
| 171 | } |
| 172 | this.preamble = clusterMetadataService.getClusterMetadata().getName().hashCode(); |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 173 | this.localEndpoint = new Endpoint(localNode.ip(), localNode.tcpPort()); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 174 | initEventLoopGroup(); |
| 175 | startAcceptingConnections(); |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 176 | timeoutExecutor = Executors.newSingleThreadScheduledExecutor( |
| 177 | groupedThreads("NettyMessagingEvt", "timeout", log)); |
| 178 | timeoutFuture = timeoutExecutor.scheduleAtFixedRate( |
| 179 | this::timeoutAllCallbacks, TIMEOUT_INTERVAL, TIMEOUT_INTERVAL, TimeUnit.MILLISECONDS); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 180 | started.set(true); |
Madan Jampani | afeebbd | 2015-05-19 15:26:01 -0700 | [diff] [blame] | 181 | log.info("Started"); |
| 182 | } |
| 183 | |
| 184 | @Deactivate |
Ray Milkey | 986a47a | 2018-01-25 11:38:51 -0800 | [diff] [blame] | 185 | public void deactivate() { |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 186 | if (started.get()) { |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 187 | serverGroup.shutdownGracefully(); |
| 188 | clientGroup.shutdownGracefully(); |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 189 | timeoutFuture.cancel(false); |
| 190 | timeoutExecutor.shutdown(); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 191 | started.set(false); |
| 192 | } |
Madan Jampani | afeebbd | 2015-05-19 15:26:01 -0700 | [diff] [blame] | 193 | log.info("Stopped"); |
| 194 | } |
JunHuy Lam | 39eb429 | 2015-06-26 17:24:23 +0900 | [diff] [blame] | 195 | |
Jonathan Hart | d9df7bd | 2015-11-10 17:10:25 -0800 | [diff] [blame] | 196 | private void getTlsParameters() { |
Brian O'Connor | 740e98c | 2017-06-29 17:07:17 -0700 | [diff] [blame] | 197 | // default is TLS enabled unless key stores cannot be loaded |
| 198 | enableNettyTls = Boolean.parseBoolean(System.getProperty("enableNettyTLS", Boolean.toString(TLS_ENABLED))); |
| 199 | |
Jonathan Hart | d9df7bd | 2015-11-10 17:10:25 -0800 | [diff] [blame] | 200 | if (enableNettyTls) { |
Brian O'Connor | 740e98c | 2017-06-29 17:07:17 -0700 | [diff] [blame] | 201 | enableNettyTls = loadKeyStores(); |
| 202 | } |
| 203 | } |
| 204 | |
| 205 | private boolean loadKeyStores() { |
| 206 | // Maintain a local copy of the trust and key managers in case anything goes wrong |
| 207 | TrustManagerFactory tmf; |
| 208 | KeyManagerFactory kmf; |
| 209 | try { |
| 210 | String ksLocation = System.getProperty("javax.net.ssl.keyStore", DEFAULT_KS_FILE.toString()); |
| 211 | String tsLocation = System.getProperty("javax.net.ssl.trustStore", DEFAULT_KS_FILE.toString()); |
| 212 | char[] ksPwd = System.getProperty("javax.net.ssl.keyStorePassword", DEFAULT_KS_PASSWORD).toCharArray(); |
| 213 | char[] tsPwd = System.getProperty("javax.net.ssl.trustStorePassword", DEFAULT_KS_PASSWORD).toCharArray(); |
| 214 | |
| 215 | tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); |
| 216 | KeyStore ts = KeyStore.getInstance("JKS"); |
| 217 | ts.load(new FileInputStream(tsLocation), tsPwd); |
| 218 | tmf.init(ts); |
| 219 | |
| 220 | kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); |
| 221 | KeyStore ks = KeyStore.getInstance("JKS"); |
| 222 | ks.load(new FileInputStream(ksLocation), ksPwd); |
| 223 | kmf.init(ks, ksPwd); |
| 224 | if (log.isInfoEnabled()) { |
| 225 | logKeyStore(ks, ksLocation, ksPwd); |
JunHuy Lam | 39eb429 | 2015-06-26 17:24:23 +0900 | [diff] [blame] | 226 | } |
Brian O'Connor | 740e98c | 2017-06-29 17:07:17 -0700 | [diff] [blame] | 227 | } catch (FileNotFoundException e) { |
| 228 | log.warn("Disabling TLS for intra-cluster messaging; Could not load cluster key store: {}", e.getMessage()); |
| 229 | return TLS_DISABLED; |
| 230 | } catch (Exception e) { |
| 231 | //TODO we might want to catch exceptions more specifically |
| 232 | log.error("Error loading key store; disabling TLS for intra-cluster messaging", e); |
| 233 | return TLS_DISABLED; |
| 234 | } |
| 235 | this.trustManager = tmf; |
| 236 | this.keyManager = kmf; |
| 237 | return TLS_ENABLED; |
| 238 | } |
| 239 | |
| 240 | private void logKeyStore(KeyStore ks, String ksLocation, char[] ksPwd) { |
| 241 | if (log.isInfoEnabled()) { |
| 242 | log.info("Loaded cluster key store from: {}", ksLocation); |
| 243 | try { |
| 244 | for (Enumeration<String> e = ks.aliases(); e.hasMoreElements();) { |
| 245 | String alias = e.nextElement(); |
Brian O'Connor | f69e3e3 | 2018-05-10 02:25:09 -0700 | [diff] [blame] | 246 | Certificate cert = ks.getCertificate(alias); |
| 247 | if (cert == null) { |
| 248 | log.info("No certificate for alias {}", alias); |
| 249 | continue; |
Brian O'Connor | 740e98c | 2017-06-29 17:07:17 -0700 | [diff] [blame] | 250 | } |
Brian O'Connor | f69e3e3 | 2018-05-10 02:25:09 -0700 | [diff] [blame] | 251 | PublicKey key = cert.getPublicKey(); |
Brian O'Connor | 740e98c | 2017-06-29 17:07:17 -0700 | [diff] [blame] | 252 | // Compute the certificate's fingerprint (use the key if certificate cannot be found) |
| 253 | MessageDigest digest = MessageDigest.getInstance("SHA1"); |
Brian O'Connor | f69e3e3 | 2018-05-10 02:25:09 -0700 | [diff] [blame] | 254 | digest.update(key.getEncoded()); |
Brian O'Connor | 740e98c | 2017-06-29 17:07:17 -0700 | [diff] [blame] | 255 | StringJoiner fingerprint = new StringJoiner(":"); |
| 256 | for (byte b : digest.digest()) { |
| 257 | fingerprint.add(String.format("%02X", b)); |
| 258 | } |
| 259 | log.info("{} -> {}", alias, fingerprint); |
| 260 | } |
| 261 | } catch (Exception e) { |
| 262 | log.warn("Unable to print contents of key store: {}", ksLocation, e); |
JunHuy Lam | 39eb429 | 2015-06-26 17:24:23 +0900 | [diff] [blame] | 263 | } |
| 264 | } |
| 265 | } |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 266 | |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 267 | private void initEventLoopGroup() { |
| 268 | // try Epoll first and if that does work, use nio. |
| 269 | try { |
Yuta HIGUCHI | 90a1689 | 2016-07-20 20:36:08 -0700 | [diff] [blame] | 270 | clientGroup = new EpollEventLoopGroup(0, groupedThreads("NettyMessagingEvt", "epollC-%d", log)); |
| 271 | serverGroup = new EpollEventLoopGroup(0, groupedThreads("NettyMessagingEvt", "epollS-%d", log)); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 272 | serverChannelClass = EpollServerSocketChannel.class; |
| 273 | clientChannelClass = EpollSocketChannel.class; |
| 274 | return; |
| 275 | } catch (Throwable e) { |
| 276 | log.debug("Failed to initialize native (epoll) transport. " |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 277 | + "Reason: {}. Proceeding with nio.", e.getMessage()); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 278 | } |
Yuta HIGUCHI | 90a1689 | 2016-07-20 20:36:08 -0700 | [diff] [blame] | 279 | clientGroup = new NioEventLoopGroup(0, groupedThreads("NettyMessagingEvt", "nioC-%d", log)); |
| 280 | serverGroup = new NioEventLoopGroup(0, groupedThreads("NettyMessagingEvt", "nioS-%d", log)); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 281 | serverChannelClass = NioServerSocketChannel.class; |
| 282 | clientChannelClass = NioSocketChannel.class; |
| 283 | } |
| 284 | |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 285 | /** |
| 286 | * Times out response callbacks. |
| 287 | */ |
| 288 | private void timeoutAllCallbacks() { |
| 289 | // Iterate through all connections and time out callbacks. |
Jordan Halterman | 1cf233c | 2017-12-08 23:52:54 -0800 | [diff] [blame] | 290 | localClientConnection.timeoutCallbacks(); |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 291 | for (RemoteClientConnection connection : clientConnections.values()) { |
| 292 | connection.timeoutCallbacks(); |
| 293 | } |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 294 | } |
| 295 | |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 296 | @Override |
| 297 | public CompletableFuture<Void> sendAsync(Endpoint ep, String type, byte[] payload) { |
Heedo Kang | 4a47a30 | 2016-02-29 17:40:23 +0900 | [diff] [blame] | 298 | checkPermission(CLUSTER_WRITE); |
Jordan Halterman | e3813a9 | 2017-07-29 14:10:31 -0700 | [diff] [blame] | 299 | InternalRequest message = new InternalRequest(preamble, |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 300 | clockService.timeNow(), |
| 301 | messageIdGenerator.incrementAndGet(), |
| 302 | localEndpoint, |
| 303 | type, |
| 304 | payload); |
Jordan Halterman | 66e6e3b | 2017-07-10 11:26:34 -0700 | [diff] [blame] | 305 | return executeOnPooledConnection(ep, type, c -> c.sendAsync(message), MoreExecutors.directExecutor()); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 306 | } |
| 307 | |
| 308 | @Override |
| 309 | public CompletableFuture<byte[]> sendAndReceive(Endpoint ep, String type, byte[] payload) { |
Heedo Kang | 4a47a30 | 2016-02-29 17:40:23 +0900 | [diff] [blame] | 310 | checkPermission(CLUSTER_WRITE); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 311 | return sendAndReceive(ep, type, payload, MoreExecutors.directExecutor()); |
| 312 | } |
| 313 | |
| 314 | @Override |
| 315 | public CompletableFuture<byte[]> sendAndReceive(Endpoint ep, String type, byte[] payload, Executor executor) { |
Heedo Kang | 4a47a30 | 2016-02-29 17:40:23 +0900 | [diff] [blame] | 316 | checkPermission(CLUSTER_WRITE); |
Jordan Halterman | 5ceb389 | 2017-08-28 15:35:03 -0700 | [diff] [blame] | 317 | long messageId = messageIdGenerator.incrementAndGet(); |
Jordan Halterman | e3813a9 | 2017-07-29 14:10:31 -0700 | [diff] [blame] | 318 | InternalRequest message = new InternalRequest(preamble, |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 319 | clockService.timeNow(), |
| 320 | messageId, |
| 321 | localEndpoint, |
| 322 | type, |
| 323 | payload); |
Jordan Halterman | 66e6e3b | 2017-07-10 11:26:34 -0700 | [diff] [blame] | 324 | return executeOnPooledConnection(ep, type, c -> c.sendAndReceive(message), executor); |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 325 | } |
Jordan Halterman | 041534b | 2017-03-21 10:37:33 -0700 | [diff] [blame] | 326 | |
Jordan Halterman | 66e6e3b | 2017-07-10 11:26:34 -0700 | [diff] [blame] | 327 | private List<CompletableFuture<Channel>> getChannelPool(Endpoint endpoint) { |
| 328 | return channels.computeIfAbsent(endpoint, e -> { |
| 329 | List<CompletableFuture<Channel>> defaultList = new ArrayList<>(CHANNEL_POOL_SIZE); |
| 330 | for (int i = 0; i < CHANNEL_POOL_SIZE; i++) { |
| 331 | defaultList.add(null); |
| 332 | } |
| 333 | return Lists.newCopyOnWriteArrayList(defaultList); |
| 334 | }); |
| 335 | } |
| 336 | |
| 337 | private int getChannelOffset(String messageType) { |
| 338 | return Math.abs(messageType.hashCode() % CHANNEL_POOL_SIZE); |
| 339 | } |
| 340 | |
Jordan Halterman | 94db191 | 2018-02-08 14:45:20 -0800 | [diff] [blame] | 341 | private CompletableFuture<Channel> getChannel(Endpoint endpoint, String messageType) { |
Jordan Halterman | 23e73c5 | 2018-01-13 14:10:56 -0800 | [diff] [blame] | 342 | List<CompletableFuture<Channel>> channelPool = getChannelPool(endpoint); |
Jordan Halterman | 94db191 | 2018-02-08 14:45:20 -0800 | [diff] [blame] | 343 | int offset = getChannelOffset(messageType); |
Jordan Halterman | 23e73c5 | 2018-01-13 14:10:56 -0800 | [diff] [blame] | 344 | |
Jordan Halterman | 23e73c5 | 2018-01-13 14:10:56 -0800 | [diff] [blame] | 345 | CompletableFuture<Channel> channelFuture = channelPool.get(offset); |
| 346 | if (channelFuture == null || channelFuture.isCompletedExceptionally()) { |
| 347 | synchronized (channelPool) { |
| 348 | channelFuture = channelPool.get(offset); |
| 349 | if (channelFuture == null || channelFuture.isCompletedExceptionally()) { |
| 350 | channelFuture = openChannel(endpoint); |
| 351 | channelPool.set(offset, channelFuture); |
| 352 | } |
| 353 | } |
| 354 | } |
| 355 | |
Jordan Halterman | 94db191 | 2018-02-08 14:45:20 -0800 | [diff] [blame] | 356 | CompletableFuture<Channel> future = new CompletableFuture<>(); |
Jordan Halterman | 23e73c5 | 2018-01-13 14:10:56 -0800 | [diff] [blame] | 357 | final CompletableFuture<Channel> finalFuture = channelFuture; |
| 358 | finalFuture.whenComplete((channel, error) -> { |
| 359 | if (error == null) { |
| 360 | if (!channel.isActive()) { |
Jordan Halterman | 94db191 | 2018-02-08 14:45:20 -0800 | [diff] [blame] | 361 | CompletableFuture<Channel> currentFuture; |
Jordan Halterman | 23e73c5 | 2018-01-13 14:10:56 -0800 | [diff] [blame] | 362 | synchronized (channelPool) { |
| 363 | currentFuture = channelPool.get(offset); |
| 364 | if (currentFuture == finalFuture) { |
| 365 | channelPool.set(offset, null); |
| 366 | } |
| 367 | } |
Jordan Halterman | 94db191 | 2018-02-08 14:45:20 -0800 | [diff] [blame] | 368 | |
| 369 | ClientConnection connection = clientConnections.remove(channel); |
| 370 | if (connection != null) { |
| 371 | connection.close(); |
| 372 | } |
| 373 | |
Jordan Halterman | 23e73c5 | 2018-01-13 14:10:56 -0800 | [diff] [blame] | 374 | if (currentFuture == finalFuture) { |
Jordan Halterman | 94db191 | 2018-02-08 14:45:20 -0800 | [diff] [blame] | 375 | getChannel(endpoint, messageType).whenComplete((recursiveResult, recursiveError) -> { |
| 376 | if (recursiveError == null) { |
| 377 | future.complete(recursiveResult); |
| 378 | } else { |
| 379 | future.completeExceptionally(recursiveError); |
| 380 | } |
| 381 | }); |
Jordan Halterman | 23e73c5 | 2018-01-13 14:10:56 -0800 | [diff] [blame] | 382 | } else { |
| 383 | currentFuture.whenComplete((recursiveResult, recursiveError) -> { |
| 384 | if (recursiveError == null) { |
Jordan Halterman | 94db191 | 2018-02-08 14:45:20 -0800 | [diff] [blame] | 385 | future.complete(recursiveResult); |
Jordan Halterman | 23e73c5 | 2018-01-13 14:10:56 -0800 | [diff] [blame] | 386 | } else { |
| 387 | future.completeExceptionally(recursiveError); |
| 388 | } |
| 389 | }); |
| 390 | } |
| 391 | } else { |
Jordan Halterman | 94db191 | 2018-02-08 14:45:20 -0800 | [diff] [blame] | 392 | future.complete(channel); |
Jordan Halterman | 23e73c5 | 2018-01-13 14:10:56 -0800 | [diff] [blame] | 393 | } |
Ray Milkey | 4f35076 | 2018-01-23 23:32:03 +0000 | [diff] [blame] | 394 | } else { |
Jordan Halterman | 23e73c5 | 2018-01-13 14:10:56 -0800 | [diff] [blame] | 395 | future.completeExceptionally(error); |
Ray Milkey | 4f35076 | 2018-01-23 23:32:03 +0000 | [diff] [blame] | 396 | } |
| 397 | }); |
Jordan Halterman | 94db191 | 2018-02-08 14:45:20 -0800 | [diff] [blame] | 398 | return future; |
| 399 | } |
| 400 | |
| 401 | private <T> CompletableFuture<T> executeOnPooledConnection( |
| 402 | Endpoint endpoint, |
| 403 | String type, |
| 404 | Function<ClientConnection, CompletableFuture<T>> callback, |
| 405 | Executor executor) { |
| 406 | CompletableFuture<T> future = new CompletableFuture<T>(); |
| 407 | executeOnPooledConnection(endpoint, type, callback, executor, future); |
| 408 | return future; |
| 409 | } |
| 410 | |
| 411 | private <T> void executeOnPooledConnection( |
| 412 | Endpoint endpoint, |
| 413 | String type, |
| 414 | Function<ClientConnection, CompletableFuture<T>> callback, |
| 415 | Executor executor, |
| 416 | CompletableFuture<T> future) { |
| 417 | if (endpoint.equals(localEndpoint)) { |
| 418 | callback.apply(localClientConnection).whenComplete((result, error) -> { |
| 419 | if (error == null) { |
| 420 | executor.execute(() -> future.complete(result)); |
| 421 | } else { |
| 422 | executor.execute(() -> future.completeExceptionally(error)); |
| 423 | } |
| 424 | }); |
| 425 | return; |
| 426 | } |
| 427 | |
| 428 | getChannel(endpoint, type).whenComplete((channel, channelError) -> { |
| 429 | if (channelError == null) { |
| 430 | ClientConnection connection = clientConnections.computeIfAbsent(channel, RemoteClientConnection::new); |
| 431 | callback.apply(connection).whenComplete((result, sendError) -> { |
| 432 | if (sendError == null) { |
| 433 | executor.execute(() -> future.complete(result)); |
| 434 | } else { |
| 435 | Throwable cause = Throwables.getRootCause(sendError); |
| 436 | if (!(cause instanceof TimeoutException) && !(cause instanceof MessagingException)) { |
| 437 | channel.close().addListener(f -> { |
| 438 | connection.close(); |
| 439 | clientConnections.remove(channel); |
| 440 | }); |
| 441 | } |
| 442 | executor.execute(() -> future.completeExceptionally(sendError)); |
| 443 | } |
| 444 | }); |
| 445 | } else { |
| 446 | executor.execute(() -> future.completeExceptionally(channelError)); |
| 447 | } |
| 448 | }); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 449 | } |
| 450 | |
| 451 | @Override |
| 452 | public void registerHandler(String type, BiConsumer<Endpoint, byte[]> handler, Executor executor) { |
Heedo Kang | 4a47a30 | 2016-02-29 17:40:23 +0900 | [diff] [blame] | 453 | checkPermission(CLUSTER_WRITE); |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 454 | handlers.put(type, (message, connection) -> executor.execute(() -> |
| 455 | handler.accept(message.sender(), message.payload()))); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 456 | } |
| 457 | |
| 458 | @Override |
| 459 | public void registerHandler(String type, BiFunction<Endpoint, byte[], byte[]> handler, Executor executor) { |
Heedo Kang | 4a47a30 | 2016-02-29 17:40:23 +0900 | [diff] [blame] | 460 | checkPermission(CLUSTER_WRITE); |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 461 | handlers.put(type, (message, connection) -> executor.execute(() -> { |
Madan Jampani | a9e70a6 | 2016-03-02 16:28:18 -0800 | [diff] [blame] | 462 | byte[] responsePayload = null; |
Jordan Halterman | e3813a9 | 2017-07-29 14:10:31 -0700 | [diff] [blame] | 463 | InternalReply.Status status = InternalReply.Status.OK; |
Madan Jampani | a9e70a6 | 2016-03-02 16:28:18 -0800 | [diff] [blame] | 464 | try { |
| 465 | responsePayload = handler.apply(message.sender(), message.payload()); |
| 466 | } catch (Exception e) { |
Jordan Halterman | b6ee9e9 | 2017-06-21 15:26:28 -0700 | [diff] [blame] | 467 | log.debug("An error occurred in a message handler: {}", e); |
Jordan Halterman | e3813a9 | 2017-07-29 14:10:31 -0700 | [diff] [blame] | 468 | status = InternalReply.Status.ERROR_HANDLER_EXCEPTION; |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 469 | } |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 470 | connection.reply(message, status, Optional.ofNullable(responsePayload)); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 471 | })); |
| 472 | } |
| 473 | |
| 474 | @Override |
| 475 | public void registerHandler(String type, BiFunction<Endpoint, byte[], CompletableFuture<byte[]>> handler) { |
Heedo Kang | 4a47a30 | 2016-02-29 17:40:23 +0900 | [diff] [blame] | 476 | checkPermission(CLUSTER_WRITE); |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 477 | handlers.put(type, (message, connection) -> { |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 478 | handler.apply(message.sender(), message.payload()).whenComplete((result, error) -> { |
Jordan Halterman | e3813a9 | 2017-07-29 14:10:31 -0700 | [diff] [blame] | 479 | InternalReply.Status status; |
Jordan Halterman | b6ee9e9 | 2017-06-21 15:26:28 -0700 | [diff] [blame] | 480 | if (error == null) { |
Jordan Halterman | e3813a9 | 2017-07-29 14:10:31 -0700 | [diff] [blame] | 481 | status = InternalReply.Status.OK; |
Jordan Halterman | b6ee9e9 | 2017-06-21 15:26:28 -0700 | [diff] [blame] | 482 | } else { |
| 483 | log.debug("An error occurred in a message handler: {}", error); |
Jordan Halterman | e3813a9 | 2017-07-29 14:10:31 -0700 | [diff] [blame] | 484 | status = InternalReply.Status.ERROR_HANDLER_EXCEPTION; |
Jordan Halterman | b6ee9e9 | 2017-06-21 15:26:28 -0700 | [diff] [blame] | 485 | } |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 486 | connection.reply(message, status, Optional.ofNullable(result)); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 487 | }); |
| 488 | }); |
| 489 | } |
| 490 | |
| 491 | @Override |
| 492 | public void unregisterHandler(String type) { |
Heedo Kang | 4a47a30 | 2016-02-29 17:40:23 +0900 | [diff] [blame] | 493 | checkPermission(CLUSTER_WRITE); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 494 | handlers.remove(type); |
| 495 | } |
| 496 | |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 497 | private Bootstrap bootstrapClient(Endpoint endpoint) { |
| 498 | Bootstrap bootstrap = new Bootstrap(); |
| 499 | bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); |
| 500 | bootstrap.option(ChannelOption.WRITE_BUFFER_WATER_MARK, |
| 501 | new WriteBufferWaterMark(10 * 32 * 1024, 10 * 64 * 1024)); |
| 502 | bootstrap.option(ChannelOption.SO_SNDBUF, 1048576); |
| 503 | bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000); |
| 504 | bootstrap.group(clientGroup); |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 505 | bootstrap.channel(clientChannelClass); |
| 506 | bootstrap.option(ChannelOption.SO_KEEPALIVE, true); |
| 507 | bootstrap.remoteAddress(endpoint.host().toInetAddress(), endpoint.port()); |
Jordan Halterman | 66e6e3b | 2017-07-10 11:26:34 -0700 | [diff] [blame] | 508 | if (enableNettyTls) { |
| 509 | bootstrap.handler(new SslClientCommunicationChannelInitializer()); |
| 510 | } else { |
| 511 | bootstrap.handler(new BasicChannelInitializer()); |
| 512 | } |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 513 | return bootstrap; |
| 514 | } |
| 515 | |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 516 | private void startAcceptingConnections() throws InterruptedException { |
| 517 | ServerBootstrap b = new ServerBootstrap(); |
Jon Hall | 9a44d6a | 2017-03-02 18:14:37 -0800 | [diff] [blame] | 518 | b.childOption(ChannelOption.WRITE_BUFFER_WATER_MARK, |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 519 | new WriteBufferWaterMark(8 * 1024, 32 * 1024)); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 520 | b.option(ChannelOption.SO_RCVBUF, 1048576); |
Jordan Halterman | 153dbd5 | 2017-12-21 11:08:19 -0800 | [diff] [blame] | 521 | b.childOption(ChannelOption.SO_KEEPALIVE, true); |
| 522 | b.childOption(ChannelOption.TCP_NODELAY, true); |
Yuta HIGUCHI | b47c953 | 2016-08-22 09:41:23 -0700 | [diff] [blame] | 523 | b.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 524 | b.group(serverGroup, clientGroup); |
| 525 | b.channel(serverChannelClass); |
| 526 | if (enableNettyTls) { |
| 527 | b.childHandler(new SslServerCommunicationChannelInitializer()); |
| 528 | } else { |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 529 | b.childHandler(new BasicChannelInitializer()); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 530 | } |
| 531 | b.option(ChannelOption.SO_BACKLOG, 128); |
| 532 | b.childOption(ChannelOption.SO_KEEPALIVE, true); |
| 533 | |
| 534 | // Bind and start to accept incoming connections. |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 535 | b.bind(localEndpoint.port()).sync().addListener(future -> { |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 536 | if (future.isSuccess()) { |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 537 | log.info("{} accepting incoming connections on port {}", |
| 538 | localEndpoint.host(), localEndpoint.port()); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 539 | } else { |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 540 | log.warn("{} failed to bind to port {} due to {}", |
| 541 | localEndpoint.host(), localEndpoint.port(), future.cause()); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 542 | } |
| 543 | }); |
| 544 | } |
| 545 | |
Jordan Halterman | 66e6e3b | 2017-07-10 11:26:34 -0700 | [diff] [blame] | 546 | private CompletableFuture<Channel> openChannel(Endpoint ep) { |
| 547 | Bootstrap bootstrap = bootstrapClient(ep); |
| 548 | CompletableFuture<Channel> retFuture = new CompletableFuture<>(); |
| 549 | ChannelFuture f = bootstrap.connect(); |
| 550 | |
| 551 | f.addListener(future -> { |
| 552 | if (future.isSuccess()) { |
| 553 | retFuture.complete(f.channel()); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 554 | } else { |
Jordan Halterman | 66e6e3b | 2017-07-10 11:26:34 -0700 | [diff] [blame] | 555 | retFuture.completeExceptionally(future.cause()); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 556 | } |
Jordan Halterman | 66e6e3b | 2017-07-10 11:26:34 -0700 | [diff] [blame] | 557 | }); |
| 558 | log.debug("Established a new connection to {}", ep); |
| 559 | return retFuture; |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 560 | } |
| 561 | |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 562 | /** |
| 563 | * Channel initializer for TLS servers. |
| 564 | */ |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 565 | private class SslServerCommunicationChannelInitializer extends ChannelInitializer<SocketChannel> { |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 566 | private final ChannelHandler dispatcher = new InboundMessageDispatcher(); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 567 | |
| 568 | @Override |
| 569 | protected void initChannel(SocketChannel channel) throws Exception { |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 570 | SSLContext serverContext = SSLContext.getInstance("TLS"); |
Brian O'Connor | 740e98c | 2017-06-29 17:07:17 -0700 | [diff] [blame] | 571 | serverContext.init(keyManager.getKeyManagers(), trustManager.getTrustManagers(), null); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 572 | |
| 573 | SSLEngine serverSslEngine = serverContext.createSSLEngine(); |
| 574 | |
| 575 | serverSslEngine.setNeedClientAuth(true); |
| 576 | serverSslEngine.setUseClientMode(false); |
| 577 | serverSslEngine.setEnabledProtocols(serverSslEngine.getSupportedProtocols()); |
| 578 | serverSslEngine.setEnabledCipherSuites(serverSslEngine.getSupportedCipherSuites()); |
| 579 | serverSslEngine.setEnableSessionCreation(true); |
| 580 | |
| 581 | channel.pipeline().addLast("ssl", new io.netty.handler.ssl.SslHandler(serverSslEngine)) |
Jordan Halterman | e3813a9 | 2017-07-29 14:10:31 -0700 | [diff] [blame] | 582 | .addLast("encoder", new MessageEncoder(localEndpoint, preamble)) |
Madan Jampani | b825aeb | 2016-04-01 15:18:25 -0700 | [diff] [blame] | 583 | .addLast("decoder", new MessageDecoder()) |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 584 | .addLast("handler", dispatcher); |
| 585 | } |
| 586 | } |
| 587 | |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 588 | /** |
| 589 | * Channel initializer for TLS clients. |
| 590 | */ |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 591 | private class SslClientCommunicationChannelInitializer extends ChannelInitializer<SocketChannel> { |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 592 | private final ChannelHandler dispatcher = new InboundMessageDispatcher(); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 593 | |
| 594 | @Override |
| 595 | protected void initChannel(SocketChannel channel) throws Exception { |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 596 | SSLContext clientContext = SSLContext.getInstance("TLS"); |
Brian O'Connor | 740e98c | 2017-06-29 17:07:17 -0700 | [diff] [blame] | 597 | clientContext.init(keyManager.getKeyManagers(), trustManager.getTrustManagers(), null); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 598 | |
| 599 | SSLEngine clientSslEngine = clientContext.createSSLEngine(); |
| 600 | |
| 601 | clientSslEngine.setUseClientMode(true); |
| 602 | clientSslEngine.setEnabledProtocols(clientSslEngine.getSupportedProtocols()); |
| 603 | clientSslEngine.setEnabledCipherSuites(clientSslEngine.getSupportedCipherSuites()); |
| 604 | clientSslEngine.setEnableSessionCreation(true); |
| 605 | |
| 606 | channel.pipeline().addLast("ssl", new io.netty.handler.ssl.SslHandler(clientSslEngine)) |
Jordan Halterman | e3813a9 | 2017-07-29 14:10:31 -0700 | [diff] [blame] | 607 | .addLast("encoder", new MessageEncoder(localEndpoint, preamble)) |
Madan Jampani | b825aeb | 2016-04-01 15:18:25 -0700 | [diff] [blame] | 608 | .addLast("decoder", new MessageDecoder()) |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 609 | .addLast("handler", dispatcher); |
| 610 | } |
| 611 | } |
| 612 | |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 613 | /** |
| 614 | * Channel initializer for basic connections. |
| 615 | */ |
| 616 | private class BasicChannelInitializer extends ChannelInitializer<SocketChannel> { |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 617 | private final ChannelHandler dispatcher = new InboundMessageDispatcher(); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 618 | |
| 619 | @Override |
| 620 | protected void initChannel(SocketChannel channel) throws Exception { |
| 621 | channel.pipeline() |
Jordan Halterman | e3813a9 | 2017-07-29 14:10:31 -0700 | [diff] [blame] | 622 | .addLast("encoder", new MessageEncoder(localEndpoint, preamble)) |
Madan Jampani | b825aeb | 2016-04-01 15:18:25 -0700 | [diff] [blame] | 623 | .addLast("decoder", new MessageDecoder()) |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 624 | .addLast("handler", dispatcher); |
| 625 | } |
| 626 | } |
| 627 | |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 628 | /** |
| 629 | * Channel inbound handler that dispatches messages to the appropriate handler. |
| 630 | */ |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 631 | @ChannelHandler.Sharable |
Yuta HIGUCHI | c012dda | 2016-08-17 00:43:46 -0700 | [diff] [blame] | 632 | private class InboundMessageDispatcher extends SimpleChannelInboundHandler<Object> { |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 633 | // Effectively SimpleChannelInboundHandler<InternalMessage>, |
| 634 | // had to specify <Object> to avoid Class Loader not being able to find some classes. |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 635 | |
| 636 | @Override |
Yuta HIGUCHI | c012dda | 2016-08-17 00:43:46 -0700 | [diff] [blame] | 637 | protected void channelRead0(ChannelHandlerContext ctx, Object rawMessage) throws Exception { |
| 638 | InternalMessage message = (InternalMessage) rawMessage; |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 639 | try { |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 640 | if (message.isRequest()) { |
| 641 | RemoteServerConnection connection = |
| 642 | serverConnections.computeIfAbsent(ctx.channel(), RemoteServerConnection::new); |
Jordan Halterman | e3813a9 | 2017-07-29 14:10:31 -0700 | [diff] [blame] | 643 | connection.dispatch((InternalRequest) message); |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 644 | } else { |
| 645 | RemoteClientConnection connection = |
| 646 | clientConnections.computeIfAbsent(ctx.channel(), RemoteClientConnection::new); |
Jordan Halterman | e3813a9 | 2017-07-29 14:10:31 -0700 | [diff] [blame] | 647 | connection.dispatch((InternalReply) message); |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 648 | } |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 649 | } catch (RejectedExecutionException e) { |
| 650 | log.warn("Unable to dispatch message due to {}", e.getMessage()); |
| 651 | } |
| 652 | } |
| 653 | |
| 654 | @Override |
| 655 | public void exceptionCaught(ChannelHandlerContext context, Throwable cause) { |
| 656 | log.error("Exception inside channel handling pipeline.", cause); |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 657 | |
| 658 | RemoteClientConnection clientConnection = clientConnections.remove(context.channel()); |
| 659 | if (clientConnection != null) { |
| 660 | clientConnection.close(); |
| 661 | } |
| 662 | |
| 663 | RemoteServerConnection serverConnection = serverConnections.remove(context.channel()); |
| 664 | if (serverConnection != null) { |
| 665 | serverConnection.close(); |
| 666 | } |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 667 | context.close(); |
| 668 | } |
Yuta HIGUCHI | c012dda | 2016-08-17 00:43:46 -0700 | [diff] [blame] | 669 | |
Jordan Halterman | 23e73c5 | 2018-01-13 14:10:56 -0800 | [diff] [blame] | 670 | @Override |
| 671 | public void channelInactive(ChannelHandlerContext context) throws Exception { |
| 672 | RemoteClientConnection clientConnection = clientConnections.remove(context.channel()); |
| 673 | if (clientConnection != null) { |
| 674 | clientConnection.close(); |
| 675 | } |
| 676 | |
| 677 | RemoteServerConnection serverConnection = serverConnections.remove(context.channel()); |
| 678 | if (serverConnection != null) { |
| 679 | serverConnection.close(); |
| 680 | } |
| 681 | context.close(); |
| 682 | } |
| 683 | |
Yuta HIGUCHI | c012dda | 2016-08-17 00:43:46 -0700 | [diff] [blame] | 684 | /** |
| 685 | * Returns true if the given message should be handled. |
| 686 | * |
| 687 | * @param msg inbound message |
| 688 | * @return true if {@code msg} is {@link InternalMessage} instance. |
Yuta HIGUCHI | c012dda | 2016-08-17 00:43:46 -0700 | [diff] [blame] | 689 | * @see SimpleChannelInboundHandler#acceptInboundMessage(Object) |
| 690 | */ |
| 691 | @Override |
| 692 | public final boolean acceptInboundMessage(Object msg) { |
| 693 | return msg instanceof InternalMessage; |
| 694 | } |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 695 | } |
Yuta HIGUCHI | c012dda | 2016-08-17 00:43:46 -0700 | [diff] [blame] | 696 | |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 697 | /** |
| 698 | * Wraps a {@link CompletableFuture} and tracks its type and creation time. |
| 699 | */ |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 700 | private final class Callback { |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 701 | private final String type; |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 702 | private final CompletableFuture<byte[]> future; |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 703 | private final long time = System.currentTimeMillis(); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 704 | |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 705 | Callback(String type, CompletableFuture<byte[]> future) { |
| 706 | this.type = type; |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 707 | this.future = future; |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 708 | } |
| 709 | |
| 710 | public void complete(byte[] value) { |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 711 | future.complete(value); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 712 | } |
| 713 | |
| 714 | public void completeExceptionally(Throwable error) { |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 715 | future.completeExceptionally(error); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 716 | } |
| 717 | } |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 718 | |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 719 | /** |
| 720 | * Represents the client side of a connection to a local or remote server. |
| 721 | */ |
| 722 | private interface ClientConnection { |
| 723 | |
| 724 | /** |
| 725 | * Sends a message to the other side of the connection. |
| 726 | * |
| 727 | * @param message the message to send |
| 728 | * @return a completable future to be completed once the message has been sent |
| 729 | */ |
Jordan Halterman | e3813a9 | 2017-07-29 14:10:31 -0700 | [diff] [blame] | 730 | CompletableFuture<Void> sendAsync(InternalRequest message); |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 731 | |
| 732 | /** |
| 733 | * Sends a message to the other side of the connection, awaiting a reply. |
| 734 | * |
| 735 | * @param message the message to send |
| 736 | * @return a completable future to be completed once a reply is received or the request times out |
| 737 | */ |
Jordan Halterman | e3813a9 | 2017-07-29 14:10:31 -0700 | [diff] [blame] | 738 | CompletableFuture<byte[]> sendAndReceive(InternalRequest message); |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 739 | |
| 740 | /** |
| 741 | * Closes the connection. |
| 742 | */ |
| 743 | default void close() { |
| 744 | } |
| 745 | } |
| 746 | |
| 747 | /** |
| 748 | * Represents the server side of a connection. |
| 749 | */ |
| 750 | private interface ServerConnection { |
| 751 | |
| 752 | /** |
| 753 | * Sends a reply to the other side of the connection. |
| 754 | * |
| 755 | * @param message the message to which to reply |
Jordan Halterman | 1cf233c | 2017-12-08 23:52:54 -0800 | [diff] [blame] | 756 | * @param status the reply status |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 757 | * @param payload the response payload |
| 758 | */ |
Jordan Halterman | e3813a9 | 2017-07-29 14:10:31 -0700 | [diff] [blame] | 759 | void reply(InternalRequest message, InternalReply.Status status, Optional<byte[]> payload); |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 760 | |
| 761 | /** |
| 762 | * Closes the connection. |
| 763 | */ |
| 764 | default void close() { |
| 765 | } |
| 766 | } |
| 767 | |
| 768 | /** |
Jordan Halterman | 1cf233c | 2017-12-08 23:52:54 -0800 | [diff] [blame] | 769 | * Remote connection implementation. |
| 770 | */ |
| 771 | private abstract class AbstractClientConnection implements ClientConnection { |
| 772 | private final Map<Long, Callback> futures = Maps.newConcurrentMap(); |
| 773 | private final AtomicBoolean closed = new AtomicBoolean(false); |
Jordan Halterman | ef92f19 | 2017-12-21 11:59:38 -0800 | [diff] [blame] | 774 | private final Cache<String, RequestMonitor> requestMonitors = CacheBuilder.newBuilder() |
Jordan Halterman | 1cf233c | 2017-12-08 23:52:54 -0800 | [diff] [blame] | 775 | .expireAfterAccess(HISTORY_EXPIRE_MILLIS, TimeUnit.MILLISECONDS) |
| 776 | .build(); |
| 777 | |
| 778 | /** |
| 779 | * Times out callbacks for this connection. |
| 780 | */ |
Jordan Halterman | ef92f19 | 2017-12-21 11:59:38 -0800 | [diff] [blame] | 781 | void timeoutCallbacks() { |
Jordan Halterman | 1cf233c | 2017-12-08 23:52:54 -0800 | [diff] [blame] | 782 | // Store the current time. |
| 783 | long currentTime = System.currentTimeMillis(); |
| 784 | |
| 785 | // Iterate through future callbacks and time out callbacks that have been alive |
| 786 | // longer than the current timeout according to the message type. |
| 787 | Iterator<Map.Entry<Long, Callback>> iterator = futures.entrySet().iterator(); |
| 788 | while (iterator.hasNext()) { |
| 789 | Callback callback = iterator.next().getValue(); |
| 790 | try { |
Jordan Halterman | ef92f19 | 2017-12-21 11:59:38 -0800 | [diff] [blame] | 791 | RequestMonitor requestMonitor = requestMonitors.get(callback.type, RequestMonitor::new); |
| 792 | long elapsedTime = currentTime - callback.time; |
Jordan Halterman | 111aab7 | 2018-01-12 16:28:57 -0800 | [diff] [blame] | 793 | if (elapsedTime > MAX_TIMEOUT_MILLIS || |
| 794 | (elapsedTime > MIN_TIMEOUT_MILLIS && requestMonitor.isTimedOut(elapsedTime))) { |
Jordan Halterman | 1cf233c | 2017-12-08 23:52:54 -0800 | [diff] [blame] | 795 | iterator.remove(); |
Jordan Halterman | ef92f19 | 2017-12-21 11:59:38 -0800 | [diff] [blame] | 796 | requestMonitor.addReplyTime(elapsedTime); |
Jordan Halterman | 1cf233c | 2017-12-08 23:52:54 -0800 | [diff] [blame] | 797 | callback.completeExceptionally( |
| 798 | new TimeoutException("Request timed out in " + elapsedTime + " milliseconds")); |
| 799 | } |
| 800 | } catch (ExecutionException e) { |
| 801 | throw new AssertionError(); |
| 802 | } |
| 803 | } |
Jordan Halterman | 1cf233c | 2017-12-08 23:52:54 -0800 | [diff] [blame] | 804 | } |
| 805 | |
| 806 | protected void registerCallback(long id, String subject, CompletableFuture<byte[]> future) { |
| 807 | futures.put(id, new Callback(subject, future)); |
| 808 | } |
| 809 | |
| 810 | protected Callback completeCallback(long id) { |
| 811 | Callback callback = futures.remove(id); |
| 812 | if (callback != null) { |
| 813 | try { |
Jordan Halterman | ef92f19 | 2017-12-21 11:59:38 -0800 | [diff] [blame] | 814 | RequestMonitor requestMonitor = requestMonitors.get(callback.type, RequestMonitor::new); |
| 815 | requestMonitor.addReplyTime(System.currentTimeMillis() - callback.time); |
Jordan Halterman | 1cf233c | 2017-12-08 23:52:54 -0800 | [diff] [blame] | 816 | } catch (ExecutionException e) { |
| 817 | throw new AssertionError(); |
| 818 | } |
| 819 | } |
| 820 | return callback; |
| 821 | } |
| 822 | |
| 823 | protected Callback failCallback(long id) { |
| 824 | return futures.remove(id); |
| 825 | } |
| 826 | |
| 827 | @Override |
| 828 | public void close() { |
| 829 | if (closed.compareAndSet(false, true)) { |
Jordan Halterman | 1cf233c | 2017-12-08 23:52:54 -0800 | [diff] [blame] | 830 | for (Callback callback : futures.values()) { |
| 831 | callback.completeExceptionally(new ConnectException()); |
| 832 | } |
| 833 | } |
| 834 | } |
| 835 | } |
| 836 | |
| 837 | /** |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 838 | * Local connection implementation. |
| 839 | */ |
Jordan Halterman | 1cf233c | 2017-12-08 23:52:54 -0800 | [diff] [blame] | 840 | private final class LocalClientConnection extends AbstractClientConnection { |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 841 | @Override |
Jordan Halterman | e3813a9 | 2017-07-29 14:10:31 -0700 | [diff] [blame] | 842 | public CompletableFuture<Void> sendAsync(InternalRequest message) { |
| 843 | BiConsumer<InternalRequest, ServerConnection> handler = handlers.get(message.subject()); |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 844 | if (handler != null) { |
| 845 | handler.accept(message, localServerConnection); |
| 846 | } else { |
| 847 | log.debug("No handler for message type {} from {}", message.type(), message.sender()); |
| 848 | } |
| 849 | return CompletableFuture.completedFuture(null); |
| 850 | } |
| 851 | |
| 852 | @Override |
Jordan Halterman | e3813a9 | 2017-07-29 14:10:31 -0700 | [diff] [blame] | 853 | public CompletableFuture<byte[]> sendAndReceive(InternalRequest message) { |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 854 | CompletableFuture<byte[]> future = new CompletableFuture<>(); |
Jordan Halterman | 1cf233c | 2017-12-08 23:52:54 -0800 | [diff] [blame] | 855 | future.whenComplete((r, e) -> completeCallback(message.id())); |
| 856 | registerCallback(message.id(), message.subject(), future); |
Jordan Halterman | e3813a9 | 2017-07-29 14:10:31 -0700 | [diff] [blame] | 857 | BiConsumer<InternalRequest, ServerConnection> handler = handlers.get(message.subject()); |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 858 | if (handler != null) { |
| 859 | handler.accept(message, new LocalServerConnection(future)); |
| 860 | } else { |
| 861 | log.debug("No handler for message type {} from {}", message.type(), message.sender()); |
Jordan Halterman | e3813a9 | 2017-07-29 14:10:31 -0700 | [diff] [blame] | 862 | new LocalServerConnection(future) |
| 863 | .reply(message, InternalReply.Status.ERROR_NO_HANDLER, Optional.empty()); |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 864 | } |
| 865 | return future; |
| 866 | } |
| 867 | } |
| 868 | |
| 869 | /** |
| 870 | * Local server connection. |
| 871 | */ |
| 872 | private final class LocalServerConnection implements ServerConnection { |
| 873 | private final CompletableFuture<byte[]> future; |
| 874 | |
| 875 | LocalServerConnection(CompletableFuture<byte[]> future) { |
| 876 | this.future = future; |
| 877 | } |
| 878 | |
| 879 | @Override |
Jordan Halterman | e3813a9 | 2017-07-29 14:10:31 -0700 | [diff] [blame] | 880 | public void reply(InternalRequest message, InternalReply.Status status, Optional<byte[]> payload) { |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 881 | if (future != null) { |
Jordan Halterman | e3813a9 | 2017-07-29 14:10:31 -0700 | [diff] [blame] | 882 | if (status == InternalReply.Status.OK) { |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 883 | future.complete(payload.orElse(EMPTY_PAYLOAD)); |
Jordan Halterman | e3813a9 | 2017-07-29 14:10:31 -0700 | [diff] [blame] | 884 | } else if (status == InternalReply.Status.ERROR_NO_HANDLER) { |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 885 | future.completeExceptionally(new MessagingException.NoRemoteHandler()); |
Jordan Halterman | e3813a9 | 2017-07-29 14:10:31 -0700 | [diff] [blame] | 886 | } else if (status == InternalReply.Status.ERROR_HANDLER_EXCEPTION) { |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 887 | future.completeExceptionally(new MessagingException.RemoteHandlerFailure()); |
Jordan Halterman | e3813a9 | 2017-07-29 14:10:31 -0700 | [diff] [blame] | 888 | } else if (status == InternalReply.Status.PROTOCOL_EXCEPTION) { |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 889 | future.completeExceptionally(new MessagingException.ProtocolException()); |
| 890 | } |
| 891 | } |
| 892 | } |
| 893 | } |
| 894 | |
| 895 | /** |
| 896 | * Remote connection implementation. |
| 897 | */ |
Jordan Halterman | 1cf233c | 2017-12-08 23:52:54 -0800 | [diff] [blame] | 898 | private final class RemoteClientConnection extends AbstractClientConnection { |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 899 | private final Channel channel; |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 900 | |
| 901 | RemoteClientConnection(Channel channel) { |
| 902 | this.channel = channel; |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 903 | } |
| 904 | |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 905 | @Override |
Jordan Halterman | e3813a9 | 2017-07-29 14:10:31 -0700 | [diff] [blame] | 906 | public CompletableFuture<Void> sendAsync(InternalRequest message) { |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 907 | CompletableFuture<Void> future = new CompletableFuture<>(); |
| 908 | channel.writeAndFlush(message).addListener(channelFuture -> { |
| 909 | if (!channelFuture.isSuccess()) { |
| 910 | future.completeExceptionally(channelFuture.cause()); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 911 | } else { |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 912 | future.complete(null); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 913 | } |
| 914 | }); |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 915 | return future; |
| 916 | } |
| 917 | |
| 918 | @Override |
Jordan Halterman | e3813a9 | 2017-07-29 14:10:31 -0700 | [diff] [blame] | 919 | public CompletableFuture<byte[]> sendAndReceive(InternalRequest message) { |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 920 | CompletableFuture<byte[]> future = new CompletableFuture<>(); |
Jordan Halterman | 1cf233c | 2017-12-08 23:52:54 -0800 | [diff] [blame] | 921 | registerCallback(message.id(), message.subject(), future); |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 922 | channel.writeAndFlush(message).addListener(channelFuture -> { |
| 923 | if (!channelFuture.isSuccess()) { |
Jordan Halterman | 1cf233c | 2017-12-08 23:52:54 -0800 | [diff] [blame] | 924 | Callback callback = failCallback(message.id()); |
| 925 | if (callback != null) { |
| 926 | callback.completeExceptionally(channelFuture.cause()); |
| 927 | } |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 928 | } |
| 929 | }); |
| 930 | return future; |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 931 | } |
| 932 | |
| 933 | /** |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 934 | * Dispatches a message to a local handler. |
| 935 | * |
| 936 | * @param message the message to dispatch |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 937 | */ |
Jordan Halterman | e3813a9 | 2017-07-29 14:10:31 -0700 | [diff] [blame] | 938 | private void dispatch(InternalReply message) { |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 939 | if (message.preamble() != preamble) { |
Jordan Halterman | e3813a9 | 2017-07-29 14:10:31 -0700 | [diff] [blame] | 940 | log.debug("Received {} with invalid preamble", message.type()); |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 941 | return; |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 942 | } |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 943 | |
| 944 | clockService.recordEventTime(message.time()); |
| 945 | |
Jordan Halterman | 1cf233c | 2017-12-08 23:52:54 -0800 | [diff] [blame] | 946 | Callback callback = completeCallback(message.id()); |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 947 | if (callback != null) { |
Jordan Halterman | e3813a9 | 2017-07-29 14:10:31 -0700 | [diff] [blame] | 948 | if (message.status() == InternalReply.Status.OK) { |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 949 | callback.complete(message.payload()); |
Jordan Halterman | e3813a9 | 2017-07-29 14:10:31 -0700 | [diff] [blame] | 950 | } else if (message.status() == InternalReply.Status.ERROR_NO_HANDLER) { |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 951 | callback.completeExceptionally(new MessagingException.NoRemoteHandler()); |
Jordan Halterman | e3813a9 | 2017-07-29 14:10:31 -0700 | [diff] [blame] | 952 | } else if (message.status() == InternalReply.Status.ERROR_HANDLER_EXCEPTION) { |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 953 | callback.completeExceptionally(new MessagingException.RemoteHandlerFailure()); |
Jordan Halterman | e3813a9 | 2017-07-29 14:10:31 -0700 | [diff] [blame] | 954 | } else if (message.status() == InternalReply.Status.PROTOCOL_EXCEPTION) { |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 955 | callback.completeExceptionally(new MessagingException.ProtocolException()); |
| 956 | } |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 957 | } else { |
Jordan Halterman | e3813a9 | 2017-07-29 14:10:31 -0700 | [diff] [blame] | 958 | log.debug("Received a reply for message id:[{}] " |
| 959 | + "but was unable to locate the" |
| 960 | + " request handle", message.id()); |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 961 | } |
| 962 | } |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 963 | } |
| 964 | |
| 965 | /** |
| 966 | * Remote server connection. |
| 967 | */ |
| 968 | private final class RemoteServerConnection implements ServerConnection { |
| 969 | private final Channel channel; |
| 970 | |
| 971 | RemoteServerConnection(Channel channel) { |
| 972 | this.channel = channel; |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 973 | } |
| 974 | |
| 975 | /** |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 976 | * Dispatches a message to a local handler. |
| 977 | * |
| 978 | * @param message the message to dispatch |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 979 | */ |
Jordan Halterman | e3813a9 | 2017-07-29 14:10:31 -0700 | [diff] [blame] | 980 | private void dispatch(InternalRequest message) { |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 981 | if (message.preamble() != preamble) { |
| 982 | log.debug("Received {} with invalid preamble from {}", message.type(), message.sender()); |
Jordan Halterman | e3813a9 | 2017-07-29 14:10:31 -0700 | [diff] [blame] | 983 | reply(message, InternalReply.Status.PROTOCOL_EXCEPTION, Optional.empty()); |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 984 | return; |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 985 | } |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 986 | |
| 987 | clockService.recordEventTime(message.time()); |
| 988 | |
Jordan Halterman | e3813a9 | 2017-07-29 14:10:31 -0700 | [diff] [blame] | 989 | BiConsumer<InternalRequest, ServerConnection> handler = handlers.get(message.subject()); |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 990 | if (handler != null) { |
| 991 | handler.accept(message, this); |
| 992 | } else { |
| 993 | log.debug("No handler for message type {} from {}", message.type(), message.sender()); |
Jordan Halterman | e3813a9 | 2017-07-29 14:10:31 -0700 | [diff] [blame] | 994 | reply(message, InternalReply.Status.ERROR_NO_HANDLER, Optional.empty()); |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 995 | } |
| 996 | } |
| 997 | |
| 998 | @Override |
Jordan Halterman | e3813a9 | 2017-07-29 14:10:31 -0700 | [diff] [blame] | 999 | public void reply(InternalRequest message, InternalReply.Status status, Optional<byte[]> payload) { |
| 1000 | InternalReply response = new InternalReply(preamble, |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 1001 | clockService.timeNow(), |
| 1002 | message.id(), |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 1003 | payload.orElse(EMPTY_PAYLOAD), |
| 1004 | status); |
| 1005 | channel.writeAndFlush(response); |
| 1006 | } |
| 1007 | } |
| 1008 | |
| 1009 | /** |
| 1010 | * Request-reply timeout history tracker. |
| 1011 | */ |
Jordan Halterman | ef92f19 | 2017-12-21 11:59:38 -0800 | [diff] [blame] | 1012 | private static final class RequestMonitor { |
| 1013 | private final DescriptiveStatistics samples = new SynchronizedDescriptiveStatistics(WINDOW_SIZE); |
Jordan Halterman | 0529908 | 2018-05-14 14:45:20 -0700 | [diff] [blame^] | 1014 | private final AtomicLong max = new AtomicLong(); |
| 1015 | private volatile int replyCount; |
| 1016 | private volatile long lastUpdate = System.currentTimeMillis(); |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 1017 | |
| 1018 | /** |
| 1019 | * Adds a reply time to the history. |
| 1020 | * |
| 1021 | * @param replyTime the reply time to add to the history |
| 1022 | */ |
| 1023 | void addReplyTime(long replyTime) { |
Jordan Halterman | 0529908 | 2018-05-14 14:45:20 -0700 | [diff] [blame^] | 1024 | max.accumulateAndGet(replyTime, Math::max); |
| 1025 | |
| 1026 | // If at least WINDOW_UPDATE_SAMPLE_SIZE response times have been recorded, and at least |
| 1027 | // WINDOW_UPDATE_MILLIS have passed since the last update, record the maximum response time in the samples. |
| 1028 | int replyCount = ++this.replyCount; |
| 1029 | if (replyCount >= WINDOW_UPDATE_SAMPLE_SIZE |
| 1030 | && System.currentTimeMillis() - lastUpdate > WINDOW_UPDATE_MILLIS) { |
| 1031 | synchronized (this) { |
| 1032 | if (System.currentTimeMillis() - lastUpdate > WINDOW_UPDATE_MILLIS) { |
| 1033 | long lastMax = max.get(); |
| 1034 | if (lastMax > 0) { |
| 1035 | samples.addValue(lastMax); |
| 1036 | lastUpdate = System.currentTimeMillis(); |
| 1037 | this.replyCount = 0; |
| 1038 | max.set(0); |
| 1039 | } |
| 1040 | } |
| 1041 | } |
| 1042 | } |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 1043 | } |
| 1044 | |
| 1045 | /** |
Jordan Halterman | ef92f19 | 2017-12-21 11:59:38 -0800 | [diff] [blame] | 1046 | * Returns a boolean indicating whether the given request should be timed out according to the elapsed time. |
| 1047 | * |
| 1048 | * @param elapsedTime the elapsed request time |
| 1049 | * @return indicates whether the request should be timed out |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 1050 | */ |
Jordan Halterman | ef92f19 | 2017-12-21 11:59:38 -0800 | [diff] [blame] | 1051 | boolean isTimedOut(long elapsedTime) { |
Jordan Halterman | 0529908 | 2018-05-14 14:45:20 -0700 | [diff] [blame^] | 1052 | return samples.getN() == WINDOW_SIZE && phi(elapsedTime) >= PHI_FAILURE_THRESHOLD; |
Jordan Halterman | ef92f19 | 2017-12-21 11:59:38 -0800 | [diff] [blame] | 1053 | } |
| 1054 | |
| 1055 | /** |
| 1056 | * Compute phi for the specified node id. |
| 1057 | * |
| 1058 | * @param elapsedTime the duration since the request was sent |
| 1059 | * @return phi value |
| 1060 | */ |
| 1061 | private double phi(long elapsedTime) { |
| 1062 | if (samples.getN() < MIN_SAMPLES) { |
| 1063 | return 0.0; |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 1064 | } |
Jordan Halterman | ef92f19 | 2017-12-21 11:59:38 -0800 | [diff] [blame] | 1065 | return computePhi(samples, elapsedTime); |
| 1066 | } |
| 1067 | |
| 1068 | /** |
| 1069 | * Computes the phi value from the given samples. |
| 1070 | * |
| 1071 | * @param samples the samples from which to compute phi |
| 1072 | * @param elapsedTime the duration since the request was sent |
| 1073 | * @return phi |
| 1074 | */ |
| 1075 | private double computePhi(DescriptiveStatistics samples, long elapsedTime) { |
Jordan Halterman | 0529908 | 2018-05-14 14:45:20 -0700 | [diff] [blame^] | 1076 | double meanMillis = samples.getMean(); |
| 1077 | double y = (elapsedTime - meanMillis) / Math.max(samples.getStandardDeviation(), MIN_STANDARD_DEVIATION); |
| 1078 | double e = Math.exp(-y * (1.5976 + 0.070566 * y * y)); |
| 1079 | if (elapsedTime > meanMillis) { |
| 1080 | return -Math.log10(e / (1.0 + e)); |
| 1081 | } else { |
| 1082 | return -Math.log10(1.0 - 1.0 / (1.0 + e)); |
| 1083 | } |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 1084 | } |
| 1085 | } |
JunHuy Lam | 39eb429 | 2015-06-26 17:24:23 +0900 | [diff] [blame] | 1086 | } |