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