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