blob: b84e193fdf0ca436262ffbb0cb3c122f389dd373 [file] [log] [blame]
Thomas Vachuska24c849c2014-10-27 09:53:05 -07001/*
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07002 * Copyright 2014 Open Networking Laboratory
Thomas Vachuska24c849c2014-10-27 09:53:05 -07003 *
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07004 * 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
Thomas Vachuska24c849c2014-10-27 09:53:05 -07007 *
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07008 * 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.
Thomas Vachuska24c849c2014-10-27 09:53:05 -070015 */
Madan Jampaniab6d3112014-10-02 16:30:14 -070016package org.onlab.netty;
17
Madan Jampaniab6d3112014-10-02 16:30:14 -070018import io.netty.bootstrap.Bootstrap;
19import io.netty.bootstrap.ServerBootstrap;
20import io.netty.buffer.PooledByteBufAllocator;
21import io.netty.channel.Channel;
22import io.netty.channel.ChannelFuture;
Madan Jampani5f9ec9a2014-10-29 13:45:52 -070023import io.netty.channel.ChannelFutureListener;
Madan Jampaniddf76222014-10-04 23:48:44 -070024import io.netty.channel.ChannelHandler;
Madan Jampaniab6d3112014-10-02 16:30:14 -070025import io.netty.channel.ChannelHandlerContext;
26import io.netty.channel.ChannelInitializer;
27import io.netty.channel.ChannelOption;
28import io.netty.channel.EventLoopGroup;
Madan Jampani824a7c12014-10-21 09:46:15 -070029import io.netty.channel.ServerChannel;
Madan Jampaniab6d3112014-10-02 16:30:14 -070030import io.netty.channel.SimpleChannelInboundHandler;
Madan Jampani824a7c12014-10-21 09:46:15 -070031import io.netty.channel.epoll.EpollEventLoopGroup;
32import io.netty.channel.epoll.EpollServerSocketChannel;
33import io.netty.channel.epoll.EpollSocketChannel;
Madan Jampaniab6d3112014-10-02 16:30:14 -070034import io.netty.channel.nio.NioEventLoopGroup;
35import io.netty.channel.socket.SocketChannel;
36import io.netty.channel.socket.nio.NioServerSocketChannel;
37import io.netty.channel.socket.nio.NioSocketChannel;
38
Madan Jampani348a9fe2014-11-09 01:37:51 -080039import java.io.IOException;
Madan Jampani2e5f87b2015-02-22 10:37:15 -080040import java.net.InetAddress;
Madan Jampani348a9fe2014-11-09 01:37:51 -080041import java.net.UnknownHostException;
42import java.util.concurrent.ConcurrentHashMap;
43import java.util.concurrent.ConcurrentMap;
Madan Jampani2af244a2015-02-22 13:12:01 -080044import java.util.concurrent.ExecutorService;
Madan Jampani348a9fe2014-11-09 01:37:51 -080045import java.util.concurrent.TimeUnit;
46import java.util.concurrent.TimeoutException;
47import java.util.concurrent.atomic.AtomicLong;
48
Madan Jampaniab6d3112014-10-02 16:30:14 -070049import org.apache.commons.pool.KeyedPoolableObjectFactory;
50import org.apache.commons.pool.impl.GenericKeyedObjectPool;
Madan Jampani2e5f87b2015-02-22 10:37:15 -080051import org.onlab.packet.IpAddress;
Madan Jampaniab6d3112014-10-02 16:30:14 -070052import org.slf4j.Logger;
53import org.slf4j.LoggerFactory;
54
Madan Jampani2e5f87b2015-02-22 10:37:15 -080055import com.google.common.base.Charsets;
Madan Jampaniab6d3112014-10-02 16:30:14 -070056import com.google.common.cache.Cache;
57import com.google.common.cache.CacheBuilder;
Madan Jampani2e5f87b2015-02-22 10:37:15 -080058import com.google.common.cache.CacheLoader;
59import com.google.common.cache.LoadingCache;
Madan Jampani5f9ec9a2014-10-29 13:45:52 -070060import com.google.common.cache.RemovalListener;
61import com.google.common.cache.RemovalNotification;
Madan Jampani2e5f87b2015-02-22 10:37:15 -080062import com.google.common.hash.Hashing;
Madan Jampani24f9efb2014-10-24 18:56:23 -070063import com.google.common.util.concurrent.ListenableFuture;
64import com.google.common.util.concurrent.SettableFuture;
Madan Jampaniab6d3112014-10-02 16:30:14 -070065
66/**
67 * A Netty based implementation of MessagingService.
68 */
69public class NettyMessagingService implements MessagingService {
70
71 private final Logger log = LoggerFactory.getLogger(getClass());
72
Madan Jampaniddf76222014-10-04 23:48:44 -070073 private final Endpoint localEp;
Madan Jampani2e5f87b2015-02-22 10:37:15 -080074 private final ConcurrentMap<Long, MessageHandler> handlers = new ConcurrentHashMap<>();
Madan Jampani24f9efb2014-10-24 18:56:23 -070075 private final AtomicLong messageIdGenerator = new AtomicLong(0);
76 private final Cache<Long, SettableFuture<byte[]>> responseFutures = CacheBuilder.newBuilder()
Madan Jampaniddf76222014-10-04 23:48:44 -070077 .maximumSize(100000)
Madan Jampani5f9ec9a2014-10-29 13:45:52 -070078 .expireAfterWrite(10, TimeUnit.SECONDS)
79 .removalListener(new RemovalListener<Long, SettableFuture<byte[]>>() {
80 @Override
81 public void onRemoval(RemovalNotification<Long, SettableFuture<byte[]>> entry) {
Yuta HIGUCHIc611d922015-02-10 16:07:38 -080082 if (entry.wasEvicted()) {
83 entry.getValue().setException(new TimeoutException("Timedout waiting for reply"));
84 }
Madan Jampani5f9ec9a2014-10-29 13:45:52 -070085 }
86 })
Madan Jampaniddf76222014-10-04 23:48:44 -070087 .build();
Madan Jampani2e5f87b2015-02-22 10:37:15 -080088
89 private final LoadingCache<String, Long> messageTypeLookupCache = CacheBuilder.newBuilder()
90 .softValues()
91 .build(new CacheLoader<String, Long>() {
92
93 @Override
94 public Long load(String type) {
95 return hashToLong(type);
96 }
97 });
98
Madan Jampaniddf76222014-10-04 23:48:44 -070099 private final GenericKeyedObjectPool<Endpoint, Channel> channels
100 = new GenericKeyedObjectPool<Endpoint, Channel>(new OnosCommunicationChannelFactory());
Madan Jampaniab6d3112014-10-02 16:30:14 -0700101
Madan Jampani824a7c12014-10-21 09:46:15 -0700102 private EventLoopGroup serverGroup;
103 private EventLoopGroup clientGroup;
104 private Class<? extends ServerChannel> serverChannelClass;
105 private Class<? extends Channel> clientChannelClass;
106
Madan Jampani5e83f332014-10-20 15:35:09 -0700107 private void initEventLoopGroup() {
Madan Jampani824a7c12014-10-21 09:46:15 -0700108 // try Epoll first and if that does work, use nio.
Madan Jampani824a7c12014-10-21 09:46:15 -0700109 try {
Madan Jampani99e9fe22014-10-21 13:47:12 -0700110 clientGroup = new EpollEventLoopGroup();
111 serverGroup = new EpollEventLoopGroup();
112 serverChannelClass = EpollServerSocketChannel.class;
113 clientChannelClass = EpollSocketChannel.class;
114 return;
Madan Jampani824a7c12014-10-21 09:46:15 -0700115 } catch (Throwable t) {
Madan Jampanicfbc0542014-10-24 20:38:07 -0700116 log.warn("Failed to initialize native (epoll) transport. Reason: {}. Proceeding with nio.", t.getMessage());
Madan Jampani824a7c12014-10-21 09:46:15 -0700117 }
118 clientGroup = new NioEventLoopGroup();
119 serverGroup = new NioEventLoopGroup();
120 serverChannelClass = NioServerSocketChannel.class;
121 clientChannelClass = NioSocketChannel.class;
Madan Jampani5e83f332014-10-20 15:35:09 -0700122 }
123
Madan Jampani2e5f87b2015-02-22 10:37:15 -0800124 public NettyMessagingService(IpAddress ip, int port) {
Madan Jampani87100932014-10-21 16:46:12 -0700125 localEp = new Endpoint(ip, port);
126 }
127
Madan Jampaniab6d3112014-10-02 16:30:14 -0700128 public NettyMessagingService() {
Madan Jampaniab6d3112014-10-02 16:30:14 -0700129 this(8080);
130 }
131
Madan Jampaniab6d3112014-10-02 16:30:14 -0700132 public NettyMessagingService(int port) {
Madan Jampaniab6d3112014-10-02 16:30:14 -0700133 try {
Madan Jampani2e5f87b2015-02-22 10:37:15 -0800134 localEp = new Endpoint(IpAddress.valueOf(InetAddress.getLocalHost()), port);
Madan Jampaniab6d3112014-10-02 16:30:14 -0700135 } catch (UnknownHostException e) {
Ray Milkey3f0c97e2014-12-08 14:53:30 -0800136 // Cannot resolve the local host, something is very wrong. Bailing out.
137 throw new IllegalStateException("Cannot resolve local host", e);
Madan Jampaniab6d3112014-10-02 16:30:14 -0700138 }
139 }
140
Ray Milkey3f0c97e2014-12-08 14:53:30 -0800141 public void activate() throws InterruptedException {
Madan Jampani86ed0552014-10-03 16:45:42 -0700142 channels.setTestOnBorrow(true);
143 channels.setTestOnReturn(true);
Madan Jampani5e83f332014-10-20 15:35:09 -0700144 initEventLoopGroup();
Madan Jampaniab6d3112014-10-02 16:30:14 -0700145 startAcceptingConnections();
146 }
147
148 public void deactivate() throws Exception {
149 channels.close();
Madan Jampani824a7c12014-10-21 09:46:15 -0700150 serverGroup.shutdownGracefully();
151 clientGroup.shutdownGracefully();
Madan Jampaniab6d3112014-10-02 16:30:14 -0700152 }
153
Madan Jampani87100932014-10-21 16:46:12 -0700154 /**
155 * Returns the local endpoint for this instance.
156 * @return local end point.
157 */
158 public Endpoint localEp() {
159 return localEp;
160 }
161
Madan Jampaniab6d3112014-10-02 16:30:14 -0700162 @Override
Madan Jampani53e44e62014-10-07 12:39:51 -0700163 public void sendAsync(Endpoint ep, String type, byte[] payload) throws IOException {
Madan Jampaniab6d3112014-10-02 16:30:14 -0700164 InternalMessage message = new InternalMessage.Builder(this)
Madan Jampani24f9efb2014-10-24 18:56:23 -0700165 .withId(messageIdGenerator.incrementAndGet())
Madan Jampaniab6d3112014-10-02 16:30:14 -0700166 .withSender(localEp)
Madan Jampani2e5f87b2015-02-22 10:37:15 -0800167 .withType(messageTypeLookupCache.getUnchecked(type))
Madan Jampaniab6d3112014-10-02 16:30:14 -0700168 .withPayload(payload)
169 .build();
170 sendAsync(ep, message);
171 }
172
173 protected void sendAsync(Endpoint ep, InternalMessage message) throws IOException {
174 Channel channel = null;
175 try {
Madan Jampani86ed0552014-10-03 16:45:42 -0700176 try {
177 channel = channels.borrowObject(ep);
178 channel.eventLoop().execute(new WriteTask(channel, message));
179 } finally {
180 channels.returnObject(ep, channel);
181 }
Madan Jampani5f9ec9a2014-10-29 13:45:52 -0700182 } catch (IOException e) {
183 throw e;
Madan Jampaniab6d3112014-10-02 16:30:14 -0700184 } catch (Exception e) {
Madan Jampani5f9ec9a2014-10-29 13:45:52 -0700185 throw new IOException(e);
Madan Jampaniab6d3112014-10-02 16:30:14 -0700186 }
Madan Jampani5f9ec9a2014-10-29 13:45:52 -0700187
Madan Jampaniab6d3112014-10-02 16:30:14 -0700188 }
189
190 @Override
Madan Jampani24f9efb2014-10-24 18:56:23 -0700191 public ListenableFuture<byte[]> sendAndReceive(Endpoint ep, String type, byte[] payload)
Madan Jampaniab6d3112014-10-02 16:30:14 -0700192 throws IOException {
Madan Jampani24f9efb2014-10-24 18:56:23 -0700193 SettableFuture<byte[]> futureResponse = SettableFuture.create();
194 Long messageId = messageIdGenerator.incrementAndGet();
Madan Jampaniab6d3112014-10-02 16:30:14 -0700195 responseFutures.put(messageId, futureResponse);
196 InternalMessage message = new InternalMessage.Builder(this)
197 .withId(messageId)
198 .withSender(localEp)
Madan Jampani2e5f87b2015-02-22 10:37:15 -0800199 .withType(messageTypeLookupCache.getUnchecked(type))
Madan Jampaniab6d3112014-10-02 16:30:14 -0700200 .withPayload(payload)
201 .build();
Madan Jampani15cd0b82014-10-28 08:40:23 -0700202 try {
203 sendAsync(ep, message);
Madan Jampani5f9ec9a2014-10-29 13:45:52 -0700204 } catch (Exception e) {
Madan Jampani15cd0b82014-10-28 08:40:23 -0700205 responseFutures.invalidate(messageId);
206 throw e;
207 }
Madan Jampaniab6d3112014-10-02 16:30:14 -0700208 return futureResponse;
209 }
210
211 @Override
212 public void registerHandler(String type, MessageHandler handler) {
Madan Jampani2e5f87b2015-02-22 10:37:15 -0800213 handlers.putIfAbsent(hashToLong(type), handler);
Madan Jampaniab6d3112014-10-02 16:30:14 -0700214 }
215
Yuta HIGUCHIe5ca93b2014-10-23 09:49:00 -0700216 @Override
Madan Jampani2af244a2015-02-22 13:12:01 -0800217 public void registerHandler(String type, MessageHandler handler, ExecutorService executor) {
218 handlers.putIfAbsent(hashToLong(type), new MessageHandler() {
219 @Override
220 public void handle(Message message) throws IOException {
221 executor.submit(() -> {
222 try {
223 handler.handle(message);
224 } catch (Exception e) {
225 log.warn("Failed to process message of type {}", type, e);
226 }
227 });
228 }
229 });
230 }
231
232 @Override
Madan Jampaniab6d3112014-10-02 16:30:14 -0700233 public void unregisterHandler(String type) {
234 handlers.remove(type);
235 }
236
Madan Jampani2e5f87b2015-02-22 10:37:15 -0800237 private MessageHandler getMessageHandler(long type) {
Madan Jampaniab6d3112014-10-02 16:30:14 -0700238 return handlers.get(type);
239 }
240
241 private void startAcceptingConnections() throws InterruptedException {
242 ServerBootstrap b = new ServerBootstrap();
Madan Jampani86ed0552014-10-03 16:45:42 -0700243 b.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 32 * 1024);
Madan Jampaniddf76222014-10-04 23:48:44 -0700244 b.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024);
Madan Jampaniab6d3112014-10-02 16:30:14 -0700245 b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
Madan Jampani824a7c12014-10-21 09:46:15 -0700246 b.group(serverGroup, clientGroup)
247 .channel(serverChannelClass)
Madan Jampaniab6d3112014-10-02 16:30:14 -0700248 .childHandler(new OnosCommunicationChannelInitializer())
249 .option(ChannelOption.SO_BACKLOG, 128)
250 .childOption(ChannelOption.SO_KEEPALIVE, true);
251
252 // Bind and start to accept incoming connections.
Madan Jampani87100932014-10-21 16:46:12 -0700253 b.bind(localEp.port()).sync();
Madan Jampaniab6d3112014-10-02 16:30:14 -0700254 }
255
256 private class OnosCommunicationChannelFactory
257 implements KeyedPoolableObjectFactory<Endpoint, Channel> {
258
259 @Override
260 public void activateObject(Endpoint endpoint, Channel channel)
261 throws Exception {
262 }
263
264 @Override
265 public void destroyObject(Endpoint ep, Channel channel) throws Exception {
266 channel.close();
267 }
268
269 @Override
270 public Channel makeObject(Endpoint ep) throws Exception {
Madan Jampaniddf76222014-10-04 23:48:44 -0700271 Bootstrap bootstrap = new Bootstrap();
272 bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
273 bootstrap.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 32 * 1024);
274 bootstrap.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024);
Madan Jampani824a7c12014-10-21 09:46:15 -0700275 bootstrap.group(clientGroup);
Madan Jampaniab6d3112014-10-02 16:30:14 -0700276 // TODO: Make this faster:
277 // http://normanmaurer.me/presentations/2014-facebook-eng-netty/slides.html#37.0
Madan Jampani824a7c12014-10-21 09:46:15 -0700278 bootstrap.channel(clientChannelClass);
Madan Jampaniddf76222014-10-04 23:48:44 -0700279 bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
280 bootstrap.handler(new OnosCommunicationChannelInitializer());
Madan Jampaniab6d3112014-10-02 16:30:14 -0700281 // Start the client.
Madan Jampani2e5f87b2015-02-22 10:37:15 -0800282 ChannelFuture f = bootstrap.connect(ep.host().toString(), ep.port()).sync();
Madan Jampaniab6d3112014-10-02 16:30:14 -0700283 return f.channel();
284 }
285
286 @Override
287 public void passivateObject(Endpoint ep, Channel channel)
288 throws Exception {
289 }
290
291 @Override
292 public boolean validateObject(Endpoint ep, Channel channel) {
293 return channel.isOpen();
294 }
295 }
296
297 private class OnosCommunicationChannelInitializer extends ChannelInitializer<SocketChannel> {
298
Madan Jampaniddf76222014-10-04 23:48:44 -0700299 private final ChannelHandler dispatcher = new InboundMessageDispatcher();
Madan Jampani53e44e62014-10-07 12:39:51 -0700300 private final ChannelHandler encoder = new MessageEncoder();
Madan Jampaniddf76222014-10-04 23:48:44 -0700301
Madan Jampaniab6d3112014-10-02 16:30:14 -0700302 @Override
303 protected void initChannel(SocketChannel channel) throws Exception {
304 channel.pipeline()
Madan Jampaniddf76222014-10-04 23:48:44 -0700305 .addLast("encoder", encoder)
Madan Jampani53e44e62014-10-07 12:39:51 -0700306 .addLast("decoder", new MessageDecoder(NettyMessagingService.this))
Madan Jampaniddf76222014-10-04 23:48:44 -0700307 .addLast("handler", dispatcher);
Madan Jampaniab6d3112014-10-02 16:30:14 -0700308 }
309 }
310
Yuta HIGUCHIe5ca93b2014-10-23 09:49:00 -0700311 private static class WriteTask implements Runnable {
Madan Jampaniab6d3112014-10-02 16:30:14 -0700312
Madan Jampani86ed0552014-10-03 16:45:42 -0700313 private final InternalMessage message;
Madan Jampaniab6d3112014-10-02 16:30:14 -0700314 private final Channel channel;
315
Madan Jampani86ed0552014-10-03 16:45:42 -0700316 public WriteTask(Channel channel, InternalMessage message) {
Madan Jampaniab6d3112014-10-02 16:30:14 -0700317 this.channel = channel;
Madan Jampani86ed0552014-10-03 16:45:42 -0700318 this.message = message;
Madan Jampaniab6d3112014-10-02 16:30:14 -0700319 }
320
321 @Override
322 public void run() {
Madan Jampani5f9ec9a2014-10-29 13:45:52 -0700323 channel.writeAndFlush(message).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
Madan Jampaniab6d3112014-10-02 16:30:14 -0700324 }
325 }
326
Madan Jampaniddf76222014-10-04 23:48:44 -0700327 @ChannelHandler.Sharable
Madan Jampaniab6d3112014-10-02 16:30:14 -0700328 private class InboundMessageDispatcher extends SimpleChannelInboundHandler<InternalMessage> {
329
330 @Override
331 protected void channelRead0(ChannelHandlerContext ctx, InternalMessage message) throws Exception {
Madan Jampani2e5f87b2015-02-22 10:37:15 -0800332 long type = message.type();
333 if (type == InternalMessage.REPLY_MESSAGE_TYPE) {
Madan Jampaniab6d3112014-10-02 16:30:14 -0700334 try {
Madan Jampani24f9efb2014-10-24 18:56:23 -0700335 SettableFuture<byte[]> futureResponse =
Madan Jampaniab6d3112014-10-02 16:30:14 -0700336 NettyMessagingService.this.responseFutures.getIfPresent(message.id());
337 if (futureResponse != null) {
Madan Jampani24f9efb2014-10-24 18:56:23 -0700338 futureResponse.set(message.payload());
Madan Jampanif1d425a2014-10-07 09:52:36 -0700339 } else {
Madan Jampani15cd0b82014-10-28 08:40:23 -0700340 log.warn("Received a reply for message id:[{}]. "
Madan Jampani348a9fe2014-11-09 01:37:51 -0800341 + " from {}. But was unable to locate the"
342 + " request handle", message.id(), message.sender());
Madan Jampaniab6d3112014-10-02 16:30:14 -0700343 }
Madan Jampaniab6d3112014-10-02 16:30:14 -0700344 } finally {
345 NettyMessagingService.this.responseFutures.invalidate(message.id());
346 }
347 return;
348 }
349 MessageHandler handler = NettyMessagingService.this.getMessageHandler(type);
Yuta HIGUCHI5f9d6962014-11-07 13:06:45 -0800350 if (handler != null) {
351 handler.handle(message);
352 } else {
353 log.debug("No handler registered for {}", type);
354 }
Madan Jampaniab6d3112014-10-02 16:30:14 -0700355 }
Madan Jampani86ed0552014-10-03 16:45:42 -0700356
Madan Jampani86ed0552014-10-03 16:45:42 -0700357 @Override
358 public void exceptionCaught(ChannelHandlerContext context, Throwable cause) {
Madan Jampani29e5dfd2014-10-07 17:26:25 -0700359 log.error("Exception inside channel handling pipeline.", cause);
Madan Jampani86ed0552014-10-03 16:45:42 -0700360 context.close();
361 }
Madan Jampaniab6d3112014-10-02 16:30:14 -0700362 }
Madan Jampani2e5f87b2015-02-22 10:37:15 -0800363
364 /**
365 * Returns the md5 hash of the specified input string as a long.
366 * @param input input string.
367 * @return md5 hash as long.
368 */
369 public static long hashToLong(String input) {
370 return Hashing.md5().hashBytes(input.getBytes(Charsets.UTF_8)).asLong();
371 }
372}