blob: 69806b183f5f150958ca6132774cf1cd19a1fb3d [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;
44import java.util.concurrent.TimeUnit;
45import java.util.concurrent.TimeoutException;
46import java.util.concurrent.atomic.AtomicLong;
47
Madan Jampaniab6d3112014-10-02 16:30:14 -070048import org.apache.commons.pool.KeyedPoolableObjectFactory;
49import org.apache.commons.pool.impl.GenericKeyedObjectPool;
Madan Jampani2e5f87b2015-02-22 10:37:15 -080050import org.onlab.packet.IpAddress;
Madan Jampaniab6d3112014-10-02 16:30:14 -070051import org.slf4j.Logger;
52import org.slf4j.LoggerFactory;
53
Madan Jampani2e5f87b2015-02-22 10:37:15 -080054import com.google.common.base.Charsets;
Madan Jampaniab6d3112014-10-02 16:30:14 -070055import com.google.common.cache.Cache;
56import com.google.common.cache.CacheBuilder;
Madan Jampani2e5f87b2015-02-22 10:37:15 -080057import com.google.common.cache.CacheLoader;
58import com.google.common.cache.LoadingCache;
Madan Jampani5f9ec9a2014-10-29 13:45:52 -070059import com.google.common.cache.RemovalListener;
60import com.google.common.cache.RemovalNotification;
Madan Jampani2e5f87b2015-02-22 10:37:15 -080061import com.google.common.hash.Hashing;
Madan Jampani24f9efb2014-10-24 18:56:23 -070062import com.google.common.util.concurrent.ListenableFuture;
63import com.google.common.util.concurrent.SettableFuture;
Madan Jampaniab6d3112014-10-02 16:30:14 -070064
65/**
66 * A Netty based implementation of MessagingService.
67 */
68public class NettyMessagingService implements MessagingService {
69
70 private final Logger log = LoggerFactory.getLogger(getClass());
71
Madan Jampaniddf76222014-10-04 23:48:44 -070072 private final Endpoint localEp;
Madan Jampani2e5f87b2015-02-22 10:37:15 -080073 private final ConcurrentMap<Long, MessageHandler> handlers = new ConcurrentHashMap<>();
Madan Jampani24f9efb2014-10-24 18:56:23 -070074 private final AtomicLong messageIdGenerator = new AtomicLong(0);
75 private final Cache<Long, SettableFuture<byte[]>> responseFutures = CacheBuilder.newBuilder()
Madan Jampaniddf76222014-10-04 23:48:44 -070076 .maximumSize(100000)
Madan Jampani5f9ec9a2014-10-29 13:45:52 -070077 .expireAfterWrite(10, TimeUnit.SECONDS)
78 .removalListener(new RemovalListener<Long, SettableFuture<byte[]>>() {
79 @Override
80 public void onRemoval(RemovalNotification<Long, SettableFuture<byte[]>> entry) {
Yuta HIGUCHIc611d922015-02-10 16:07:38 -080081 if (entry.wasEvicted()) {
82 entry.getValue().setException(new TimeoutException("Timedout waiting for reply"));
83 }
Madan Jampani5f9ec9a2014-10-29 13:45:52 -070084 }
85 })
Madan Jampaniddf76222014-10-04 23:48:44 -070086 .build();
Madan Jampani2e5f87b2015-02-22 10:37:15 -080087
88 private final LoadingCache<String, Long> messageTypeLookupCache = CacheBuilder.newBuilder()
89 .softValues()
90 .build(new CacheLoader<String, Long>() {
91
92 @Override
93 public Long load(String type) {
94 return hashToLong(type);
95 }
96 });
97
Madan Jampaniddf76222014-10-04 23:48:44 -070098 private final GenericKeyedObjectPool<Endpoint, Channel> channels
99 = new GenericKeyedObjectPool<Endpoint, Channel>(new OnosCommunicationChannelFactory());
Madan Jampaniab6d3112014-10-02 16:30:14 -0700100
Madan Jampani824a7c12014-10-21 09:46:15 -0700101 private EventLoopGroup serverGroup;
102 private EventLoopGroup clientGroup;
103 private Class<? extends ServerChannel> serverChannelClass;
104 private Class<? extends Channel> clientChannelClass;
105
Madan Jampani5e83f332014-10-20 15:35:09 -0700106 private void initEventLoopGroup() {
Madan Jampani824a7c12014-10-21 09:46:15 -0700107 // try Epoll first and if that does work, use nio.
Madan Jampani824a7c12014-10-21 09:46:15 -0700108 try {
Madan Jampani99e9fe22014-10-21 13:47:12 -0700109 clientGroup = new EpollEventLoopGroup();
110 serverGroup = new EpollEventLoopGroup();
111 serverChannelClass = EpollServerSocketChannel.class;
112 clientChannelClass = EpollSocketChannel.class;
113 return;
Madan Jampani824a7c12014-10-21 09:46:15 -0700114 } catch (Throwable t) {
Madan Jampanicfbc0542014-10-24 20:38:07 -0700115 log.warn("Failed to initialize native (epoll) transport. Reason: {}. Proceeding with nio.", t.getMessage());
Madan Jampani824a7c12014-10-21 09:46:15 -0700116 }
117 clientGroup = new NioEventLoopGroup();
118 serverGroup = new NioEventLoopGroup();
119 serverChannelClass = NioServerSocketChannel.class;
120 clientChannelClass = NioSocketChannel.class;
Madan Jampani5e83f332014-10-20 15:35:09 -0700121 }
122
Madan Jampani2e5f87b2015-02-22 10:37:15 -0800123 public NettyMessagingService(IpAddress ip, int port) {
Madan Jampani87100932014-10-21 16:46:12 -0700124 localEp = new Endpoint(ip, port);
125 }
126
Madan Jampaniab6d3112014-10-02 16:30:14 -0700127 public NettyMessagingService() {
Madan Jampaniab6d3112014-10-02 16:30:14 -0700128 this(8080);
129 }
130
Madan Jampaniab6d3112014-10-02 16:30:14 -0700131 public NettyMessagingService(int port) {
Madan Jampaniab6d3112014-10-02 16:30:14 -0700132 try {
Madan Jampani2e5f87b2015-02-22 10:37:15 -0800133 localEp = new Endpoint(IpAddress.valueOf(InetAddress.getLocalHost()), port);
Madan Jampaniab6d3112014-10-02 16:30:14 -0700134 } catch (UnknownHostException e) {
Ray Milkey3f0c97e2014-12-08 14:53:30 -0800135 // Cannot resolve the local host, something is very wrong. Bailing out.
136 throw new IllegalStateException("Cannot resolve local host", e);
Madan Jampaniab6d3112014-10-02 16:30:14 -0700137 }
138 }
139
Ray Milkey3f0c97e2014-12-08 14:53:30 -0800140 public void activate() throws InterruptedException {
Madan Jampani86ed0552014-10-03 16:45:42 -0700141 channels.setTestOnBorrow(true);
142 channels.setTestOnReturn(true);
Madan Jampani5e83f332014-10-20 15:35:09 -0700143 initEventLoopGroup();
Madan Jampaniab6d3112014-10-02 16:30:14 -0700144 startAcceptingConnections();
145 }
146
147 public void deactivate() throws Exception {
148 channels.close();
Madan Jampani824a7c12014-10-21 09:46:15 -0700149 serverGroup.shutdownGracefully();
150 clientGroup.shutdownGracefully();
Madan Jampaniab6d3112014-10-02 16:30:14 -0700151 }
152
Madan Jampani87100932014-10-21 16:46:12 -0700153 /**
154 * Returns the local endpoint for this instance.
155 * @return local end point.
156 */
157 public Endpoint localEp() {
158 return localEp;
159 }
160
Madan Jampaniab6d3112014-10-02 16:30:14 -0700161 @Override
Madan Jampani53e44e62014-10-07 12:39:51 -0700162 public void sendAsync(Endpoint ep, String type, byte[] payload) throws IOException {
Madan Jampaniab6d3112014-10-02 16:30:14 -0700163 InternalMessage message = new InternalMessage.Builder(this)
Madan Jampani24f9efb2014-10-24 18:56:23 -0700164 .withId(messageIdGenerator.incrementAndGet())
Madan Jampaniab6d3112014-10-02 16:30:14 -0700165 .withSender(localEp)
Madan Jampani2e5f87b2015-02-22 10:37:15 -0800166 .withType(messageTypeLookupCache.getUnchecked(type))
Madan Jampaniab6d3112014-10-02 16:30:14 -0700167 .withPayload(payload)
168 .build();
169 sendAsync(ep, message);
170 }
171
172 protected void sendAsync(Endpoint ep, InternalMessage message) throws IOException {
173 Channel channel = null;
174 try {
Madan Jampani86ed0552014-10-03 16:45:42 -0700175 try {
176 channel = channels.borrowObject(ep);
177 channel.eventLoop().execute(new WriteTask(channel, message));
178 } finally {
179 channels.returnObject(ep, channel);
180 }
Madan Jampani5f9ec9a2014-10-29 13:45:52 -0700181 } catch (IOException e) {
182 throw e;
Madan Jampaniab6d3112014-10-02 16:30:14 -0700183 } catch (Exception e) {
Madan Jampani5f9ec9a2014-10-29 13:45:52 -0700184 throw new IOException(e);
Madan Jampaniab6d3112014-10-02 16:30:14 -0700185 }
Madan Jampani5f9ec9a2014-10-29 13:45:52 -0700186
Madan Jampaniab6d3112014-10-02 16:30:14 -0700187 }
188
189 @Override
Madan Jampani24f9efb2014-10-24 18:56:23 -0700190 public ListenableFuture<byte[]> sendAndReceive(Endpoint ep, String type, byte[] payload)
Madan Jampaniab6d3112014-10-02 16:30:14 -0700191 throws IOException {
Madan Jampani24f9efb2014-10-24 18:56:23 -0700192 SettableFuture<byte[]> futureResponse = SettableFuture.create();
193 Long messageId = messageIdGenerator.incrementAndGet();
Madan Jampaniab6d3112014-10-02 16:30:14 -0700194 responseFutures.put(messageId, futureResponse);
195 InternalMessage message = new InternalMessage.Builder(this)
196 .withId(messageId)
197 .withSender(localEp)
Madan Jampani2e5f87b2015-02-22 10:37:15 -0800198 .withType(messageTypeLookupCache.getUnchecked(type))
Madan Jampaniab6d3112014-10-02 16:30:14 -0700199 .withPayload(payload)
200 .build();
Madan Jampani15cd0b82014-10-28 08:40:23 -0700201 try {
202 sendAsync(ep, message);
Madan Jampani5f9ec9a2014-10-29 13:45:52 -0700203 } catch (Exception e) {
Madan Jampani15cd0b82014-10-28 08:40:23 -0700204 responseFutures.invalidate(messageId);
205 throw e;
206 }
Madan Jampaniab6d3112014-10-02 16:30:14 -0700207 return futureResponse;
208 }
209
210 @Override
211 public void registerHandler(String type, MessageHandler handler) {
Madan Jampani2e5f87b2015-02-22 10:37:15 -0800212 handlers.putIfAbsent(hashToLong(type), handler);
Madan Jampaniab6d3112014-10-02 16:30:14 -0700213 }
214
Yuta HIGUCHIe5ca93b2014-10-23 09:49:00 -0700215 @Override
Madan Jampaniab6d3112014-10-02 16:30:14 -0700216 public void unregisterHandler(String type) {
217 handlers.remove(type);
218 }
219
Madan Jampani2e5f87b2015-02-22 10:37:15 -0800220 private MessageHandler getMessageHandler(long type) {
Madan Jampaniab6d3112014-10-02 16:30:14 -0700221 return handlers.get(type);
222 }
223
224 private void startAcceptingConnections() throws InterruptedException {
225 ServerBootstrap b = new ServerBootstrap();
Madan Jampani86ed0552014-10-03 16:45:42 -0700226 b.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 32 * 1024);
Madan Jampaniddf76222014-10-04 23:48:44 -0700227 b.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024);
Madan Jampaniab6d3112014-10-02 16:30:14 -0700228 b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
Madan Jampani824a7c12014-10-21 09:46:15 -0700229 b.group(serverGroup, clientGroup)
230 .channel(serverChannelClass)
Madan Jampaniab6d3112014-10-02 16:30:14 -0700231 .childHandler(new OnosCommunicationChannelInitializer())
232 .option(ChannelOption.SO_BACKLOG, 128)
233 .childOption(ChannelOption.SO_KEEPALIVE, true);
234
235 // Bind and start to accept incoming connections.
Madan Jampani87100932014-10-21 16:46:12 -0700236 b.bind(localEp.port()).sync();
Madan Jampaniab6d3112014-10-02 16:30:14 -0700237 }
238
239 private class OnosCommunicationChannelFactory
240 implements KeyedPoolableObjectFactory<Endpoint, Channel> {
241
242 @Override
243 public void activateObject(Endpoint endpoint, Channel channel)
244 throws Exception {
245 }
246
247 @Override
248 public void destroyObject(Endpoint ep, Channel channel) throws Exception {
249 channel.close();
250 }
251
252 @Override
253 public Channel makeObject(Endpoint ep) throws Exception {
Madan Jampaniddf76222014-10-04 23:48:44 -0700254 Bootstrap bootstrap = new Bootstrap();
255 bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
256 bootstrap.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 32 * 1024);
257 bootstrap.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024);
Madan Jampani824a7c12014-10-21 09:46:15 -0700258 bootstrap.group(clientGroup);
Madan Jampaniab6d3112014-10-02 16:30:14 -0700259 // TODO: Make this faster:
260 // http://normanmaurer.me/presentations/2014-facebook-eng-netty/slides.html#37.0
Madan Jampani824a7c12014-10-21 09:46:15 -0700261 bootstrap.channel(clientChannelClass);
Madan Jampaniddf76222014-10-04 23:48:44 -0700262 bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
263 bootstrap.handler(new OnosCommunicationChannelInitializer());
Madan Jampaniab6d3112014-10-02 16:30:14 -0700264 // Start the client.
Madan Jampani2e5f87b2015-02-22 10:37:15 -0800265 ChannelFuture f = bootstrap.connect(ep.host().toString(), ep.port()).sync();
Madan Jampaniab6d3112014-10-02 16:30:14 -0700266 return f.channel();
267 }
268
269 @Override
270 public void passivateObject(Endpoint ep, Channel channel)
271 throws Exception {
272 }
273
274 @Override
275 public boolean validateObject(Endpoint ep, Channel channel) {
276 return channel.isOpen();
277 }
278 }
279
280 private class OnosCommunicationChannelInitializer extends ChannelInitializer<SocketChannel> {
281
Madan Jampaniddf76222014-10-04 23:48:44 -0700282 private final ChannelHandler dispatcher = new InboundMessageDispatcher();
Madan Jampani53e44e62014-10-07 12:39:51 -0700283 private final ChannelHandler encoder = new MessageEncoder();
Madan Jampaniddf76222014-10-04 23:48:44 -0700284
Madan Jampaniab6d3112014-10-02 16:30:14 -0700285 @Override
286 protected void initChannel(SocketChannel channel) throws Exception {
287 channel.pipeline()
Madan Jampaniddf76222014-10-04 23:48:44 -0700288 .addLast("encoder", encoder)
Madan Jampani53e44e62014-10-07 12:39:51 -0700289 .addLast("decoder", new MessageDecoder(NettyMessagingService.this))
Madan Jampaniddf76222014-10-04 23:48:44 -0700290 .addLast("handler", dispatcher);
Madan Jampaniab6d3112014-10-02 16:30:14 -0700291 }
292 }
293
Yuta HIGUCHIe5ca93b2014-10-23 09:49:00 -0700294 private static class WriteTask implements Runnable {
Madan Jampaniab6d3112014-10-02 16:30:14 -0700295
Madan Jampani86ed0552014-10-03 16:45:42 -0700296 private final InternalMessage message;
Madan Jampaniab6d3112014-10-02 16:30:14 -0700297 private final Channel channel;
298
Madan Jampani86ed0552014-10-03 16:45:42 -0700299 public WriteTask(Channel channel, InternalMessage message) {
Madan Jampaniab6d3112014-10-02 16:30:14 -0700300 this.channel = channel;
Madan Jampani86ed0552014-10-03 16:45:42 -0700301 this.message = message;
Madan Jampaniab6d3112014-10-02 16:30:14 -0700302 }
303
304 @Override
305 public void run() {
Madan Jampani5f9ec9a2014-10-29 13:45:52 -0700306 channel.writeAndFlush(message).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
Madan Jampaniab6d3112014-10-02 16:30:14 -0700307 }
308 }
309
Madan Jampaniddf76222014-10-04 23:48:44 -0700310 @ChannelHandler.Sharable
Madan Jampaniab6d3112014-10-02 16:30:14 -0700311 private class InboundMessageDispatcher extends SimpleChannelInboundHandler<InternalMessage> {
312
313 @Override
314 protected void channelRead0(ChannelHandlerContext ctx, InternalMessage message) throws Exception {
Madan Jampani2e5f87b2015-02-22 10:37:15 -0800315 long type = message.type();
316 if (type == InternalMessage.REPLY_MESSAGE_TYPE) {
Madan Jampaniab6d3112014-10-02 16:30:14 -0700317 try {
Madan Jampani24f9efb2014-10-24 18:56:23 -0700318 SettableFuture<byte[]> futureResponse =
Madan Jampaniab6d3112014-10-02 16:30:14 -0700319 NettyMessagingService.this.responseFutures.getIfPresent(message.id());
320 if (futureResponse != null) {
Madan Jampani24f9efb2014-10-24 18:56:23 -0700321 futureResponse.set(message.payload());
Madan Jampanif1d425a2014-10-07 09:52:36 -0700322 } else {
Madan Jampani15cd0b82014-10-28 08:40:23 -0700323 log.warn("Received a reply for message id:[{}]. "
Madan Jampani348a9fe2014-11-09 01:37:51 -0800324 + " from {}. But was unable to locate the"
325 + " request handle", message.id(), message.sender());
Madan Jampaniab6d3112014-10-02 16:30:14 -0700326 }
Madan Jampaniab6d3112014-10-02 16:30:14 -0700327 } finally {
328 NettyMessagingService.this.responseFutures.invalidate(message.id());
329 }
330 return;
331 }
332 MessageHandler handler = NettyMessagingService.this.getMessageHandler(type);
Yuta HIGUCHI5f9d6962014-11-07 13:06:45 -0800333 if (handler != null) {
334 handler.handle(message);
335 } else {
336 log.debug("No handler registered for {}", type);
337 }
Madan Jampaniab6d3112014-10-02 16:30:14 -0700338 }
Madan Jampani86ed0552014-10-03 16:45:42 -0700339
Madan Jampani86ed0552014-10-03 16:45:42 -0700340 @Override
341 public void exceptionCaught(ChannelHandlerContext context, Throwable cause) {
Madan Jampani29e5dfd2014-10-07 17:26:25 -0700342 log.error("Exception inside channel handling pipeline.", cause);
Madan Jampani86ed0552014-10-03 16:45:42 -0700343 context.close();
344 }
Madan Jampaniab6d3112014-10-02 16:30:14 -0700345 }
Madan Jampani2e5f87b2015-02-22 10:37:15 -0800346
347 /**
348 * Returns the md5 hash of the specified input string as a long.
349 * @param input input string.
350 * @return md5 hash as long.
351 */
352 public static long hashToLong(String input) {
353 return Hashing.md5().hashBytes(input.getBytes(Charsets.UTF_8)).asLong();
354 }
355}