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