Thomas Vachuska | 58de416 | 2015-09-10 16:15:33 -0700 | [diff] [blame] | 1 | /* |
Brian O'Connor | 5ab426f | 2016-04-09 01:19:45 -0700 | [diff] [blame] | 2 | * Copyright 2015-present Open Networking Laboratory |
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 | |
JunHuy Lam | 39eb429 | 2015-06-26 17:24:23 +0900 | [diff] [blame] | 18 | import com.google.common.base.Strings; |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 19 | import com.google.common.cache.Cache; |
| 20 | import com.google.common.cache.CacheBuilder; |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 21 | import com.google.common.collect.Maps; |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 22 | import com.google.common.util.concurrent.MoreExecutors; |
Madan Jampani | a9e70a6 | 2016-03-02 16:28:18 -0800 | [diff] [blame] | 23 | |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 24 | import io.netty.bootstrap.Bootstrap; |
| 25 | import io.netty.bootstrap.ServerBootstrap; |
| 26 | import io.netty.buffer.PooledByteBufAllocator; |
| 27 | import io.netty.channel.Channel; |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 28 | import io.netty.channel.ChannelHandler; |
| 29 | import io.netty.channel.ChannelHandlerContext; |
| 30 | import io.netty.channel.ChannelInitializer; |
| 31 | import io.netty.channel.ChannelOption; |
| 32 | import io.netty.channel.EventLoopGroup; |
| 33 | import io.netty.channel.ServerChannel; |
| 34 | import io.netty.channel.SimpleChannelInboundHandler; |
Jon Hall | 9a44d6a | 2017-03-02 18:14:37 -0800 | [diff] [blame] | 35 | import io.netty.channel.WriteBufferWaterMark; |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 36 | import io.netty.channel.epoll.EpollEventLoopGroup; |
| 37 | import io.netty.channel.epoll.EpollServerSocketChannel; |
| 38 | import io.netty.channel.epoll.EpollSocketChannel; |
| 39 | import io.netty.channel.nio.NioEventLoopGroup; |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 40 | import io.netty.channel.pool.AbstractChannelPoolHandler; |
| 41 | import io.netty.channel.pool.AbstractChannelPoolMap; |
| 42 | import io.netty.channel.pool.ChannelPool; |
| 43 | import io.netty.channel.pool.ChannelPoolMap; |
| 44 | import io.netty.channel.pool.SimpleChannelPool; |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 45 | import io.netty.channel.socket.SocketChannel; |
| 46 | import io.netty.channel.socket.nio.NioServerSocketChannel; |
| 47 | import io.netty.channel.socket.nio.NioSocketChannel; |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 48 | import io.netty.util.concurrent.FutureListener; |
| 49 | import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; |
| 50 | import org.apache.commons.math3.stat.descriptive.SynchronizedDescriptiveStatistics; |
Madan Jampani | afeebbd | 2015-05-19 15:26:01 -0700 | [diff] [blame] | 51 | import org.apache.felix.scr.annotations.Activate; |
| 52 | import org.apache.felix.scr.annotations.Component; |
| 53 | import org.apache.felix.scr.annotations.Deactivate; |
| 54 | import org.apache.felix.scr.annotations.Reference; |
| 55 | import org.apache.felix.scr.annotations.ReferenceCardinality; |
| 56 | import org.apache.felix.scr.annotations.Service; |
Madan Jampani | ec1df02 | 2015-10-13 21:23:03 -0700 | [diff] [blame] | 57 | import org.onosproject.cluster.ClusterMetadataService; |
Madan Jampani | afeebbd | 2015-05-19 15:26:01 -0700 | [diff] [blame] | 58 | import org.onosproject.cluster.ControllerNode; |
Madan Jampani | 0583387 | 2016-07-12 23:01:39 -0700 | [diff] [blame] | 59 | import org.onosproject.core.HybridLogicalClockService; |
Madan Jampani | afeebbd | 2015-05-19 15:26:01 -0700 | [diff] [blame] | 60 | import org.onosproject.store.cluster.messaging.Endpoint; |
Madan Jampani | a9e70a6 | 2016-03-02 16:28:18 -0800 | [diff] [blame] | 61 | import org.onosproject.store.cluster.messaging.MessagingException; |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 62 | import org.onosproject.store.cluster.messaging.MessagingService; |
Madan Jampani | a9e70a6 | 2016-03-02 16:28:18 -0800 | [diff] [blame] | 63 | import org.onosproject.store.cluster.messaging.impl.InternalMessage.Status; |
Madan Jampani | afeebbd | 2015-05-19 15:26:01 -0700 | [diff] [blame] | 64 | import org.slf4j.Logger; |
| 65 | import org.slf4j.LoggerFactory; |
| 66 | |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 67 | import javax.net.ssl.KeyManagerFactory; |
| 68 | import javax.net.ssl.SSLContext; |
| 69 | import javax.net.ssl.SSLEngine; |
| 70 | import javax.net.ssl.TrustManagerFactory; |
Madan Jampani | a9e70a6 | 2016-03-02 16:28:18 -0800 | [diff] [blame] | 71 | |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 72 | import java.io.FileInputStream; |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 73 | import java.net.ConnectException; |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 74 | import java.security.KeyStore; |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 75 | import java.time.Duration; |
| 76 | import java.util.Iterator; |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 77 | import java.util.Map; |
Madan Jampani | a9e70a6 | 2016-03-02 16:28:18 -0800 | [diff] [blame] | 78 | import java.util.Optional; |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 79 | import java.util.concurrent.CompletableFuture; |
| 80 | import java.util.concurrent.ConcurrentHashMap; |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 81 | import java.util.concurrent.ExecutionException; |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 82 | import java.util.concurrent.Executor; |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 83 | import java.util.concurrent.Executors; |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 84 | import java.util.concurrent.RejectedExecutionException; |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 85 | import java.util.concurrent.ScheduledExecutorService; |
| 86 | import java.util.concurrent.ScheduledFuture; |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 87 | import java.util.concurrent.TimeUnit; |
| 88 | import java.util.concurrent.TimeoutException; |
| 89 | import java.util.concurrent.atomic.AtomicBoolean; |
| 90 | import java.util.concurrent.atomic.AtomicLong; |
| 91 | import java.util.function.BiConsumer; |
| 92 | import java.util.function.BiFunction; |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 93 | import java.util.function.Function; |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 94 | |
Yuta HIGUCHI | 90a1689 | 2016-07-20 20:36:08 -0700 | [diff] [blame] | 95 | import static org.onlab.util.Tools.groupedThreads; |
Heedo Kang | 4a47a30 | 2016-02-29 17:40:23 +0900 | [diff] [blame] | 96 | import static org.onosproject.security.AppGuard.checkPermission; |
| 97 | import static org.onosproject.security.AppPermission.Type.CLUSTER_WRITE; |
| 98 | |
Madan Jampani | afeebbd | 2015-05-19 15:26:01 -0700 | [diff] [blame] | 99 | /** |
| 100 | * Netty based MessagingService. |
| 101 | */ |
Sho SHIMIZU | 5c396e3 | 2016-08-12 15:19:12 -0700 | [diff] [blame] | 102 | @Component(immediate = true) |
Madan Jampani | afeebbd | 2015-05-19 15:26:01 -0700 | [diff] [blame] | 103 | @Service |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 104 | public class NettyMessagingManager implements MessagingService { |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 105 | private static final long DEFAULT_TIMEOUT_MILLIS = 500; |
| 106 | private static final long HISTORY_EXPIRE_MILLIS = Duration.ofMinutes(10).toMillis(); |
| 107 | private static final long MIN_TIMEOUT_MILLIS = 100; |
| 108 | private static final long MAX_TIMEOUT_MILLIS = 5000; |
| 109 | private static final long TIMEOUT_INTERVAL = 50; |
| 110 | private static final int WINDOW_SIZE = 100; |
| 111 | private static final double TIMEOUT_MULTIPLIER = 2.5; |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 112 | private static final short MIN_KS_LENGTH = 6; |
Madan Jampani | afeebbd | 2015-05-19 15:26:01 -0700 | [diff] [blame] | 113 | |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 114 | private static final byte[] EMPTY_PAYLOAD = new byte[0]; |
| 115 | |
Madan Jampani | afeebbd | 2015-05-19 15:26:01 -0700 | [diff] [blame] | 116 | private final Logger log = LoggerFactory.getLogger(getClass()); |
| 117 | |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 118 | private final ClientConnection localClientConnection = new LocalClientConnection(); |
| 119 | private final ServerConnection localServerConnection = new LocalServerConnection(null); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 120 | |
Madan Jampani | 0583387 | 2016-07-12 23:01:39 -0700 | [diff] [blame] | 121 | @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) |
| 122 | protected HybridLogicalClockService clockService; |
| 123 | |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 124 | private Endpoint localEndpoint; |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 125 | private int preamble; |
| 126 | private final AtomicBoolean started = new AtomicBoolean(false); |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 127 | private final Map<String, BiConsumer<InternalMessage, ServerConnection>> handlers = new ConcurrentHashMap<>(); |
| 128 | private final Map<Channel, RemoteClientConnection> clientConnections = Maps.newConcurrentMap(); |
| 129 | private final Map<Channel, RemoteServerConnection> serverConnections = Maps.newConcurrentMap(); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 130 | private final AtomicLong messageIdGenerator = new AtomicLong(0); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 131 | |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 132 | private final Cache<String, TimeoutHistory> timeoutHistories = CacheBuilder.newBuilder() |
| 133 | .expireAfterAccess(HISTORY_EXPIRE_MILLIS, TimeUnit.MILLISECONDS) |
| 134 | .build(); |
| 135 | private ScheduledFuture<?> timeoutFuture; |
| 136 | |
| 137 | private final ChannelPoolMap<Endpoint, SimpleChannelPool> channels = |
| 138 | new AbstractChannelPoolMap<Endpoint, SimpleChannelPool>() { |
| 139 | @Override |
| 140 | protected SimpleChannelPool newPool(Endpoint endpoint) { |
| 141 | return new SimpleChannelPool(bootstrapClient(endpoint), new ClientChannelPoolHandler()); |
| 142 | } |
| 143 | }; |
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 | |
| 151 | protected static final boolean TLS_DISABLED = false; |
| 152 | protected boolean enableNettyTls = TLS_DISABLED; |
| 153 | |
| 154 | protected String ksLocation; |
| 155 | protected String tsLocation; |
| 156 | protected char[] ksPwd; |
| 157 | protected char[] tsPwd; |
JunHuy Lam | 39eb429 | 2015-06-26 17:24:23 +0900 | [diff] [blame] | 158 | |
Madan Jampani | afeebbd | 2015-05-19 15:26:01 -0700 | [diff] [blame] | 159 | @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) |
Madan Jampani | ec1df02 | 2015-10-13 21:23:03 -0700 | [diff] [blame] | 160 | protected ClusterMetadataService clusterMetadataService; |
Madan Jampani | afeebbd | 2015-05-19 15:26:01 -0700 | [diff] [blame] | 161 | |
| 162 | @Activate |
| 163 | public void activate() throws Exception { |
Madan Jampani | ec1df02 | 2015-10-13 21:23:03 -0700 | [diff] [blame] | 164 | ControllerNode localNode = clusterMetadataService.getLocalNode(); |
Jonathan Hart | d9df7bd | 2015-11-10 17:10:25 -0800 | [diff] [blame] | 165 | getTlsParameters(); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 166 | |
| 167 | if (started.get()) { |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 168 | log.warn("Already running at local endpoint: {}", localEndpoint); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 169 | return; |
| 170 | } |
| 171 | this.preamble = clusterMetadataService.getClusterMetadata().getName().hashCode(); |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 172 | this.localEndpoint = new Endpoint(localNode.ip(), localNode.tcpPort()); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 173 | initEventLoopGroup(); |
| 174 | startAcceptingConnections(); |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 175 | timeoutExecutor = Executors.newSingleThreadScheduledExecutor( |
| 176 | groupedThreads("NettyMessagingEvt", "timeout", log)); |
| 177 | timeoutFuture = timeoutExecutor.scheduleAtFixedRate( |
| 178 | this::timeoutAllCallbacks, TIMEOUT_INTERVAL, TIMEOUT_INTERVAL, TimeUnit.MILLISECONDS); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 179 | started.set(true); |
Madan Jampani | afeebbd | 2015-05-19 15:26:01 -0700 | [diff] [blame] | 180 | log.info("Started"); |
| 181 | } |
| 182 | |
| 183 | @Deactivate |
| 184 | public void deactivate() throws Exception { |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 185 | if (started.get()) { |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 186 | serverGroup.shutdownGracefully(); |
| 187 | clientGroup.shutdownGracefully(); |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 188 | timeoutFuture.cancel(false); |
| 189 | timeoutExecutor.shutdown(); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 190 | started.set(false); |
| 191 | } |
Madan Jampani | afeebbd | 2015-05-19 15:26:01 -0700 | [diff] [blame] | 192 | log.info("Stopped"); |
| 193 | } |
JunHuy Lam | 39eb429 | 2015-06-26 17:24:23 +0900 | [diff] [blame] | 194 | |
Jonathan Hart | d9df7bd | 2015-11-10 17:10:25 -0800 | [diff] [blame] | 195 | private void getTlsParameters() { |
JunHuy Lam | 39eb429 | 2015-06-26 17:24:23 +0900 | [diff] [blame] | 196 | String tempString = System.getProperty("enableNettyTLS"); |
Jonathan Hart | d9df7bd | 2015-11-10 17:10:25 -0800 | [diff] [blame] | 197 | enableNettyTls = Strings.isNullOrEmpty(tempString) ? TLS_DISABLED : Boolean.parseBoolean(tempString); |
| 198 | log.info("enableNettyTLS = {}", enableNettyTls); |
| 199 | if (enableNettyTls) { |
JunHuy Lam | 39eb429 | 2015-06-26 17:24:23 +0900 | [diff] [blame] | 200 | ksLocation = System.getProperty("javax.net.ssl.keyStore"); |
| 201 | if (Strings.isNullOrEmpty(ksLocation)) { |
Jonathan Hart | d9df7bd | 2015-11-10 17:10:25 -0800 | [diff] [blame] | 202 | enableNettyTls = TLS_DISABLED; |
JunHuy Lam | 39eb429 | 2015-06-26 17:24:23 +0900 | [diff] [blame] | 203 | return; |
| 204 | } |
| 205 | tsLocation = System.getProperty("javax.net.ssl.trustStore"); |
| 206 | if (Strings.isNullOrEmpty(tsLocation)) { |
Jonathan Hart | d9df7bd | 2015-11-10 17:10:25 -0800 | [diff] [blame] | 207 | enableNettyTls = TLS_DISABLED; |
JunHuy Lam | 39eb429 | 2015-06-26 17:24:23 +0900 | [diff] [blame] | 208 | return; |
| 209 | } |
| 210 | ksPwd = System.getProperty("javax.net.ssl.keyStorePassword").toCharArray(); |
| 211 | if (MIN_KS_LENGTH > ksPwd.length) { |
Jonathan Hart | d9df7bd | 2015-11-10 17:10:25 -0800 | [diff] [blame] | 212 | enableNettyTls = TLS_DISABLED; |
JunHuy Lam | 39eb429 | 2015-06-26 17:24:23 +0900 | [diff] [blame] | 213 | return; |
| 214 | } |
| 215 | tsPwd = System.getProperty("javax.net.ssl.trustStorePassword").toCharArray(); |
| 216 | if (MIN_KS_LENGTH > tsPwd.length) { |
Jonathan Hart | d9df7bd | 2015-11-10 17:10:25 -0800 | [diff] [blame] | 217 | enableNettyTls = TLS_DISABLED; |
JunHuy Lam | 39eb429 | 2015-06-26 17:24:23 +0900 | [diff] [blame] | 218 | return; |
| 219 | } |
| 220 | } |
| 221 | } |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 222 | |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 223 | private void initEventLoopGroup() { |
| 224 | // try Epoll first and if that does work, use nio. |
| 225 | try { |
Yuta HIGUCHI | 90a1689 | 2016-07-20 20:36:08 -0700 | [diff] [blame] | 226 | clientGroup = new EpollEventLoopGroup(0, groupedThreads("NettyMessagingEvt", "epollC-%d", log)); |
| 227 | serverGroup = new EpollEventLoopGroup(0, groupedThreads("NettyMessagingEvt", "epollS-%d", log)); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 228 | serverChannelClass = EpollServerSocketChannel.class; |
| 229 | clientChannelClass = EpollSocketChannel.class; |
| 230 | return; |
| 231 | } catch (Throwable e) { |
| 232 | log.debug("Failed to initialize native (epoll) transport. " |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 233 | + "Reason: {}. Proceeding with nio.", e.getMessage()); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 234 | } |
Yuta HIGUCHI | 90a1689 | 2016-07-20 20:36:08 -0700 | [diff] [blame] | 235 | clientGroup = new NioEventLoopGroup(0, groupedThreads("NettyMessagingEvt", "nioC-%d", log)); |
| 236 | serverGroup = new NioEventLoopGroup(0, groupedThreads("NettyMessagingEvt", "nioS-%d", log)); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 237 | serverChannelClass = NioServerSocketChannel.class; |
| 238 | clientChannelClass = NioSocketChannel.class; |
| 239 | } |
| 240 | |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 241 | /** |
| 242 | * Times out response callbacks. |
| 243 | */ |
| 244 | private void timeoutAllCallbacks() { |
| 245 | // Iterate through all connections and time out callbacks. |
| 246 | for (RemoteClientConnection connection : clientConnections.values()) { |
| 247 | connection.timeoutCallbacks(); |
| 248 | } |
| 249 | |
| 250 | // Iterate through all timeout histories and recompute the timeout. |
| 251 | for (TimeoutHistory timeoutHistory : timeoutHistories.asMap().values()) { |
| 252 | timeoutHistory.recomputeTimeoutMillis(); |
| 253 | } |
| 254 | } |
| 255 | |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 256 | @Override |
| 257 | public CompletableFuture<Void> sendAsync(Endpoint ep, String type, byte[] payload) { |
Heedo Kang | 4a47a30 | 2016-02-29 17:40:23 +0900 | [diff] [blame] | 258 | checkPermission(CLUSTER_WRITE); |
Madan Jampani | b825aeb | 2016-04-01 15:18:25 -0700 | [diff] [blame] | 259 | InternalMessage message = new InternalMessage(preamble, |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 260 | clockService.timeNow(), |
| 261 | messageIdGenerator.incrementAndGet(), |
| 262 | localEndpoint, |
| 263 | type, |
| 264 | payload); |
| 265 | return executeOnPooledConnection(ep, c -> c.sendAsync(message), MoreExecutors.directExecutor()); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 266 | } |
| 267 | |
| 268 | @Override |
| 269 | public CompletableFuture<byte[]> sendAndReceive(Endpoint ep, String type, byte[] payload) { |
Heedo Kang | 4a47a30 | 2016-02-29 17:40:23 +0900 | [diff] [blame] | 270 | checkPermission(CLUSTER_WRITE); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 271 | return sendAndReceive(ep, type, payload, MoreExecutors.directExecutor()); |
| 272 | } |
| 273 | |
| 274 | @Override |
| 275 | public CompletableFuture<byte[]> sendAndReceive(Endpoint ep, String type, byte[] payload, Executor executor) { |
Heedo Kang | 4a47a30 | 2016-02-29 17:40:23 +0900 | [diff] [blame] | 276 | checkPermission(CLUSTER_WRITE); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 277 | Long messageId = messageIdGenerator.incrementAndGet(); |
Madan Jampani | 0583387 | 2016-07-12 23:01:39 -0700 | [diff] [blame] | 278 | InternalMessage message = new InternalMessage(preamble, |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 279 | clockService.timeNow(), |
| 280 | messageId, |
| 281 | localEndpoint, |
| 282 | type, |
| 283 | payload); |
| 284 | return executeOnPooledConnection(ep, c -> c.sendAndReceive(message), executor); |
| 285 | } |
Jordan Halterman | 041534b | 2017-03-21 10:37:33 -0700 | [diff] [blame] | 286 | |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 287 | /** |
| 288 | * Executes the given callback on a pooled connection. |
| 289 | * |
| 290 | * @param endpoint the endpoint to which to send a message |
| 291 | * @param callback the callback to execute to send the message |
| 292 | * @param <T> the send result type |
| 293 | * @return a completable future to be completed with the result of the supplied function |
| 294 | */ |
| 295 | private <T> CompletableFuture<T> executeOnPooledConnection( |
| 296 | Endpoint endpoint, |
| 297 | Function<ClientConnection, CompletableFuture<T>> callback, |
| 298 | Executor executor) { |
| 299 | if (endpoint.equals(localEndpoint)) { |
| 300 | CompletableFuture<T> future = new CompletableFuture<>(); |
| 301 | callback.apply(localClientConnection).whenComplete((result, error) -> { |
| 302 | if (error == null) { |
| 303 | executor.execute(() -> future.complete(result)); |
| 304 | } else { |
| 305 | executor.execute(() -> future.completeExceptionally(error)); |
| 306 | } |
| 307 | }); |
| 308 | return future; |
| 309 | } |
| 310 | |
| 311 | CompletableFuture<T> future = new CompletableFuture<>(); |
| 312 | ChannelPool pool = channels.get(endpoint); |
| 313 | pool.acquire().addListener((FutureListener<Channel>) channelResult -> { |
| 314 | if (channelResult.isSuccess()) { |
| 315 | Channel channel = channelResult.getNow(); |
| 316 | ClientConnection connection = clientConnections.computeIfAbsent(channel, RemoteClientConnection::new); |
| 317 | callback.apply(connection).whenComplete((result, error) -> { |
| 318 | pool.release(channel).addListener(releaseResult -> { |
| 319 | if (!releaseResult.isSuccess()) { |
| 320 | clientConnections.remove(channel); |
| 321 | connection.close(); |
| 322 | } |
| 323 | }); |
| 324 | |
| 325 | if (error == null) { |
| 326 | executor.execute(() -> future.complete(result)); |
| 327 | } else { |
| 328 | executor.execute(() -> future.completeExceptionally(error)); |
| 329 | } |
| 330 | }); |
| 331 | } else { |
| 332 | executor.execute(() -> future.completeExceptionally(channelResult.cause())); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 333 | } |
Jordan Halterman | 041534b | 2017-03-21 10:37:33 -0700 | [diff] [blame] | 334 | }); |
| 335 | return future; |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 336 | } |
| 337 | |
| 338 | @Override |
| 339 | public void registerHandler(String type, BiConsumer<Endpoint, byte[]> handler, Executor executor) { |
Heedo Kang | 4a47a30 | 2016-02-29 17:40:23 +0900 | [diff] [blame] | 340 | checkPermission(CLUSTER_WRITE); |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 341 | handlers.put(type, (message, connection) -> executor.execute(() -> |
| 342 | handler.accept(message.sender(), message.payload()))); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 343 | } |
| 344 | |
| 345 | @Override |
| 346 | public void registerHandler(String type, BiFunction<Endpoint, byte[], byte[]> handler, Executor executor) { |
Heedo Kang | 4a47a30 | 2016-02-29 17:40:23 +0900 | [diff] [blame] | 347 | checkPermission(CLUSTER_WRITE); |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 348 | handlers.put(type, (message, connection) -> executor.execute(() -> { |
Madan Jampani | a9e70a6 | 2016-03-02 16:28:18 -0800 | [diff] [blame] | 349 | byte[] responsePayload = null; |
| 350 | Status status = Status.OK; |
| 351 | try { |
| 352 | responsePayload = handler.apply(message.sender(), message.payload()); |
| 353 | } catch (Exception e) { |
Jordan Halterman | b6ee9e9 | 2017-06-21 15:26:28 -0700 | [diff] [blame] | 354 | log.debug("An error occurred in a message handler: {}", e); |
Madan Jampani | a9e70a6 | 2016-03-02 16:28:18 -0800 | [diff] [blame] | 355 | status = Status.ERROR_HANDLER_EXCEPTION; |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 356 | } |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 357 | connection.reply(message, status, Optional.ofNullable(responsePayload)); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 358 | })); |
| 359 | } |
| 360 | |
| 361 | @Override |
| 362 | public void registerHandler(String type, BiFunction<Endpoint, byte[], CompletableFuture<byte[]>> handler) { |
Heedo Kang | 4a47a30 | 2016-02-29 17:40:23 +0900 | [diff] [blame] | 363 | checkPermission(CLUSTER_WRITE); |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 364 | handlers.put(type, (message, connection) -> { |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 365 | handler.apply(message.sender(), message.payload()).whenComplete((result, error) -> { |
Jordan Halterman | b6ee9e9 | 2017-06-21 15:26:28 -0700 | [diff] [blame] | 366 | Status status; |
| 367 | if (error == null) { |
| 368 | status = Status.OK; |
| 369 | } else { |
| 370 | log.debug("An error occurred in a message handler: {}", error); |
| 371 | status = Status.ERROR_HANDLER_EXCEPTION; |
| 372 | } |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 373 | connection.reply(message, status, Optional.ofNullable(result)); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 374 | }); |
| 375 | }); |
| 376 | } |
| 377 | |
| 378 | @Override |
| 379 | public void unregisterHandler(String type) { |
Heedo Kang | 4a47a30 | 2016-02-29 17:40:23 +0900 | [diff] [blame] | 380 | checkPermission(CLUSTER_WRITE); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 381 | handlers.remove(type); |
| 382 | } |
| 383 | |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 384 | private Bootstrap bootstrapClient(Endpoint endpoint) { |
| 385 | Bootstrap bootstrap = new Bootstrap(); |
| 386 | bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); |
| 387 | bootstrap.option(ChannelOption.WRITE_BUFFER_WATER_MARK, |
| 388 | new WriteBufferWaterMark(10 * 32 * 1024, 10 * 64 * 1024)); |
| 389 | bootstrap.option(ChannelOption.SO_SNDBUF, 1048576); |
| 390 | bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000); |
| 391 | bootstrap.group(clientGroup); |
| 392 | // TODO: Make this faster: |
| 393 | // http://normanmaurer.me/presentations/2014-facebook-eng-netty/slides.html#37.0 |
| 394 | bootstrap.channel(clientChannelClass); |
| 395 | bootstrap.option(ChannelOption.SO_KEEPALIVE, true); |
| 396 | bootstrap.remoteAddress(endpoint.host().toInetAddress(), endpoint.port()); |
| 397 | return bootstrap; |
| 398 | } |
| 399 | |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 400 | private void startAcceptingConnections() throws InterruptedException { |
| 401 | ServerBootstrap b = new ServerBootstrap(); |
Jon Hall | 9a44d6a | 2017-03-02 18:14:37 -0800 | [diff] [blame] | 402 | b.childOption(ChannelOption.WRITE_BUFFER_WATER_MARK, |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 403 | new WriteBufferWaterMark(8 * 1024, 32 * 1024)); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 404 | b.option(ChannelOption.SO_RCVBUF, 1048576); |
| 405 | b.option(ChannelOption.TCP_NODELAY, true); |
Yuta HIGUCHI | b47c953 | 2016-08-22 09:41:23 -0700 | [diff] [blame] | 406 | b.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 407 | b.group(serverGroup, clientGroup); |
| 408 | b.channel(serverChannelClass); |
| 409 | if (enableNettyTls) { |
| 410 | b.childHandler(new SslServerCommunicationChannelInitializer()); |
| 411 | } else { |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 412 | b.childHandler(new BasicChannelInitializer()); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 413 | } |
| 414 | b.option(ChannelOption.SO_BACKLOG, 128); |
| 415 | b.childOption(ChannelOption.SO_KEEPALIVE, true); |
| 416 | |
| 417 | // Bind and start to accept incoming connections. |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 418 | b.bind(localEndpoint.port()).sync().addListener(future -> { |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 419 | if (future.isSuccess()) { |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 420 | log.info("{} accepting incoming connections on port {}", |
| 421 | localEndpoint.host(), localEndpoint.port()); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 422 | } else { |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 423 | log.warn("{} failed to bind to port {} due to {}", |
| 424 | localEndpoint.host(), localEndpoint.port(), future.cause()); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 425 | } |
| 426 | }); |
| 427 | } |
| 428 | |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 429 | /** |
| 430 | * Channel pool handler. |
| 431 | */ |
| 432 | private class ClientChannelPoolHandler extends AbstractChannelPoolHandler { |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 433 | @Override |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 434 | public void channelCreated(Channel channel) throws Exception { |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 435 | if (enableNettyTls) { |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 436 | new SslClientCommunicationChannelInitializer().initChannel((SocketChannel) channel); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 437 | } else { |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 438 | new BasicChannelInitializer().initChannel((SocketChannel) channel); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 439 | } |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 440 | } |
| 441 | } |
| 442 | |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 443 | /** |
| 444 | * Channel initializer for TLS servers. |
| 445 | */ |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 446 | private class SslServerCommunicationChannelInitializer extends ChannelInitializer<SocketChannel> { |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 447 | private final ChannelHandler dispatcher = new InboundMessageDispatcher(); |
| 448 | private final ChannelHandler encoder = new MessageEncoder(preamble); |
| 449 | |
| 450 | @Override |
| 451 | protected void initChannel(SocketChannel channel) throws Exception { |
| 452 | TrustManagerFactory tmFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); |
| 453 | KeyStore ts = KeyStore.getInstance("JKS"); |
| 454 | ts.load(new FileInputStream(tsLocation), tsPwd); |
| 455 | tmFactory.init(ts); |
| 456 | |
| 457 | KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); |
| 458 | KeyStore ks = KeyStore.getInstance("JKS"); |
| 459 | ks.load(new FileInputStream(ksLocation), ksPwd); |
| 460 | kmf.init(ks, ksPwd); |
| 461 | |
| 462 | SSLContext serverContext = SSLContext.getInstance("TLS"); |
| 463 | serverContext.init(kmf.getKeyManagers(), tmFactory.getTrustManagers(), null); |
| 464 | |
| 465 | SSLEngine serverSslEngine = serverContext.createSSLEngine(); |
| 466 | |
| 467 | serverSslEngine.setNeedClientAuth(true); |
| 468 | serverSslEngine.setUseClientMode(false); |
| 469 | serverSslEngine.setEnabledProtocols(serverSslEngine.getSupportedProtocols()); |
| 470 | serverSslEngine.setEnabledCipherSuites(serverSslEngine.getSupportedCipherSuites()); |
| 471 | serverSslEngine.setEnableSessionCreation(true); |
| 472 | |
| 473 | channel.pipeline().addLast("ssl", new io.netty.handler.ssl.SslHandler(serverSslEngine)) |
| 474 | .addLast("encoder", encoder) |
Madan Jampani | b825aeb | 2016-04-01 15:18:25 -0700 | [diff] [blame] | 475 | .addLast("decoder", new MessageDecoder()) |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 476 | .addLast("handler", dispatcher); |
| 477 | } |
| 478 | } |
| 479 | |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 480 | /** |
| 481 | * Channel initializer for TLS clients. |
| 482 | */ |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 483 | private class SslClientCommunicationChannelInitializer extends ChannelInitializer<SocketChannel> { |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 484 | private final ChannelHandler dispatcher = new InboundMessageDispatcher(); |
| 485 | private final ChannelHandler encoder = new MessageEncoder(preamble); |
| 486 | |
| 487 | @Override |
| 488 | protected void initChannel(SocketChannel channel) throws Exception { |
| 489 | TrustManagerFactory tmFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); |
| 490 | KeyStore ts = KeyStore.getInstance("JKS"); |
| 491 | ts.load(new FileInputStream(tsLocation), tsPwd); |
| 492 | tmFactory.init(ts); |
| 493 | |
| 494 | KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); |
| 495 | KeyStore ks = KeyStore.getInstance("JKS"); |
| 496 | ks.load(new FileInputStream(ksLocation), ksPwd); |
| 497 | kmf.init(ks, ksPwd); |
| 498 | |
| 499 | SSLContext clientContext = SSLContext.getInstance("TLS"); |
| 500 | clientContext.init(kmf.getKeyManagers(), tmFactory.getTrustManagers(), null); |
| 501 | |
| 502 | SSLEngine clientSslEngine = clientContext.createSSLEngine(); |
| 503 | |
| 504 | clientSslEngine.setUseClientMode(true); |
| 505 | clientSslEngine.setEnabledProtocols(clientSslEngine.getSupportedProtocols()); |
| 506 | clientSslEngine.setEnabledCipherSuites(clientSslEngine.getSupportedCipherSuites()); |
| 507 | clientSslEngine.setEnableSessionCreation(true); |
| 508 | |
| 509 | channel.pipeline().addLast("ssl", new io.netty.handler.ssl.SslHandler(clientSslEngine)) |
| 510 | .addLast("encoder", encoder) |
Madan Jampani | b825aeb | 2016-04-01 15:18:25 -0700 | [diff] [blame] | 511 | .addLast("decoder", new MessageDecoder()) |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 512 | .addLast("handler", dispatcher); |
| 513 | } |
| 514 | } |
| 515 | |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 516 | /** |
| 517 | * Channel initializer for basic connections. |
| 518 | */ |
| 519 | private class BasicChannelInitializer extends ChannelInitializer<SocketChannel> { |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 520 | private final ChannelHandler dispatcher = new InboundMessageDispatcher(); |
| 521 | private final ChannelHandler encoder = new MessageEncoder(preamble); |
| 522 | |
| 523 | @Override |
| 524 | protected void initChannel(SocketChannel channel) throws Exception { |
| 525 | channel.pipeline() |
| 526 | .addLast("encoder", encoder) |
Madan Jampani | b825aeb | 2016-04-01 15:18:25 -0700 | [diff] [blame] | 527 | .addLast("decoder", new MessageDecoder()) |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 528 | .addLast("handler", dispatcher); |
| 529 | } |
| 530 | } |
| 531 | |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 532 | /** |
| 533 | * Channel inbound handler that dispatches messages to the appropriate handler. |
| 534 | */ |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 535 | @ChannelHandler.Sharable |
Yuta HIGUCHI | c012dda | 2016-08-17 00:43:46 -0700 | [diff] [blame] | 536 | private class InboundMessageDispatcher extends SimpleChannelInboundHandler<Object> { |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 537 | // Effectively SimpleChannelInboundHandler<InternalMessage>, |
| 538 | // 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] | 539 | |
| 540 | @Override |
Yuta HIGUCHI | c012dda | 2016-08-17 00:43:46 -0700 | [diff] [blame] | 541 | protected void channelRead0(ChannelHandlerContext ctx, Object rawMessage) throws Exception { |
| 542 | InternalMessage message = (InternalMessage) rawMessage; |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 543 | try { |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 544 | if (message.isRequest()) { |
| 545 | RemoteServerConnection connection = |
| 546 | serverConnections.computeIfAbsent(ctx.channel(), RemoteServerConnection::new); |
| 547 | connection.dispatch(message); |
| 548 | } else { |
| 549 | RemoteClientConnection connection = |
| 550 | clientConnections.computeIfAbsent(ctx.channel(), RemoteClientConnection::new); |
| 551 | connection.dispatch(message); |
| 552 | } |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 553 | } catch (RejectedExecutionException e) { |
| 554 | log.warn("Unable to dispatch message due to {}", e.getMessage()); |
| 555 | } |
| 556 | } |
| 557 | |
| 558 | @Override |
| 559 | public void exceptionCaught(ChannelHandlerContext context, Throwable cause) { |
| 560 | log.error("Exception inside channel handling pipeline.", cause); |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 561 | |
| 562 | RemoteClientConnection clientConnection = clientConnections.remove(context.channel()); |
| 563 | if (clientConnection != null) { |
| 564 | clientConnection.close(); |
| 565 | } |
| 566 | |
| 567 | RemoteServerConnection serverConnection = serverConnections.remove(context.channel()); |
| 568 | if (serverConnection != null) { |
| 569 | serverConnection.close(); |
| 570 | } |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 571 | context.close(); |
| 572 | } |
Yuta HIGUCHI | c012dda | 2016-08-17 00:43:46 -0700 | [diff] [blame] | 573 | |
| 574 | /** |
| 575 | * Returns true if the given message should be handled. |
| 576 | * |
| 577 | * @param msg inbound message |
| 578 | * @return true if {@code msg} is {@link InternalMessage} instance. |
| 579 | * |
| 580 | * @see SimpleChannelInboundHandler#acceptInboundMessage(Object) |
| 581 | */ |
| 582 | @Override |
| 583 | public final boolean acceptInboundMessage(Object msg) { |
| 584 | return msg instanceof InternalMessage; |
| 585 | } |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 586 | } |
Yuta HIGUCHI | c012dda | 2016-08-17 00:43:46 -0700 | [diff] [blame] | 587 | |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 588 | /** |
| 589 | * Wraps a {@link CompletableFuture} and tracks its type and creation time. |
| 590 | */ |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 591 | private final class Callback { |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 592 | private final String type; |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 593 | private final CompletableFuture<byte[]> future; |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 594 | private final long time = System.currentTimeMillis(); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 595 | |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 596 | Callback(String type, CompletableFuture<byte[]> future) { |
| 597 | this.type = type; |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 598 | this.future = future; |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 599 | } |
| 600 | |
| 601 | public void complete(byte[] value) { |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 602 | future.complete(value); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 603 | } |
| 604 | |
| 605 | public void completeExceptionally(Throwable error) { |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 606 | future.completeExceptionally(error); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 607 | } |
| 608 | } |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 609 | |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 610 | /** |
| 611 | * Represents the client side of a connection to a local or remote server. |
| 612 | */ |
| 613 | private interface ClientConnection { |
| 614 | |
| 615 | /** |
| 616 | * Sends a message to the other side of the connection. |
| 617 | * |
| 618 | * @param message the message to send |
| 619 | * @return a completable future to be completed once the message has been sent |
| 620 | */ |
| 621 | CompletableFuture<Void> sendAsync(InternalMessage message); |
| 622 | |
| 623 | /** |
| 624 | * Sends a message to the other side of the connection, awaiting a reply. |
| 625 | * |
| 626 | * @param message the message to send |
| 627 | * @return a completable future to be completed once a reply is received or the request times out |
| 628 | */ |
| 629 | CompletableFuture<byte[]> sendAndReceive(InternalMessage message); |
| 630 | |
| 631 | /** |
| 632 | * Closes the connection. |
| 633 | */ |
| 634 | default void close() { |
| 635 | } |
| 636 | } |
| 637 | |
| 638 | /** |
| 639 | * Represents the server side of a connection. |
| 640 | */ |
| 641 | private interface ServerConnection { |
| 642 | |
| 643 | /** |
| 644 | * Sends a reply to the other side of the connection. |
| 645 | * |
| 646 | * @param message the message to which to reply |
| 647 | * @param status the reply status |
| 648 | * @param payload the response payload |
| 649 | */ |
| 650 | void reply(InternalMessage message, Status status, Optional<byte[]> payload); |
| 651 | |
| 652 | /** |
| 653 | * Closes the connection. |
| 654 | */ |
| 655 | default void close() { |
| 656 | } |
| 657 | } |
| 658 | |
| 659 | /** |
| 660 | * Local connection implementation. |
| 661 | */ |
| 662 | private final class LocalClientConnection implements ClientConnection { |
| 663 | @Override |
| 664 | public CompletableFuture<Void> sendAsync(InternalMessage message) { |
| 665 | BiConsumer<InternalMessage, ServerConnection> handler = handlers.get(message.type()); |
| 666 | if (handler != null) { |
| 667 | handler.accept(message, localServerConnection); |
| 668 | } else { |
| 669 | log.debug("No handler for message type {} from {}", message.type(), message.sender()); |
| 670 | } |
| 671 | return CompletableFuture.completedFuture(null); |
| 672 | } |
| 673 | |
| 674 | @Override |
| 675 | public CompletableFuture<byte[]> sendAndReceive(InternalMessage message) { |
| 676 | CompletableFuture<byte[]> future = new CompletableFuture<>(); |
| 677 | BiConsumer<InternalMessage, ServerConnection> handler = handlers.get(message.type()); |
| 678 | if (handler != null) { |
| 679 | handler.accept(message, new LocalServerConnection(future)); |
| 680 | } else { |
| 681 | log.debug("No handler for message type {} from {}", message.type(), message.sender()); |
| 682 | new LocalServerConnection(future).reply(message, Status.ERROR_NO_HANDLER, Optional.empty()); |
| 683 | } |
| 684 | return future; |
| 685 | } |
| 686 | } |
| 687 | |
| 688 | /** |
| 689 | * Local server connection. |
| 690 | */ |
| 691 | private final class LocalServerConnection implements ServerConnection { |
| 692 | private final CompletableFuture<byte[]> future; |
| 693 | |
| 694 | LocalServerConnection(CompletableFuture<byte[]> future) { |
| 695 | this.future = future; |
| 696 | } |
| 697 | |
| 698 | @Override |
| 699 | public void reply(InternalMessage message, Status status, Optional<byte[]> payload) { |
| 700 | if (future != null) { |
| 701 | if (status == Status.OK) { |
| 702 | future.complete(payload.orElse(EMPTY_PAYLOAD)); |
| 703 | } else if (status == Status.ERROR_NO_HANDLER) { |
| 704 | future.completeExceptionally(new MessagingException.NoRemoteHandler()); |
| 705 | } else if (status == Status.ERROR_HANDLER_EXCEPTION) { |
| 706 | future.completeExceptionally(new MessagingException.RemoteHandlerFailure()); |
| 707 | } else if (status == Status.PROTOCOL_EXCEPTION) { |
| 708 | future.completeExceptionally(new MessagingException.ProtocolException()); |
| 709 | } |
| 710 | } |
| 711 | } |
| 712 | } |
| 713 | |
| 714 | /** |
| 715 | * Remote connection implementation. |
| 716 | */ |
| 717 | private final class RemoteClientConnection implements ClientConnection { |
| 718 | private final Channel channel; |
| 719 | private final Map<Long, Callback> futures = Maps.newConcurrentMap(); |
| 720 | private final AtomicBoolean closed = new AtomicBoolean(false); |
| 721 | |
| 722 | RemoteClientConnection(Channel channel) { |
| 723 | this.channel = channel; |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 724 | } |
| 725 | |
| 726 | /** |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 727 | * Times out callbacks for this connection. |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 728 | */ |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 729 | private void timeoutCallbacks() { |
| 730 | // Store the current time. |
| 731 | long currentTime = System.currentTimeMillis(); |
| 732 | |
| 733 | // Iterate through future callbacks and time out callbacks that have been alive |
| 734 | // longer than the current timeout according to the message type. |
| 735 | Iterator<Map.Entry<Long, Callback>> iterator = futures.entrySet().iterator(); |
| 736 | while (iterator.hasNext()) { |
| 737 | Callback callback = iterator.next().getValue(); |
| 738 | try { |
| 739 | TimeoutHistory timeoutHistory = timeoutHistories.get(callback.type, TimeoutHistory::new); |
| 740 | long currentTimeout = timeoutHistory.currentTimeout; |
| 741 | if (currentTime - callback.time > currentTimeout) { |
| 742 | iterator.remove(); |
| 743 | long elapsedTime = currentTime - callback.time; |
| 744 | timeoutHistory.addReplyTime(elapsedTime); |
| 745 | callback.completeExceptionally( |
| 746 | new TimeoutException("Request timed out in " + elapsedTime + " milliseconds")); |
| 747 | } |
| 748 | } catch (ExecutionException e) { |
| 749 | throw new AssertionError(); |
| 750 | } |
| 751 | } |
| 752 | } |
| 753 | |
| 754 | @Override |
| 755 | public CompletableFuture<Void> sendAsync(InternalMessage message) { |
| 756 | CompletableFuture<Void> future = new CompletableFuture<>(); |
| 757 | channel.writeAndFlush(message).addListener(channelFuture -> { |
| 758 | if (!channelFuture.isSuccess()) { |
| 759 | future.completeExceptionally(channelFuture.cause()); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 760 | } else { |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 761 | future.complete(null); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 762 | } |
| 763 | }); |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 764 | return future; |
| 765 | } |
| 766 | |
| 767 | @Override |
| 768 | public CompletableFuture<byte[]> sendAndReceive(InternalMessage message) { |
| 769 | CompletableFuture<byte[]> future = new CompletableFuture<>(); |
| 770 | Callback callback = new Callback(message.type(), future); |
| 771 | futures.put(message.id(), callback); |
| 772 | channel.writeAndFlush(message).addListener(channelFuture -> { |
| 773 | if (!channelFuture.isSuccess()) { |
| 774 | futures.remove(message.id()); |
| 775 | callback.completeExceptionally(channelFuture.cause()); |
| 776 | } |
| 777 | }); |
| 778 | return future; |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 779 | } |
| 780 | |
| 781 | /** |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 782 | * Dispatches a message to a local handler. |
| 783 | * |
| 784 | * @param message the message to dispatch |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 785 | */ |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 786 | private void dispatch(InternalMessage message) { |
| 787 | if (message.preamble() != preamble) { |
| 788 | log.debug("Received {} with invalid preamble from {}", message.type(), message.sender()); |
| 789 | return; |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 790 | } |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 791 | |
| 792 | clockService.recordEventTime(message.time()); |
| 793 | |
| 794 | Callback callback = futures.remove(message.id()); |
| 795 | if (callback != null) { |
| 796 | if (message.status() == Status.OK) { |
| 797 | callback.complete(message.payload()); |
| 798 | } else if (message.status() == Status.ERROR_NO_HANDLER) { |
| 799 | callback.completeExceptionally(new MessagingException.NoRemoteHandler()); |
| 800 | } else if (message.status() == Status.ERROR_HANDLER_EXCEPTION) { |
| 801 | callback.completeExceptionally(new MessagingException.RemoteHandlerFailure()); |
| 802 | } else if (message.status() == Status.PROTOCOL_EXCEPTION) { |
| 803 | callback.completeExceptionally(new MessagingException.ProtocolException()); |
| 804 | } |
| 805 | |
| 806 | try { |
| 807 | TimeoutHistory timeoutHistory = timeoutHistories.get(callback.type, TimeoutHistory::new); |
| 808 | timeoutHistory.addReplyTime(System.currentTimeMillis() - callback.time); |
| 809 | } catch (ExecutionException e) { |
| 810 | throw new AssertionError(); |
| 811 | } |
| 812 | } else { |
| 813 | log.debug("Received a reply for message id:[{}]. " |
| 814 | + " from {}. But was unable to locate the" |
| 815 | + " request handle", message.id(), message.sender()); |
| 816 | } |
| 817 | } |
| 818 | |
| 819 | @Override |
| 820 | public void close() { |
| 821 | if (closed.compareAndSet(false, true)) { |
| 822 | timeoutFuture.cancel(false); |
| 823 | for (Callback callback : futures.values()) { |
| 824 | callback.completeExceptionally(new ConnectException()); |
| 825 | } |
| 826 | } |
| 827 | } |
| 828 | } |
| 829 | |
| 830 | /** |
| 831 | * Remote server connection. |
| 832 | */ |
| 833 | private final class RemoteServerConnection implements ServerConnection { |
| 834 | private final Channel channel; |
| 835 | |
| 836 | RemoteServerConnection(Channel channel) { |
| 837 | this.channel = channel; |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 838 | } |
| 839 | |
| 840 | /** |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 841 | * Dispatches a message to a local handler. |
| 842 | * |
| 843 | * @param message the message to dispatch |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 844 | */ |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 845 | private void dispatch(InternalMessage message) { |
| 846 | if (message.preamble() != preamble) { |
| 847 | log.debug("Received {} with invalid preamble from {}", message.type(), message.sender()); |
| 848 | reply(message, Status.PROTOCOL_EXCEPTION, Optional.empty()); |
| 849 | return; |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 850 | } |
Jordan Halterman | f7c7f6f | 2017-05-05 03:02:34 -0700 | [diff] [blame] | 851 | |
| 852 | clockService.recordEventTime(message.time()); |
| 853 | |
| 854 | BiConsumer<InternalMessage, ServerConnection> handler = handlers.get(message.type()); |
| 855 | if (handler != null) { |
| 856 | handler.accept(message, this); |
| 857 | } else { |
| 858 | log.debug("No handler for message type {} from {}", message.type(), message.sender()); |
| 859 | reply(message, Status.ERROR_NO_HANDLER, Optional.empty()); |
| 860 | } |
| 861 | } |
| 862 | |
| 863 | @Override |
| 864 | public void reply(InternalMessage message, Status status, Optional<byte[]> payload) { |
| 865 | InternalMessage response = new InternalMessage(preamble, |
| 866 | clockService.timeNow(), |
| 867 | message.id(), |
| 868 | localEndpoint, |
| 869 | payload.orElse(EMPTY_PAYLOAD), |
| 870 | status); |
| 871 | channel.writeAndFlush(response); |
| 872 | } |
| 873 | } |
| 874 | |
| 875 | /** |
| 876 | * Request-reply timeout history tracker. |
| 877 | */ |
| 878 | private static final class TimeoutHistory { |
| 879 | private final DescriptiveStatistics timeoutHistory = new SynchronizedDescriptiveStatistics(WINDOW_SIZE); |
| 880 | private final AtomicLong maxReplyTime = new AtomicLong(); |
| 881 | private volatile long currentTimeout = DEFAULT_TIMEOUT_MILLIS; |
| 882 | |
| 883 | /** |
| 884 | * Adds a reply time to the history. |
| 885 | * |
| 886 | * @param replyTime the reply time to add to the history |
| 887 | */ |
| 888 | void addReplyTime(long replyTime) { |
| 889 | maxReplyTime.getAndAccumulate(replyTime, Math::max); |
| 890 | } |
| 891 | |
| 892 | /** |
| 893 | * Computes the current timeout. |
| 894 | */ |
| 895 | private void recomputeTimeoutMillis() { |
| 896 | double nextTimeout = maxReplyTime.getAndSet(0) * TIMEOUT_MULTIPLIER; |
| 897 | timeoutHistory.addValue( |
| 898 | Math.min(Math.max(nextTimeout, MIN_TIMEOUT_MILLIS), MAX_TIMEOUT_MILLIS)); |
| 899 | if (timeoutHistory.getN() == WINDOW_SIZE) { |
| 900 | this.currentTimeout = (long) timeoutHistory.getMax(); |
| 901 | } |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 902 | } |
| 903 | } |
JunHuy Lam | 39eb429 | 2015-06-26 17:24:23 +0900 | [diff] [blame] | 904 | } |