Madan Jampani | ab6d311 | 2014-10-02 16:30:14 -0700 | [diff] [blame] | 1 | package org.onlab.netty; |
| 2 | |
| 3 | import java.io.IOException; |
| 4 | import java.net.UnknownHostException; |
| 5 | import java.util.concurrent.ConcurrentHashMap; |
| 6 | import java.util.concurrent.ConcurrentMap; |
| 7 | import java.util.concurrent.TimeUnit; |
Madan Jampani | 24f9efb | 2014-10-24 18:56:23 -0700 | [diff] [blame^] | 8 | import java.util.concurrent.atomic.AtomicLong; |
Madan Jampani | ab6d311 | 2014-10-02 16:30:14 -0700 | [diff] [blame] | 9 | |
| 10 | import io.netty.bootstrap.Bootstrap; |
| 11 | import io.netty.bootstrap.ServerBootstrap; |
| 12 | import io.netty.buffer.PooledByteBufAllocator; |
| 13 | import io.netty.channel.Channel; |
| 14 | import io.netty.channel.ChannelFuture; |
Madan Jampani | ddf7622 | 2014-10-04 23:48:44 -0700 | [diff] [blame] | 15 | import io.netty.channel.ChannelHandler; |
Madan Jampani | ab6d311 | 2014-10-02 16:30:14 -0700 | [diff] [blame] | 16 | import io.netty.channel.ChannelHandlerContext; |
| 17 | import io.netty.channel.ChannelInitializer; |
| 18 | import io.netty.channel.ChannelOption; |
| 19 | import io.netty.channel.EventLoopGroup; |
Madan Jampani | 824a7c1 | 2014-10-21 09:46:15 -0700 | [diff] [blame] | 20 | import io.netty.channel.ServerChannel; |
Madan Jampani | ab6d311 | 2014-10-02 16:30:14 -0700 | [diff] [blame] | 21 | import io.netty.channel.SimpleChannelInboundHandler; |
Madan Jampani | 824a7c1 | 2014-10-21 09:46:15 -0700 | [diff] [blame] | 22 | import io.netty.channel.epoll.EpollEventLoopGroup; |
| 23 | import io.netty.channel.epoll.EpollServerSocketChannel; |
| 24 | import io.netty.channel.epoll.EpollSocketChannel; |
Madan Jampani | ab6d311 | 2014-10-02 16:30:14 -0700 | [diff] [blame] | 25 | import io.netty.channel.nio.NioEventLoopGroup; |
| 26 | import io.netty.channel.socket.SocketChannel; |
| 27 | import io.netty.channel.socket.nio.NioServerSocketChannel; |
| 28 | import io.netty.channel.socket.nio.NioSocketChannel; |
| 29 | |
Madan Jampani | ab6d311 | 2014-10-02 16:30:14 -0700 | [diff] [blame] | 30 | import org.apache.commons.pool.KeyedPoolableObjectFactory; |
| 31 | import org.apache.commons.pool.impl.GenericKeyedObjectPool; |
| 32 | import org.slf4j.Logger; |
| 33 | import org.slf4j.LoggerFactory; |
| 34 | |
| 35 | import com.google.common.cache.Cache; |
| 36 | import com.google.common.cache.CacheBuilder; |
Madan Jampani | 24f9efb | 2014-10-24 18:56:23 -0700 | [diff] [blame^] | 37 | import com.google.common.util.concurrent.ListenableFuture; |
| 38 | import com.google.common.util.concurrent.SettableFuture; |
Madan Jampani | ab6d311 | 2014-10-02 16:30:14 -0700 | [diff] [blame] | 39 | |
| 40 | /** |
| 41 | * A Netty based implementation of MessagingService. |
| 42 | */ |
| 43 | public class NettyMessagingService implements MessagingService { |
| 44 | |
| 45 | private final Logger log = LoggerFactory.getLogger(getClass()); |
| 46 | |
Madan Jampani | ddf7622 | 2014-10-04 23:48:44 -0700 | [diff] [blame] | 47 | private final Endpoint localEp; |
Madan Jampani | ab6d311 | 2014-10-02 16:30:14 -0700 | [diff] [blame] | 48 | private final ConcurrentMap<String, MessageHandler> handlers = new ConcurrentHashMap<>(); |
Madan Jampani | 24f9efb | 2014-10-24 18:56:23 -0700 | [diff] [blame^] | 49 | private final AtomicLong messageIdGenerator = new AtomicLong(0); |
| 50 | private final Cache<Long, SettableFuture<byte[]>> responseFutures = CacheBuilder.newBuilder() |
Madan Jampani | ddf7622 | 2014-10-04 23:48:44 -0700 | [diff] [blame] | 51 | .maximumSize(100000) |
| 52 | .weakValues() |
| 53 | // TODO: Once the entry expires, notify blocking threads (if any). |
| 54 | .expireAfterWrite(10, TimeUnit.MINUTES) |
| 55 | .build(); |
| 56 | private final GenericKeyedObjectPool<Endpoint, Channel> channels |
| 57 | = new GenericKeyedObjectPool<Endpoint, Channel>(new OnosCommunicationChannelFactory()); |
Madan Jampani | ab6d311 | 2014-10-02 16:30:14 -0700 | [diff] [blame] | 58 | |
Madan Jampani | 824a7c1 | 2014-10-21 09:46:15 -0700 | [diff] [blame] | 59 | private EventLoopGroup serverGroup; |
| 60 | private EventLoopGroup clientGroup; |
| 61 | private Class<? extends ServerChannel> serverChannelClass; |
| 62 | private Class<? extends Channel> clientChannelClass; |
| 63 | |
Madan Jampani | 5e83f33 | 2014-10-20 15:35:09 -0700 | [diff] [blame] | 64 | private void initEventLoopGroup() { |
Madan Jampani | 824a7c1 | 2014-10-21 09:46:15 -0700 | [diff] [blame] | 65 | // try Epoll first and if that does work, use nio. |
| 66 | // TODO: make this configurable. |
| 67 | try { |
Madan Jampani | 99e9fe2 | 2014-10-21 13:47:12 -0700 | [diff] [blame] | 68 | clientGroup = new EpollEventLoopGroup(); |
| 69 | serverGroup = new EpollEventLoopGroup(); |
| 70 | serverChannelClass = EpollServerSocketChannel.class; |
| 71 | clientChannelClass = EpollSocketChannel.class; |
| 72 | return; |
Madan Jampani | 824a7c1 | 2014-10-21 09:46:15 -0700 | [diff] [blame] | 73 | } catch (Throwable t) { |
Madan Jampani | 99e9fe2 | 2014-10-21 13:47:12 -0700 | [diff] [blame] | 74 | log.warn("Failed to initialize native (epoll) transport. Proceeding with nio.", t); |
Madan Jampani | 824a7c1 | 2014-10-21 09:46:15 -0700 | [diff] [blame] | 75 | } |
| 76 | clientGroup = new NioEventLoopGroup(); |
| 77 | serverGroup = new NioEventLoopGroup(); |
| 78 | serverChannelClass = NioServerSocketChannel.class; |
| 79 | clientChannelClass = NioSocketChannel.class; |
Madan Jampani | 5e83f33 | 2014-10-20 15:35:09 -0700 | [diff] [blame] | 80 | } |
| 81 | |
Madan Jampani | 8710093 | 2014-10-21 16:46:12 -0700 | [diff] [blame] | 82 | public NettyMessagingService(String ip, int port) { |
| 83 | localEp = new Endpoint(ip, port); |
| 84 | } |
| 85 | |
Madan Jampani | ab6d311 | 2014-10-02 16:30:14 -0700 | [diff] [blame] | 86 | public NettyMessagingService() { |
| 87 | // TODO: Default port should be configurable. |
| 88 | this(8080); |
| 89 | } |
| 90 | |
| 91 | // FIXME: Constructor should not throw exceptions. |
| 92 | public NettyMessagingService(int port) { |
Madan Jampani | ab6d311 | 2014-10-02 16:30:14 -0700 | [diff] [blame] | 93 | try { |
| 94 | localEp = new Endpoint(java.net.InetAddress.getLocalHost().getHostName(), port); |
| 95 | } catch (UnknownHostException e) { |
| 96 | // bailing out. |
| 97 | throw new RuntimeException(e); |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | public void activate() throws Exception { |
Madan Jampani | 86ed055 | 2014-10-03 16:45:42 -0700 | [diff] [blame] | 102 | channels.setTestOnBorrow(true); |
| 103 | channels.setTestOnReturn(true); |
Madan Jampani | 5e83f33 | 2014-10-20 15:35:09 -0700 | [diff] [blame] | 104 | initEventLoopGroup(); |
Madan Jampani | ab6d311 | 2014-10-02 16:30:14 -0700 | [diff] [blame] | 105 | startAcceptingConnections(); |
| 106 | } |
| 107 | |
| 108 | public void deactivate() throws Exception { |
| 109 | channels.close(); |
Madan Jampani | 824a7c1 | 2014-10-21 09:46:15 -0700 | [diff] [blame] | 110 | serverGroup.shutdownGracefully(); |
| 111 | clientGroup.shutdownGracefully(); |
Madan Jampani | ab6d311 | 2014-10-02 16:30:14 -0700 | [diff] [blame] | 112 | } |
| 113 | |
Madan Jampani | 8710093 | 2014-10-21 16:46:12 -0700 | [diff] [blame] | 114 | /** |
| 115 | * Returns the local endpoint for this instance. |
| 116 | * @return local end point. |
| 117 | */ |
| 118 | public Endpoint localEp() { |
| 119 | return localEp; |
| 120 | } |
| 121 | |
Madan Jampani | ab6d311 | 2014-10-02 16:30:14 -0700 | [diff] [blame] | 122 | @Override |
Madan Jampani | 53e44e6 | 2014-10-07 12:39:51 -0700 | [diff] [blame] | 123 | public void sendAsync(Endpoint ep, String type, byte[] payload) throws IOException { |
Madan Jampani | ab6d311 | 2014-10-02 16:30:14 -0700 | [diff] [blame] | 124 | InternalMessage message = new InternalMessage.Builder(this) |
Madan Jampani | 24f9efb | 2014-10-24 18:56:23 -0700 | [diff] [blame^] | 125 | .withId(messageIdGenerator.incrementAndGet()) |
Madan Jampani | ab6d311 | 2014-10-02 16:30:14 -0700 | [diff] [blame] | 126 | .withSender(localEp) |
| 127 | .withType(type) |
| 128 | .withPayload(payload) |
| 129 | .build(); |
| 130 | sendAsync(ep, message); |
| 131 | } |
| 132 | |
| 133 | protected void sendAsync(Endpoint ep, InternalMessage message) throws IOException { |
| 134 | Channel channel = null; |
| 135 | try { |
Madan Jampani | 86ed055 | 2014-10-03 16:45:42 -0700 | [diff] [blame] | 136 | try { |
| 137 | channel = channels.borrowObject(ep); |
| 138 | channel.eventLoop().execute(new WriteTask(channel, message)); |
| 139 | } finally { |
| 140 | channels.returnObject(ep, channel); |
| 141 | } |
Madan Jampani | ab6d311 | 2014-10-02 16:30:14 -0700 | [diff] [blame] | 142 | } catch (Exception e) { |
Madan Jampani | 8710093 | 2014-10-21 16:46:12 -0700 | [diff] [blame] | 143 | throw new IOException("Failed to send message to " + ep.toString(), e); |
Madan Jampani | ab6d311 | 2014-10-02 16:30:14 -0700 | [diff] [blame] | 144 | } |
| 145 | } |
| 146 | |
| 147 | @Override |
Madan Jampani | 24f9efb | 2014-10-24 18:56:23 -0700 | [diff] [blame^] | 148 | public ListenableFuture<byte[]> sendAndReceive(Endpoint ep, String type, byte[] payload) |
Madan Jampani | ab6d311 | 2014-10-02 16:30:14 -0700 | [diff] [blame] | 149 | throws IOException { |
Madan Jampani | 24f9efb | 2014-10-24 18:56:23 -0700 | [diff] [blame^] | 150 | SettableFuture<byte[]> futureResponse = SettableFuture.create(); |
| 151 | Long messageId = messageIdGenerator.incrementAndGet(); |
Madan Jampani | ab6d311 | 2014-10-02 16:30:14 -0700 | [diff] [blame] | 152 | responseFutures.put(messageId, futureResponse); |
| 153 | InternalMessage message = new InternalMessage.Builder(this) |
| 154 | .withId(messageId) |
| 155 | .withSender(localEp) |
| 156 | .withType(type) |
| 157 | .withPayload(payload) |
| 158 | .build(); |
| 159 | sendAsync(ep, message); |
| 160 | return futureResponse; |
| 161 | } |
| 162 | |
| 163 | @Override |
| 164 | public void registerHandler(String type, MessageHandler handler) { |
| 165 | // TODO: Is this the right semantics for handler registration? |
| 166 | handlers.putIfAbsent(type, handler); |
| 167 | } |
| 168 | |
Yuta HIGUCHI | e5ca93b | 2014-10-23 09:49:00 -0700 | [diff] [blame] | 169 | @Override |
Madan Jampani | ab6d311 | 2014-10-02 16:30:14 -0700 | [diff] [blame] | 170 | public void unregisterHandler(String type) { |
| 171 | handlers.remove(type); |
| 172 | } |
| 173 | |
| 174 | private MessageHandler getMessageHandler(String type) { |
| 175 | return handlers.get(type); |
| 176 | } |
| 177 | |
| 178 | private void startAcceptingConnections() throws InterruptedException { |
| 179 | ServerBootstrap b = new ServerBootstrap(); |
Madan Jampani | 86ed055 | 2014-10-03 16:45:42 -0700 | [diff] [blame] | 180 | b.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 32 * 1024); |
Madan Jampani | ddf7622 | 2014-10-04 23:48:44 -0700 | [diff] [blame] | 181 | b.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024); |
| 182 | // TODO: Need JVM options to configure PooledByteBufAllocator. |
Madan Jampani | ab6d311 | 2014-10-02 16:30:14 -0700 | [diff] [blame] | 183 | b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); |
Madan Jampani | 824a7c1 | 2014-10-21 09:46:15 -0700 | [diff] [blame] | 184 | b.group(serverGroup, clientGroup) |
| 185 | .channel(serverChannelClass) |
Madan Jampani | ab6d311 | 2014-10-02 16:30:14 -0700 | [diff] [blame] | 186 | .childHandler(new OnosCommunicationChannelInitializer()) |
| 187 | .option(ChannelOption.SO_BACKLOG, 128) |
| 188 | .childOption(ChannelOption.SO_KEEPALIVE, true); |
| 189 | |
| 190 | // Bind and start to accept incoming connections. |
Madan Jampani | 8710093 | 2014-10-21 16:46:12 -0700 | [diff] [blame] | 191 | b.bind(localEp.port()).sync(); |
Madan Jampani | ab6d311 | 2014-10-02 16:30:14 -0700 | [diff] [blame] | 192 | } |
| 193 | |
| 194 | private class OnosCommunicationChannelFactory |
| 195 | implements KeyedPoolableObjectFactory<Endpoint, Channel> { |
| 196 | |
| 197 | @Override |
| 198 | public void activateObject(Endpoint endpoint, Channel channel) |
| 199 | throws Exception { |
| 200 | } |
| 201 | |
| 202 | @Override |
| 203 | public void destroyObject(Endpoint ep, Channel channel) throws Exception { |
| 204 | channel.close(); |
| 205 | } |
| 206 | |
| 207 | @Override |
| 208 | public Channel makeObject(Endpoint ep) throws Exception { |
Madan Jampani | ddf7622 | 2014-10-04 23:48:44 -0700 | [diff] [blame] | 209 | Bootstrap bootstrap = new Bootstrap(); |
| 210 | bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); |
| 211 | bootstrap.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 32 * 1024); |
| 212 | bootstrap.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024); |
Madan Jampani | 824a7c1 | 2014-10-21 09:46:15 -0700 | [diff] [blame] | 213 | bootstrap.group(clientGroup); |
Madan Jampani | ab6d311 | 2014-10-02 16:30:14 -0700 | [diff] [blame] | 214 | // TODO: Make this faster: |
| 215 | // http://normanmaurer.me/presentations/2014-facebook-eng-netty/slides.html#37.0 |
Madan Jampani | 824a7c1 | 2014-10-21 09:46:15 -0700 | [diff] [blame] | 216 | bootstrap.channel(clientChannelClass); |
Madan Jampani | ddf7622 | 2014-10-04 23:48:44 -0700 | [diff] [blame] | 217 | bootstrap.option(ChannelOption.SO_KEEPALIVE, true); |
| 218 | bootstrap.handler(new OnosCommunicationChannelInitializer()); |
Madan Jampani | ab6d311 | 2014-10-02 16:30:14 -0700 | [diff] [blame] | 219 | // Start the client. |
Madan Jampani | ddf7622 | 2014-10-04 23:48:44 -0700 | [diff] [blame] | 220 | ChannelFuture f = bootstrap.connect(ep.host(), ep.port()).sync(); |
Madan Jampani | ab6d311 | 2014-10-02 16:30:14 -0700 | [diff] [blame] | 221 | return f.channel(); |
| 222 | } |
| 223 | |
| 224 | @Override |
| 225 | public void passivateObject(Endpoint ep, Channel channel) |
| 226 | throws Exception { |
| 227 | } |
| 228 | |
| 229 | @Override |
| 230 | public boolean validateObject(Endpoint ep, Channel channel) { |
| 231 | return channel.isOpen(); |
| 232 | } |
| 233 | } |
| 234 | |
| 235 | private class OnosCommunicationChannelInitializer extends ChannelInitializer<SocketChannel> { |
| 236 | |
Madan Jampani | ddf7622 | 2014-10-04 23:48:44 -0700 | [diff] [blame] | 237 | private final ChannelHandler dispatcher = new InboundMessageDispatcher(); |
Madan Jampani | 53e44e6 | 2014-10-07 12:39:51 -0700 | [diff] [blame] | 238 | private final ChannelHandler encoder = new MessageEncoder(); |
Madan Jampani | ddf7622 | 2014-10-04 23:48:44 -0700 | [diff] [blame] | 239 | |
Madan Jampani | ab6d311 | 2014-10-02 16:30:14 -0700 | [diff] [blame] | 240 | @Override |
| 241 | protected void initChannel(SocketChannel channel) throws Exception { |
| 242 | channel.pipeline() |
Madan Jampani | ddf7622 | 2014-10-04 23:48:44 -0700 | [diff] [blame] | 243 | .addLast("encoder", encoder) |
Madan Jampani | 53e44e6 | 2014-10-07 12:39:51 -0700 | [diff] [blame] | 244 | .addLast("decoder", new MessageDecoder(NettyMessagingService.this)) |
Madan Jampani | ddf7622 | 2014-10-04 23:48:44 -0700 | [diff] [blame] | 245 | .addLast("handler", dispatcher); |
Madan Jampani | ab6d311 | 2014-10-02 16:30:14 -0700 | [diff] [blame] | 246 | } |
| 247 | } |
| 248 | |
Yuta HIGUCHI | e5ca93b | 2014-10-23 09:49:00 -0700 | [diff] [blame] | 249 | private static class WriteTask implements Runnable { |
Madan Jampani | ab6d311 | 2014-10-02 16:30:14 -0700 | [diff] [blame] | 250 | |
Madan Jampani | 86ed055 | 2014-10-03 16:45:42 -0700 | [diff] [blame] | 251 | private final InternalMessage message; |
Madan Jampani | ab6d311 | 2014-10-02 16:30:14 -0700 | [diff] [blame] | 252 | private final Channel channel; |
| 253 | |
Madan Jampani | 86ed055 | 2014-10-03 16:45:42 -0700 | [diff] [blame] | 254 | public WriteTask(Channel channel, InternalMessage message) { |
Madan Jampani | ab6d311 | 2014-10-02 16:30:14 -0700 | [diff] [blame] | 255 | this.channel = channel; |
Madan Jampani | 86ed055 | 2014-10-03 16:45:42 -0700 | [diff] [blame] | 256 | this.message = message; |
Madan Jampani | ab6d311 | 2014-10-02 16:30:14 -0700 | [diff] [blame] | 257 | } |
| 258 | |
| 259 | @Override |
| 260 | public void run() { |
Madan Jampani | ddf7622 | 2014-10-04 23:48:44 -0700 | [diff] [blame] | 261 | channel.writeAndFlush(message, channel.voidPromise()); |
Madan Jampani | ab6d311 | 2014-10-02 16:30:14 -0700 | [diff] [blame] | 262 | } |
| 263 | } |
| 264 | |
Madan Jampani | ddf7622 | 2014-10-04 23:48:44 -0700 | [diff] [blame] | 265 | @ChannelHandler.Sharable |
Madan Jampani | ab6d311 | 2014-10-02 16:30:14 -0700 | [diff] [blame] | 266 | private class InboundMessageDispatcher extends SimpleChannelInboundHandler<InternalMessage> { |
| 267 | |
| 268 | @Override |
| 269 | protected void channelRead0(ChannelHandlerContext ctx, InternalMessage message) throws Exception { |
| 270 | String type = message.type(); |
| 271 | if (type.equals(InternalMessage.REPLY_MESSAGE_TYPE)) { |
| 272 | try { |
Madan Jampani | 24f9efb | 2014-10-24 18:56:23 -0700 | [diff] [blame^] | 273 | SettableFuture<byte[]> futureResponse = |
Madan Jampani | ab6d311 | 2014-10-02 16:30:14 -0700 | [diff] [blame] | 274 | NettyMessagingService.this.responseFutures.getIfPresent(message.id()); |
| 275 | if (futureResponse != null) { |
Madan Jampani | 24f9efb | 2014-10-24 18:56:23 -0700 | [diff] [blame^] | 276 | futureResponse.set(message.payload()); |
Madan Jampani | f1d425a | 2014-10-07 09:52:36 -0700 | [diff] [blame] | 277 | } else { |
| 278 | log.warn("Received a reply. But was unable to locate the request handle"); |
Madan Jampani | ab6d311 | 2014-10-02 16:30:14 -0700 | [diff] [blame] | 279 | } |
Madan Jampani | ab6d311 | 2014-10-02 16:30:14 -0700 | [diff] [blame] | 280 | } finally { |
| 281 | NettyMessagingService.this.responseFutures.invalidate(message.id()); |
| 282 | } |
| 283 | return; |
| 284 | } |
| 285 | MessageHandler handler = NettyMessagingService.this.getMessageHandler(type); |
| 286 | handler.handle(message); |
| 287 | } |
Madan Jampani | 86ed055 | 2014-10-03 16:45:42 -0700 | [diff] [blame] | 288 | |
Madan Jampani | 86ed055 | 2014-10-03 16:45:42 -0700 | [diff] [blame] | 289 | @Override |
| 290 | public void exceptionCaught(ChannelHandlerContext context, Throwable cause) { |
Madan Jampani | 29e5dfd | 2014-10-07 17:26:25 -0700 | [diff] [blame] | 291 | log.error("Exception inside channel handling pipeline.", cause); |
Madan Jampani | 86ed055 | 2014-10-03 16:45:42 -0700 | [diff] [blame] | 292 | context.close(); |
| 293 | } |
Madan Jampani | ab6d311 | 2014-10-02 16:30:14 -0700 | [diff] [blame] | 294 | } |
| 295 | } |