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