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