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