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; |
| 21 | import com.google.common.cache.RemovalListener; |
| 22 | import com.google.common.cache.RemovalNotification; |
| 23 | import com.google.common.util.concurrent.MoreExecutors; |
Madan Jampani | a9e70a6 | 2016-03-02 16:28:18 -0800 | [diff] [blame] | 24 | |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 25 | import io.netty.bootstrap.Bootstrap; |
| 26 | import io.netty.bootstrap.ServerBootstrap; |
| 27 | import io.netty.buffer.PooledByteBufAllocator; |
| 28 | import io.netty.channel.Channel; |
| 29 | import io.netty.channel.ChannelFuture; |
| 30 | import io.netty.channel.ChannelHandler; |
| 31 | import io.netty.channel.ChannelHandlerContext; |
| 32 | import io.netty.channel.ChannelInitializer; |
| 33 | import io.netty.channel.ChannelOption; |
| 34 | import io.netty.channel.EventLoopGroup; |
| 35 | import io.netty.channel.ServerChannel; |
| 36 | import io.netty.channel.SimpleChannelInboundHandler; |
| 37 | import io.netty.channel.epoll.EpollEventLoopGroup; |
| 38 | import io.netty.channel.epoll.EpollServerSocketChannel; |
| 39 | import io.netty.channel.epoll.EpollSocketChannel; |
| 40 | import io.netty.channel.nio.NioEventLoopGroup; |
| 41 | import io.netty.channel.socket.SocketChannel; |
| 42 | import io.netty.channel.socket.nio.NioServerSocketChannel; |
| 43 | import io.netty.channel.socket.nio.NioSocketChannel; |
Madan Jampani | a9e70a6 | 2016-03-02 16:28:18 -0800 | [diff] [blame] | 44 | |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 45 | import org.apache.commons.pool.KeyedPoolableObjectFactory; |
| 46 | import org.apache.commons.pool.impl.GenericKeyedObjectPool; |
Madan Jampani | afeebbd | 2015-05-19 15:26:01 -0700 | [diff] [blame] | 47 | import org.apache.felix.scr.annotations.Activate; |
| 48 | import org.apache.felix.scr.annotations.Component; |
| 49 | import org.apache.felix.scr.annotations.Deactivate; |
| 50 | import org.apache.felix.scr.annotations.Reference; |
| 51 | import org.apache.felix.scr.annotations.ReferenceCardinality; |
| 52 | import org.apache.felix.scr.annotations.Service; |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 53 | import org.onlab.util.Tools; |
Madan Jampani | ec1df02 | 2015-10-13 21:23:03 -0700 | [diff] [blame] | 54 | import org.onosproject.cluster.ClusterMetadataService; |
Madan Jampani | afeebbd | 2015-05-19 15:26:01 -0700 | [diff] [blame] | 55 | import org.onosproject.cluster.ControllerNode; |
Madan Jampani | 0583387 | 2016-07-12 23:01:39 -0700 | [diff] [blame] | 56 | import org.onosproject.core.HybridLogicalClockService; |
Madan Jampani | afeebbd | 2015-05-19 15:26:01 -0700 | [diff] [blame] | 57 | import org.onosproject.store.cluster.messaging.Endpoint; |
Madan Jampani | a9e70a6 | 2016-03-02 16:28:18 -0800 | [diff] [blame] | 58 | import org.onosproject.store.cluster.messaging.MessagingException; |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 59 | import org.onosproject.store.cluster.messaging.MessagingService; |
Madan Jampani | a9e70a6 | 2016-03-02 16:28:18 -0800 | [diff] [blame] | 60 | import org.onosproject.store.cluster.messaging.impl.InternalMessage.Status; |
Madan Jampani | afeebbd | 2015-05-19 15:26:01 -0700 | [diff] [blame] | 61 | import org.slf4j.Logger; |
| 62 | import org.slf4j.LoggerFactory; |
| 63 | |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 64 | import javax.net.ssl.KeyManagerFactory; |
| 65 | import javax.net.ssl.SSLContext; |
| 66 | import javax.net.ssl.SSLEngine; |
| 67 | import javax.net.ssl.TrustManagerFactory; |
Madan Jampani | a9e70a6 | 2016-03-02 16:28:18 -0800 | [diff] [blame] | 68 | |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 69 | import java.io.FileInputStream; |
| 70 | import java.io.IOException; |
| 71 | import java.security.KeyStore; |
| 72 | import java.util.Map; |
Madan Jampani | a9e70a6 | 2016-03-02 16:28:18 -0800 | [diff] [blame] | 73 | import java.util.Optional; |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 74 | import java.util.concurrent.CompletableFuture; |
| 75 | import java.util.concurrent.ConcurrentHashMap; |
| 76 | import java.util.concurrent.Executor; |
| 77 | import java.util.concurrent.RejectedExecutionException; |
| 78 | import java.util.concurrent.TimeUnit; |
| 79 | import java.util.concurrent.TimeoutException; |
| 80 | import java.util.concurrent.atomic.AtomicBoolean; |
| 81 | import java.util.concurrent.atomic.AtomicLong; |
| 82 | import java.util.function.BiConsumer; |
| 83 | import java.util.function.BiFunction; |
| 84 | import java.util.function.Consumer; |
| 85 | |
Yuta HIGUCHI | 90a1689 | 2016-07-20 20:36:08 -0700 | [diff] [blame] | 86 | import static org.onlab.util.Tools.groupedThreads; |
Heedo Kang | 4a47a30 | 2016-02-29 17:40:23 +0900 | [diff] [blame] | 87 | import static org.onosproject.security.AppGuard.checkPermission; |
| 88 | import static org.onosproject.security.AppPermission.Type.CLUSTER_WRITE; |
| 89 | |
Madan Jampani | afeebbd | 2015-05-19 15:26:01 -0700 | [diff] [blame] | 90 | /** |
| 91 | * Netty based MessagingService. |
| 92 | */ |
Sho SHIMIZU | 5c396e3 | 2016-08-12 15:19:12 -0700 | [diff] [blame^] | 93 | @Component(immediate = true) |
Madan Jampani | afeebbd | 2015-05-19 15:26:01 -0700 | [diff] [blame] | 94 | @Service |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 95 | public class NettyMessagingManager implements MessagingService { |
| 96 | |
Madan Jampani | f3ab424 | 2016-07-27 17:21:47 -0700 | [diff] [blame] | 97 | private static final int REPLY_TIME_OUT_MILLIS = 250; |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 98 | private static final short MIN_KS_LENGTH = 6; |
Madan Jampani | afeebbd | 2015-05-19 15:26:01 -0700 | [diff] [blame] | 99 | |
| 100 | private final Logger log = LoggerFactory.getLogger(getClass()); |
| 101 | |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 102 | private static final String REPLY_MESSAGE_TYPE = "NETTY_MESSAGING_REQUEST_REPLY"; |
| 103 | |
Madan Jampani | 0583387 | 2016-07-12 23:01:39 -0700 | [diff] [blame] | 104 | @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) |
| 105 | protected HybridLogicalClockService clockService; |
| 106 | |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 107 | private Endpoint localEp; |
| 108 | private int preamble; |
| 109 | private final AtomicBoolean started = new AtomicBoolean(false); |
| 110 | private final Map<String, Consumer<InternalMessage>> handlers = new ConcurrentHashMap<>(); |
| 111 | private final AtomicLong messageIdGenerator = new AtomicLong(0); |
| 112 | private final Cache<Long, Callback> callbacks = CacheBuilder.newBuilder() |
Madan Jampani | f3ab424 | 2016-07-27 17:21:47 -0700 | [diff] [blame] | 113 | .expireAfterWrite(REPLY_TIME_OUT_MILLIS, TimeUnit.MILLISECONDS) |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 114 | .removalListener(new RemovalListener<Long, Callback>() { |
| 115 | @Override |
| 116 | public void onRemoval(RemovalNotification<Long, Callback> entry) { |
| 117 | if (entry.wasEvicted()) { |
| 118 | entry.getValue().completeExceptionally(new TimeoutException("Timedout waiting for reply")); |
| 119 | } |
| 120 | } |
| 121 | }) |
| 122 | .build(); |
| 123 | |
| 124 | private final GenericKeyedObjectPool<Endpoint, Connection> channels |
Yuta HIGUCHI | 90a1689 | 2016-07-20 20:36:08 -0700 | [diff] [blame] | 125 | = new GenericKeyedObjectPool<>(new OnosCommunicationChannelFactory()); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 126 | |
| 127 | private EventLoopGroup serverGroup; |
| 128 | private EventLoopGroup clientGroup; |
| 129 | private Class<? extends ServerChannel> serverChannelClass; |
| 130 | private Class<? extends Channel> clientChannelClass; |
| 131 | |
| 132 | protected static final boolean TLS_DISABLED = false; |
| 133 | protected boolean enableNettyTls = TLS_DISABLED; |
| 134 | |
| 135 | protected String ksLocation; |
| 136 | protected String tsLocation; |
| 137 | protected char[] ksPwd; |
| 138 | protected char[] tsPwd; |
JunHuy Lam | 39eb429 | 2015-06-26 17:24:23 +0900 | [diff] [blame] | 139 | |
Madan Jampani | afeebbd | 2015-05-19 15:26:01 -0700 | [diff] [blame] | 140 | @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) |
Madan Jampani | ec1df02 | 2015-10-13 21:23:03 -0700 | [diff] [blame] | 141 | protected ClusterMetadataService clusterMetadataService; |
Madan Jampani | afeebbd | 2015-05-19 15:26:01 -0700 | [diff] [blame] | 142 | |
| 143 | @Activate |
| 144 | public void activate() throws Exception { |
Madan Jampani | ec1df02 | 2015-10-13 21:23:03 -0700 | [diff] [blame] | 145 | ControllerNode localNode = clusterMetadataService.getLocalNode(); |
Jonathan Hart | d9df7bd | 2015-11-10 17:10:25 -0800 | [diff] [blame] | 146 | getTlsParameters(); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 147 | |
| 148 | if (started.get()) { |
| 149 | log.warn("Already running at local endpoint: {}", localEp); |
| 150 | return; |
| 151 | } |
| 152 | this.preamble = clusterMetadataService.getClusterMetadata().getName().hashCode(); |
| 153 | this.localEp = new Endpoint(localNode.ip(), localNode.tcpPort()); |
| 154 | channels.setLifo(true); |
| 155 | channels.setTestOnBorrow(true); |
| 156 | channels.setTestOnReturn(true); |
| 157 | channels.setMinEvictableIdleTimeMillis(60_000L); |
| 158 | channels.setTimeBetweenEvictionRunsMillis(30_000L); |
| 159 | initEventLoopGroup(); |
| 160 | startAcceptingConnections(); |
| 161 | started.set(true); |
Madan Jampani | f3ab424 | 2016-07-27 17:21:47 -0700 | [diff] [blame] | 162 | serverGroup.scheduleWithFixedDelay(callbacks::cleanUp, 0, REPLY_TIME_OUT_MILLIS, TimeUnit.MILLISECONDS); |
Madan Jampani | afeebbd | 2015-05-19 15:26:01 -0700 | [diff] [blame] | 163 | log.info("Started"); |
| 164 | } |
| 165 | |
| 166 | @Deactivate |
| 167 | public void deactivate() throws Exception { |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 168 | if (started.get()) { |
| 169 | channels.close(); |
| 170 | serverGroup.shutdownGracefully(); |
| 171 | clientGroup.shutdownGracefully(); |
| 172 | started.set(false); |
| 173 | } |
Madan Jampani | afeebbd | 2015-05-19 15:26:01 -0700 | [diff] [blame] | 174 | log.info("Stopped"); |
| 175 | } |
JunHuy Lam | 39eb429 | 2015-06-26 17:24:23 +0900 | [diff] [blame] | 176 | |
Jonathan Hart | d9df7bd | 2015-11-10 17:10:25 -0800 | [diff] [blame] | 177 | private void getTlsParameters() { |
JunHuy Lam | 39eb429 | 2015-06-26 17:24:23 +0900 | [diff] [blame] | 178 | String tempString = System.getProperty("enableNettyTLS"); |
Jonathan Hart | d9df7bd | 2015-11-10 17:10:25 -0800 | [diff] [blame] | 179 | enableNettyTls = Strings.isNullOrEmpty(tempString) ? TLS_DISABLED : Boolean.parseBoolean(tempString); |
| 180 | log.info("enableNettyTLS = {}", enableNettyTls); |
| 181 | if (enableNettyTls) { |
JunHuy Lam | 39eb429 | 2015-06-26 17:24:23 +0900 | [diff] [blame] | 182 | ksLocation = System.getProperty("javax.net.ssl.keyStore"); |
| 183 | if (Strings.isNullOrEmpty(ksLocation)) { |
Jonathan Hart | d9df7bd | 2015-11-10 17:10:25 -0800 | [diff] [blame] | 184 | enableNettyTls = TLS_DISABLED; |
JunHuy Lam | 39eb429 | 2015-06-26 17:24:23 +0900 | [diff] [blame] | 185 | return; |
| 186 | } |
| 187 | tsLocation = System.getProperty("javax.net.ssl.trustStore"); |
| 188 | if (Strings.isNullOrEmpty(tsLocation)) { |
Jonathan Hart | d9df7bd | 2015-11-10 17:10:25 -0800 | [diff] [blame] | 189 | enableNettyTls = TLS_DISABLED; |
JunHuy Lam | 39eb429 | 2015-06-26 17:24:23 +0900 | [diff] [blame] | 190 | return; |
| 191 | } |
| 192 | ksPwd = System.getProperty("javax.net.ssl.keyStorePassword").toCharArray(); |
| 193 | if (MIN_KS_LENGTH > ksPwd.length) { |
Jonathan Hart | d9df7bd | 2015-11-10 17:10:25 -0800 | [diff] [blame] | 194 | enableNettyTls = TLS_DISABLED; |
JunHuy Lam | 39eb429 | 2015-06-26 17:24:23 +0900 | [diff] [blame] | 195 | return; |
| 196 | } |
| 197 | tsPwd = System.getProperty("javax.net.ssl.trustStorePassword").toCharArray(); |
| 198 | if (MIN_KS_LENGTH > tsPwd.length) { |
Jonathan Hart | d9df7bd | 2015-11-10 17:10:25 -0800 | [diff] [blame] | 199 | enableNettyTls = TLS_DISABLED; |
JunHuy Lam | 39eb429 | 2015-06-26 17:24:23 +0900 | [diff] [blame] | 200 | return; |
| 201 | } |
| 202 | } |
| 203 | } |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 204 | private void initEventLoopGroup() { |
| 205 | // try Epoll first and if that does work, use nio. |
| 206 | try { |
Yuta HIGUCHI | 90a1689 | 2016-07-20 20:36:08 -0700 | [diff] [blame] | 207 | clientGroup = new EpollEventLoopGroup(0, groupedThreads("NettyMessagingEvt", "epollC-%d", log)); |
| 208 | serverGroup = new EpollEventLoopGroup(0, groupedThreads("NettyMessagingEvt", "epollS-%d", log)); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 209 | serverChannelClass = EpollServerSocketChannel.class; |
| 210 | clientChannelClass = EpollSocketChannel.class; |
| 211 | return; |
| 212 | } catch (Throwable e) { |
| 213 | log.debug("Failed to initialize native (epoll) transport. " |
| 214 | + "Reason: {}. Proceeding with nio.", e.getMessage()); |
| 215 | } |
Yuta HIGUCHI | 90a1689 | 2016-07-20 20:36:08 -0700 | [diff] [blame] | 216 | clientGroup = new NioEventLoopGroup(0, groupedThreads("NettyMessagingEvt", "nioC-%d", log)); |
| 217 | serverGroup = new NioEventLoopGroup(0, groupedThreads("NettyMessagingEvt", "nioS-%d", log)); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 218 | serverChannelClass = NioServerSocketChannel.class; |
| 219 | clientChannelClass = NioSocketChannel.class; |
| 220 | } |
| 221 | |
| 222 | @Override |
| 223 | public CompletableFuture<Void> sendAsync(Endpoint ep, String type, byte[] payload) { |
Heedo Kang | 4a47a30 | 2016-02-29 17:40:23 +0900 | [diff] [blame] | 224 | checkPermission(CLUSTER_WRITE); |
Madan Jampani | b825aeb | 2016-04-01 15:18:25 -0700 | [diff] [blame] | 225 | InternalMessage message = new InternalMessage(preamble, |
Madan Jampani | 0583387 | 2016-07-12 23:01:39 -0700 | [diff] [blame] | 226 | clockService.timeNow(), |
Madan Jampani | b825aeb | 2016-04-01 15:18:25 -0700 | [diff] [blame] | 227 | messageIdGenerator.incrementAndGet(), |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 228 | localEp, |
| 229 | type, |
| 230 | payload); |
| 231 | return sendAsync(ep, message); |
| 232 | } |
| 233 | |
| 234 | protected CompletableFuture<Void> sendAsync(Endpoint ep, InternalMessage message) { |
Heedo Kang | 4a47a30 | 2016-02-29 17:40:23 +0900 | [diff] [blame] | 235 | checkPermission(CLUSTER_WRITE); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 236 | if (ep.equals(localEp)) { |
| 237 | try { |
| 238 | dispatchLocally(message); |
| 239 | } catch (IOException e) { |
| 240 | return Tools.exceptionalFuture(e); |
| 241 | } |
| 242 | return CompletableFuture.completedFuture(null); |
| 243 | } |
| 244 | |
| 245 | CompletableFuture<Void> future = new CompletableFuture<>(); |
| 246 | try { |
| 247 | Connection connection = null; |
| 248 | try { |
| 249 | connection = channels.borrowObject(ep); |
| 250 | connection.send(message, future); |
| 251 | } finally { |
| 252 | channels.returnObject(ep, connection); |
| 253 | } |
| 254 | } catch (Exception e) { |
| 255 | future.completeExceptionally(e); |
| 256 | } |
| 257 | return future; |
| 258 | } |
| 259 | |
| 260 | @Override |
| 261 | public CompletableFuture<byte[]> sendAndReceive(Endpoint ep, String type, byte[] payload) { |
Heedo Kang | 4a47a30 | 2016-02-29 17:40:23 +0900 | [diff] [blame] | 262 | checkPermission(CLUSTER_WRITE); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 263 | return sendAndReceive(ep, type, payload, MoreExecutors.directExecutor()); |
| 264 | } |
| 265 | |
| 266 | @Override |
| 267 | public CompletableFuture<byte[]> sendAndReceive(Endpoint ep, String type, byte[] payload, Executor executor) { |
Heedo Kang | 4a47a30 | 2016-02-29 17:40:23 +0900 | [diff] [blame] | 268 | checkPermission(CLUSTER_WRITE); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 269 | CompletableFuture<byte[]> response = new CompletableFuture<>(); |
| 270 | Callback callback = new Callback(response, executor); |
| 271 | Long messageId = messageIdGenerator.incrementAndGet(); |
| 272 | callbacks.put(messageId, callback); |
Madan Jampani | 0583387 | 2016-07-12 23:01:39 -0700 | [diff] [blame] | 273 | InternalMessage message = new InternalMessage(preamble, |
| 274 | clockService.timeNow(), |
| 275 | messageId, |
| 276 | localEp, |
| 277 | type, |
| 278 | payload); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 279 | return sendAsync(ep, message).whenComplete((r, e) -> { |
| 280 | if (e != null) { |
| 281 | callbacks.invalidate(messageId); |
| 282 | } |
Yuta HIGUCHI | ed1ca66 | 2016-08-11 11:11:37 -0700 | [diff] [blame] | 283 | }).thenComposeAsync(v -> response, executor); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 284 | } |
| 285 | |
| 286 | @Override |
| 287 | public void registerHandler(String type, BiConsumer<Endpoint, byte[]> handler, Executor executor) { |
Heedo Kang | 4a47a30 | 2016-02-29 17:40:23 +0900 | [diff] [blame] | 288 | checkPermission(CLUSTER_WRITE); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 289 | handlers.put(type, message -> executor.execute(() -> handler.accept(message.sender(), message.payload()))); |
| 290 | } |
| 291 | |
| 292 | @Override |
| 293 | public void registerHandler(String type, BiFunction<Endpoint, byte[], byte[]> handler, Executor executor) { |
Heedo Kang | 4a47a30 | 2016-02-29 17:40:23 +0900 | [diff] [blame] | 294 | checkPermission(CLUSTER_WRITE); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 295 | handlers.put(type, message -> executor.execute(() -> { |
Madan Jampani | a9e70a6 | 2016-03-02 16:28:18 -0800 | [diff] [blame] | 296 | byte[] responsePayload = null; |
| 297 | Status status = Status.OK; |
| 298 | try { |
| 299 | responsePayload = handler.apply(message.sender(), message.payload()); |
| 300 | } catch (Exception e) { |
| 301 | status = Status.ERROR_HANDLER_EXCEPTION; |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 302 | } |
Madan Jampani | a9e70a6 | 2016-03-02 16:28:18 -0800 | [diff] [blame] | 303 | sendReply(message, status, Optional.ofNullable(responsePayload)); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 304 | })); |
| 305 | } |
| 306 | |
| 307 | @Override |
| 308 | public void registerHandler(String type, BiFunction<Endpoint, byte[], CompletableFuture<byte[]>> handler) { |
Heedo Kang | 4a47a30 | 2016-02-29 17:40:23 +0900 | [diff] [blame] | 309 | checkPermission(CLUSTER_WRITE); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 310 | handlers.put(type, message -> { |
| 311 | handler.apply(message.sender(), message.payload()).whenComplete((result, error) -> { |
Madan Jampani | a9e70a6 | 2016-03-02 16:28:18 -0800 | [diff] [blame] | 312 | Status status = error == null ? Status.OK : Status.ERROR_HANDLER_EXCEPTION; |
| 313 | sendReply(message, status, Optional.ofNullable(result)); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 314 | }); |
| 315 | }); |
| 316 | } |
| 317 | |
| 318 | @Override |
| 319 | public void unregisterHandler(String type) { |
Heedo Kang | 4a47a30 | 2016-02-29 17:40:23 +0900 | [diff] [blame] | 320 | checkPermission(CLUSTER_WRITE); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 321 | handlers.remove(type); |
| 322 | } |
| 323 | |
| 324 | private void startAcceptingConnections() throws InterruptedException { |
| 325 | ServerBootstrap b = new ServerBootstrap(); |
| 326 | b.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 32 * 1024); |
| 327 | b.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024); |
| 328 | b.option(ChannelOption.SO_RCVBUF, 1048576); |
| 329 | b.option(ChannelOption.TCP_NODELAY, true); |
| 330 | b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); |
| 331 | b.group(serverGroup, clientGroup); |
| 332 | b.channel(serverChannelClass); |
| 333 | if (enableNettyTls) { |
| 334 | b.childHandler(new SslServerCommunicationChannelInitializer()); |
| 335 | } else { |
| 336 | b.childHandler(new OnosCommunicationChannelInitializer()); |
| 337 | } |
| 338 | b.option(ChannelOption.SO_BACKLOG, 128); |
| 339 | b.childOption(ChannelOption.SO_KEEPALIVE, true); |
| 340 | |
| 341 | // Bind and start to accept incoming connections. |
| 342 | b.bind(localEp.port()).sync().addListener(future -> { |
| 343 | if (future.isSuccess()) { |
| 344 | log.info("{} accepting incoming connections on port {}", localEp.host(), localEp.port()); |
| 345 | } else { |
| 346 | log.warn("{} failed to bind to port {}", localEp.host(), localEp.port(), future.cause()); |
| 347 | } |
| 348 | }); |
| 349 | } |
| 350 | |
| 351 | private class OnosCommunicationChannelFactory |
| 352 | implements KeyedPoolableObjectFactory<Endpoint, Connection> { |
| 353 | |
| 354 | @Override |
| 355 | public void activateObject(Endpoint endpoint, Connection connection) |
| 356 | throws Exception { |
| 357 | } |
| 358 | |
| 359 | @Override |
| 360 | public void destroyObject(Endpoint ep, Connection connection) throws Exception { |
| 361 | log.debug("Closing connection to {}", ep); |
| 362 | //Is this the right way to destroy? |
| 363 | connection.destroy(); |
| 364 | } |
| 365 | |
| 366 | @Override |
| 367 | public Connection makeObject(Endpoint ep) throws Exception { |
| 368 | Bootstrap bootstrap = new Bootstrap(); |
| 369 | bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); |
| 370 | bootstrap.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 10 * 64 * 1024); |
| 371 | bootstrap.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 10 * 32 * 1024); |
| 372 | bootstrap.option(ChannelOption.SO_SNDBUF, 1048576); |
| 373 | bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000); |
| 374 | bootstrap.group(clientGroup); |
| 375 | // TODO: Make this faster: |
| 376 | // http://normanmaurer.me/presentations/2014-facebook-eng-netty/slides.html#37.0 |
| 377 | bootstrap.channel(clientChannelClass); |
| 378 | bootstrap.option(ChannelOption.SO_KEEPALIVE, true); |
| 379 | if (enableNettyTls) { |
| 380 | bootstrap.handler(new SslClientCommunicationChannelInitializer()); |
| 381 | } else { |
| 382 | bootstrap.handler(new OnosCommunicationChannelInitializer()); |
| 383 | } |
| 384 | // Start the client. |
| 385 | CompletableFuture<Channel> retFuture = new CompletableFuture<>(); |
| 386 | ChannelFuture f = bootstrap.connect(ep.host().toString(), ep.port()); |
| 387 | |
| 388 | f.addListener(future -> { |
| 389 | if (future.isSuccess()) { |
| 390 | retFuture.complete(f.channel()); |
| 391 | } else { |
| 392 | retFuture.completeExceptionally(future.cause()); |
| 393 | } |
| 394 | }); |
| 395 | log.debug("Established a new connection to {}", ep); |
| 396 | return new Connection(retFuture); |
| 397 | } |
| 398 | |
| 399 | @Override |
| 400 | public void passivateObject(Endpoint ep, Connection connection) |
| 401 | throws Exception { |
| 402 | } |
| 403 | |
| 404 | @Override |
| 405 | public boolean validateObject(Endpoint ep, Connection connection) { |
| 406 | return connection.validate(); |
| 407 | } |
| 408 | } |
| 409 | |
| 410 | private class SslServerCommunicationChannelInitializer extends ChannelInitializer<SocketChannel> { |
| 411 | |
| 412 | private final ChannelHandler dispatcher = new InboundMessageDispatcher(); |
| 413 | private final ChannelHandler encoder = new MessageEncoder(preamble); |
| 414 | |
| 415 | @Override |
| 416 | protected void initChannel(SocketChannel channel) throws Exception { |
| 417 | TrustManagerFactory tmFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); |
| 418 | KeyStore ts = KeyStore.getInstance("JKS"); |
| 419 | ts.load(new FileInputStream(tsLocation), tsPwd); |
| 420 | tmFactory.init(ts); |
| 421 | |
| 422 | KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); |
| 423 | KeyStore ks = KeyStore.getInstance("JKS"); |
| 424 | ks.load(new FileInputStream(ksLocation), ksPwd); |
| 425 | kmf.init(ks, ksPwd); |
| 426 | |
| 427 | SSLContext serverContext = SSLContext.getInstance("TLS"); |
| 428 | serverContext.init(kmf.getKeyManagers(), tmFactory.getTrustManagers(), null); |
| 429 | |
| 430 | SSLEngine serverSslEngine = serverContext.createSSLEngine(); |
| 431 | |
| 432 | serverSslEngine.setNeedClientAuth(true); |
| 433 | serverSslEngine.setUseClientMode(false); |
| 434 | serverSslEngine.setEnabledProtocols(serverSslEngine.getSupportedProtocols()); |
| 435 | serverSslEngine.setEnabledCipherSuites(serverSslEngine.getSupportedCipherSuites()); |
| 436 | serverSslEngine.setEnableSessionCreation(true); |
| 437 | |
| 438 | channel.pipeline().addLast("ssl", new io.netty.handler.ssl.SslHandler(serverSslEngine)) |
| 439 | .addLast("encoder", encoder) |
Madan Jampani | b825aeb | 2016-04-01 15:18:25 -0700 | [diff] [blame] | 440 | .addLast("decoder", new MessageDecoder()) |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 441 | .addLast("handler", dispatcher); |
| 442 | } |
| 443 | } |
| 444 | |
| 445 | private class SslClientCommunicationChannelInitializer extends ChannelInitializer<SocketChannel> { |
| 446 | |
| 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 clientContext = SSLContext.getInstance("TLS"); |
| 463 | clientContext.init(kmf.getKeyManagers(), tmFactory.getTrustManagers(), null); |
| 464 | |
| 465 | SSLEngine clientSslEngine = clientContext.createSSLEngine(); |
| 466 | |
| 467 | clientSslEngine.setUseClientMode(true); |
| 468 | clientSslEngine.setEnabledProtocols(clientSslEngine.getSupportedProtocols()); |
| 469 | clientSslEngine.setEnabledCipherSuites(clientSslEngine.getSupportedCipherSuites()); |
| 470 | clientSslEngine.setEnableSessionCreation(true); |
| 471 | |
| 472 | channel.pipeline().addLast("ssl", new io.netty.handler.ssl.SslHandler(clientSslEngine)) |
| 473 | .addLast("encoder", encoder) |
Madan Jampani | b825aeb | 2016-04-01 15:18:25 -0700 | [diff] [blame] | 474 | .addLast("decoder", new MessageDecoder()) |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 475 | .addLast("handler", dispatcher); |
| 476 | } |
| 477 | } |
| 478 | |
| 479 | private class OnosCommunicationChannelInitializer extends ChannelInitializer<SocketChannel> { |
| 480 | |
| 481 | private final ChannelHandler dispatcher = new InboundMessageDispatcher(); |
| 482 | private final ChannelHandler encoder = new MessageEncoder(preamble); |
| 483 | |
| 484 | @Override |
| 485 | protected void initChannel(SocketChannel channel) throws Exception { |
| 486 | channel.pipeline() |
| 487 | .addLast("encoder", encoder) |
Madan Jampani | b825aeb | 2016-04-01 15:18:25 -0700 | [diff] [blame] | 488 | .addLast("decoder", new MessageDecoder()) |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 489 | .addLast("handler", dispatcher); |
| 490 | } |
| 491 | } |
| 492 | |
| 493 | @ChannelHandler.Sharable |
| 494 | private class InboundMessageDispatcher extends SimpleChannelInboundHandler<InternalMessage> { |
| 495 | |
| 496 | @Override |
| 497 | protected void channelRead0(ChannelHandlerContext ctx, InternalMessage message) throws Exception { |
| 498 | try { |
| 499 | dispatchLocally(message); |
| 500 | } catch (RejectedExecutionException e) { |
| 501 | log.warn("Unable to dispatch message due to {}", e.getMessage()); |
| 502 | } |
| 503 | } |
| 504 | |
| 505 | @Override |
| 506 | public void exceptionCaught(ChannelHandlerContext context, Throwable cause) { |
| 507 | log.error("Exception inside channel handling pipeline.", cause); |
| 508 | context.close(); |
| 509 | } |
| 510 | } |
| 511 | private void dispatchLocally(InternalMessage message) throws IOException { |
Madan Jampani | b825aeb | 2016-04-01 15:18:25 -0700 | [diff] [blame] | 512 | if (message.preamble() != preamble) { |
| 513 | log.debug("Received {} with invalid preamble from {}", message.type(), message.sender()); |
| 514 | sendReply(message, Status.PROTOCOL_EXCEPTION, Optional.empty()); |
| 515 | } |
Madan Jampani | 0583387 | 2016-07-12 23:01:39 -0700 | [diff] [blame] | 516 | clockService.recordEventTime(message.time()); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 517 | String type = message.type(); |
| 518 | if (REPLY_MESSAGE_TYPE.equals(type)) { |
| 519 | try { |
| 520 | Callback callback = |
| 521 | callbacks.getIfPresent(message.id()); |
| 522 | if (callback != null) { |
Madan Jampani | a9e70a6 | 2016-03-02 16:28:18 -0800 | [diff] [blame] | 523 | if (message.status() == Status.OK) { |
| 524 | callback.complete(message.payload()); |
| 525 | } else if (message.status() == Status.ERROR_NO_HANDLER) { |
| 526 | callback.completeExceptionally(new MessagingException.NoRemoteHandler()); |
| 527 | } else if (message.status() == Status.ERROR_HANDLER_EXCEPTION) { |
| 528 | callback.completeExceptionally(new MessagingException.RemoteHandlerFailure()); |
Madan Jampani | b825aeb | 2016-04-01 15:18:25 -0700 | [diff] [blame] | 529 | } else if (message.status() == Status.PROTOCOL_EXCEPTION) { |
| 530 | callback.completeExceptionally(new MessagingException.ProcotolException()); |
Madan Jampani | a9e70a6 | 2016-03-02 16:28:18 -0800 | [diff] [blame] | 531 | } |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 532 | } else { |
Madan Jampani | a9e70a6 | 2016-03-02 16:28:18 -0800 | [diff] [blame] | 533 | log.debug("Received a reply for message id:[{}]. " |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 534 | + " from {}. But was unable to locate the" |
| 535 | + " request handle", message.id(), message.sender()); |
| 536 | } |
| 537 | } finally { |
| 538 | callbacks.invalidate(message.id()); |
| 539 | } |
| 540 | return; |
| 541 | } |
| 542 | Consumer<InternalMessage> handler = handlers.get(type); |
| 543 | if (handler != null) { |
| 544 | handler.accept(message); |
| 545 | } else { |
Madan Jampani | a9e70a6 | 2016-03-02 16:28:18 -0800 | [diff] [blame] | 546 | log.debug("No handler for message type {}", message.type(), message.sender()); |
| 547 | sendReply(message, Status.ERROR_NO_HANDLER, Optional.empty()); |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 548 | } |
| 549 | } |
| 550 | |
Madan Jampani | a9e70a6 | 2016-03-02 16:28:18 -0800 | [diff] [blame] | 551 | private void sendReply(InternalMessage message, Status status, Optional<byte[]> responsePayload) { |
Madan Jampani | b825aeb | 2016-04-01 15:18:25 -0700 | [diff] [blame] | 552 | InternalMessage response = new InternalMessage(preamble, |
Madan Jampani | 0583387 | 2016-07-12 23:01:39 -0700 | [diff] [blame] | 553 | clockService.timeNow(), |
Madan Jampani | b825aeb | 2016-04-01 15:18:25 -0700 | [diff] [blame] | 554 | message.id(), |
Madan Jampani | a9e70a6 | 2016-03-02 16:28:18 -0800 | [diff] [blame] | 555 | localEp, |
| 556 | REPLY_MESSAGE_TYPE, |
| 557 | responsePayload.orElse(new byte[0]), |
| 558 | status); |
| 559 | sendAsync(message.sender(), response).whenComplete((result, error) -> { |
| 560 | if (error != null) { |
| 561 | log.debug("Failed to respond", error); |
| 562 | } |
| 563 | }); |
| 564 | } |
| 565 | |
Aaron Kruglikov | 1b72738 | 2016-02-09 16:17:47 -0800 | [diff] [blame] | 566 | private final class Callback { |
| 567 | private final CompletableFuture<byte[]> future; |
| 568 | private final Executor executor; |
| 569 | |
| 570 | public Callback(CompletableFuture<byte[]> future, Executor executor) { |
| 571 | this.future = future; |
| 572 | this.executor = executor; |
| 573 | } |
| 574 | |
| 575 | public void complete(byte[] value) { |
| 576 | executor.execute(() -> future.complete(value)); |
| 577 | } |
| 578 | |
| 579 | public void completeExceptionally(Throwable error) { |
| 580 | executor.execute(() -> future.completeExceptionally(error)); |
| 581 | } |
| 582 | } |
| 583 | private final class Connection { |
| 584 | private final CompletableFuture<Channel> internalFuture; |
| 585 | |
| 586 | public Connection(CompletableFuture<Channel> internalFuture) { |
| 587 | this.internalFuture = internalFuture; |
| 588 | } |
| 589 | |
| 590 | /** |
| 591 | * Sends a message out on its channel and associated the message with a |
| 592 | * completable future used for signaling. |
| 593 | * @param message the message to be sent |
| 594 | * @param future a future that is completed normally or exceptionally if |
| 595 | * message sending succeeds or fails respectively |
| 596 | */ |
| 597 | public void send(Object message, CompletableFuture<Void> future) { |
| 598 | internalFuture.whenComplete((channel, throwable) -> { |
| 599 | if (throwable == null) { |
| 600 | channel.writeAndFlush(message).addListener(channelFuture -> { |
| 601 | if (!channelFuture.isSuccess()) { |
| 602 | future.completeExceptionally(channelFuture.cause()); |
| 603 | } else { |
| 604 | future.complete(null); |
| 605 | } |
| 606 | }); |
| 607 | } else { |
| 608 | future.completeExceptionally(throwable); |
| 609 | } |
| 610 | }); |
| 611 | } |
| 612 | |
| 613 | /** |
| 614 | * Destroys a channel by closing its channel (if it exists) and |
| 615 | * cancelling its future. |
| 616 | */ |
| 617 | public void destroy() { |
| 618 | Channel channel = internalFuture.getNow(null); |
| 619 | if (channel != null) { |
| 620 | channel.close(); |
| 621 | } |
| 622 | internalFuture.cancel(false); |
| 623 | } |
| 624 | |
| 625 | /** |
| 626 | * Determines whether the connection is valid meaning it is either |
| 627 | * complete with and active channel |
| 628 | * or it has not yet completed. |
| 629 | * @return true if the channel has an active connection or has not |
| 630 | * yet completed |
| 631 | */ |
| 632 | public boolean validate() { |
| 633 | if (internalFuture.isCompletedExceptionally()) { |
| 634 | return false; |
| 635 | } |
| 636 | Channel channel = internalFuture.getNow(null); |
| 637 | return channel == null || channel.isActive(); |
| 638 | } |
| 639 | } |
JunHuy Lam | 39eb429 | 2015-06-26 17:24:23 +0900 | [diff] [blame] | 640 | } |