blob: 2f3e039a428454c87afb775538ff2725ca0ec394 [file] [log] [blame]
Madan Jampaniab6d3112014-10-02 16:30:14 -07001package org.onlab.netty;
2
3import java.io.IOException;
4import java.net.UnknownHostException;
5import java.util.concurrent.ConcurrentHashMap;
6import java.util.concurrent.ConcurrentMap;
7import java.util.concurrent.TimeUnit;
8
9import io.netty.bootstrap.Bootstrap;
10import io.netty.bootstrap.ServerBootstrap;
11import io.netty.buffer.PooledByteBufAllocator;
12import io.netty.channel.Channel;
13import io.netty.channel.ChannelFuture;
Madan Jampaniddf76222014-10-04 23:48:44 -070014import io.netty.channel.ChannelHandler;
Madan Jampaniab6d3112014-10-02 16:30:14 -070015import io.netty.channel.ChannelHandlerContext;
16import io.netty.channel.ChannelInitializer;
17import io.netty.channel.ChannelOption;
18import io.netty.channel.EventLoopGroup;
Madan Jampani824a7c12014-10-21 09:46:15 -070019import io.netty.channel.ServerChannel;
Madan Jampaniab6d3112014-10-02 16:30:14 -070020import io.netty.channel.SimpleChannelInboundHandler;
Madan Jampani824a7c12014-10-21 09:46:15 -070021import io.netty.channel.epoll.EpollEventLoopGroup;
22import io.netty.channel.epoll.EpollServerSocketChannel;
23import io.netty.channel.epoll.EpollSocketChannel;
Madan Jampaniab6d3112014-10-02 16:30:14 -070024import io.netty.channel.nio.NioEventLoopGroup;
25import io.netty.channel.socket.SocketChannel;
26import io.netty.channel.socket.nio.NioServerSocketChannel;
27import io.netty.channel.socket.nio.NioSocketChannel;
28
29import org.apache.commons.lang.math.RandomUtils;
Madan Jampaniab6d3112014-10-02 16:30:14 -070030import org.apache.commons.pool.KeyedPoolableObjectFactory;
31import org.apache.commons.pool.impl.GenericKeyedObjectPool;
32import org.slf4j.Logger;
33import org.slf4j.LoggerFactory;
34
35import com.google.common.cache.Cache;
36import com.google.common.cache.CacheBuilder;
37
38/**
39 * A Netty based implementation of MessagingService.
40 */
41public class NettyMessagingService implements MessagingService {
42
43 private final Logger log = LoggerFactory.getLogger(getClass());
44
Madan Jampaniab6d3112014-10-02 16:30:14 -070045 private final int port;
Madan Jampaniddf76222014-10-04 23:48:44 -070046 private final Endpoint localEp;
Madan Jampaniab6d3112014-10-02 16:30:14 -070047 private final ConcurrentMap<String, MessageHandler> handlers = new ConcurrentHashMap<>();
Madan Jampani53e44e62014-10-07 12:39:51 -070048 private final Cache<Long, AsyncResponse> responseFutures = CacheBuilder.newBuilder()
Madan Jampaniddf76222014-10-04 23:48:44 -070049 .maximumSize(100000)
50 .weakValues()
51 // TODO: Once the entry expires, notify blocking threads (if any).
52 .expireAfterWrite(10, TimeUnit.MINUTES)
53 .build();
54 private final GenericKeyedObjectPool<Endpoint, Channel> channels
55 = new GenericKeyedObjectPool<Endpoint, Channel>(new OnosCommunicationChannelFactory());
Madan Jampaniab6d3112014-10-02 16:30:14 -070056
Madan Jampani824a7c12014-10-21 09:46:15 -070057 private EventLoopGroup serverGroup;
58 private EventLoopGroup clientGroup;
59 private Class<? extends ServerChannel> serverChannelClass;
60 private Class<? extends Channel> clientChannelClass;
61
Madan Jampani5e83f332014-10-20 15:35:09 -070062 private void initEventLoopGroup() {
Madan Jampani824a7c12014-10-21 09:46:15 -070063 // try Epoll first and if that does work, use nio.
64 // TODO: make this configurable.
65 try {
Madan Jampani99e9fe22014-10-21 13:47:12 -070066 clientGroup = new EpollEventLoopGroup();
67 serverGroup = new EpollEventLoopGroup();
68 serverChannelClass = EpollServerSocketChannel.class;
69 clientChannelClass = EpollSocketChannel.class;
70 return;
Madan Jampani824a7c12014-10-21 09:46:15 -070071 } catch (Throwable t) {
Madan Jampani99e9fe22014-10-21 13:47:12 -070072 log.warn("Failed to initialize native (epoll) transport. Proceeding with nio.", t);
Madan Jampani824a7c12014-10-21 09:46:15 -070073 }
74 clientGroup = new NioEventLoopGroup();
75 serverGroup = new NioEventLoopGroup();
76 serverChannelClass = NioServerSocketChannel.class;
77 clientChannelClass = NioSocketChannel.class;
Madan Jampani5e83f332014-10-20 15:35:09 -070078 }
79
Madan Jampaniab6d3112014-10-02 16:30:14 -070080 public NettyMessagingService() {
81 // TODO: Default port should be configurable.
82 this(8080);
83 }
84
85 // FIXME: Constructor should not throw exceptions.
86 public NettyMessagingService(int port) {
87 this.port = port;
88 try {
89 localEp = new Endpoint(java.net.InetAddress.getLocalHost().getHostName(), port);
90 } catch (UnknownHostException e) {
91 // bailing out.
92 throw new RuntimeException(e);
93 }
94 }
95
96 public void activate() throws Exception {
Madan Jampani86ed0552014-10-03 16:45:42 -070097 channels.setTestOnBorrow(true);
98 channels.setTestOnReturn(true);
Madan Jampani5e83f332014-10-20 15:35:09 -070099 initEventLoopGroup();
Madan Jampaniab6d3112014-10-02 16:30:14 -0700100 startAcceptingConnections();
101 }
102
103 public void deactivate() throws Exception {
104 channels.close();
Madan Jampani824a7c12014-10-21 09:46:15 -0700105 serverGroup.shutdownGracefully();
106 clientGroup.shutdownGracefully();
Madan Jampaniab6d3112014-10-02 16:30:14 -0700107 }
108
109 @Override
Madan Jampani53e44e62014-10-07 12:39:51 -0700110 public void sendAsync(Endpoint ep, String type, byte[] payload) throws IOException {
Madan Jampaniab6d3112014-10-02 16:30:14 -0700111 InternalMessage message = new InternalMessage.Builder(this)
112 .withId(RandomUtils.nextLong())
113 .withSender(localEp)
114 .withType(type)
115 .withPayload(payload)
116 .build();
117 sendAsync(ep, message);
118 }
119
120 protected void sendAsync(Endpoint ep, InternalMessage message) throws IOException {
121 Channel channel = null;
122 try {
Madan Jampani86ed0552014-10-03 16:45:42 -0700123 try {
124 channel = channels.borrowObject(ep);
125 channel.eventLoop().execute(new WriteTask(channel, message));
126 } finally {
127 channels.returnObject(ep, channel);
128 }
Madan Jampaniab6d3112014-10-02 16:30:14 -0700129 } catch (Exception e) {
130 throw new IOException(e);
Madan Jampaniab6d3112014-10-02 16:30:14 -0700131 }
132 }
133
134 @Override
Madan Jampani53e44e62014-10-07 12:39:51 -0700135 public Response sendAndReceive(Endpoint ep, String type, byte[] payload)
Madan Jampaniab6d3112014-10-02 16:30:14 -0700136 throws IOException {
Madan Jampani53e44e62014-10-07 12:39:51 -0700137 AsyncResponse futureResponse = new AsyncResponse();
Madan Jampaniab6d3112014-10-02 16:30:14 -0700138 Long messageId = RandomUtils.nextLong();
139 responseFutures.put(messageId, futureResponse);
140 InternalMessage message = new InternalMessage.Builder(this)
141 .withId(messageId)
142 .withSender(localEp)
143 .withType(type)
144 .withPayload(payload)
145 .build();
146 sendAsync(ep, message);
147 return futureResponse;
148 }
149
150 @Override
151 public void registerHandler(String type, MessageHandler handler) {
152 // TODO: Is this the right semantics for handler registration?
153 handlers.putIfAbsent(type, handler);
154 }
155
156 public void unregisterHandler(String type) {
157 handlers.remove(type);
158 }
159
160 private MessageHandler getMessageHandler(String type) {
161 return handlers.get(type);
162 }
163
164 private void startAcceptingConnections() throws InterruptedException {
165 ServerBootstrap b = new ServerBootstrap();
Madan Jampani86ed0552014-10-03 16:45:42 -0700166 b.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 32 * 1024);
Madan Jampaniddf76222014-10-04 23:48:44 -0700167 b.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024);
168 // TODO: Need JVM options to configure PooledByteBufAllocator.
Madan Jampaniab6d3112014-10-02 16:30:14 -0700169 b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
Madan Jampani824a7c12014-10-21 09:46:15 -0700170 b.group(serverGroup, clientGroup)
171 .channel(serverChannelClass)
Madan Jampaniab6d3112014-10-02 16:30:14 -0700172 .childHandler(new OnosCommunicationChannelInitializer())
173 .option(ChannelOption.SO_BACKLOG, 128)
174 .childOption(ChannelOption.SO_KEEPALIVE, true);
175
176 // Bind and start to accept incoming connections.
177 b.bind(port).sync();
178 }
179
180 private class OnosCommunicationChannelFactory
181 implements KeyedPoolableObjectFactory<Endpoint, Channel> {
182
183 @Override
184 public void activateObject(Endpoint endpoint, Channel channel)
185 throws Exception {
186 }
187
188 @Override
189 public void destroyObject(Endpoint ep, Channel channel) throws Exception {
190 channel.close();
191 }
192
193 @Override
194 public Channel makeObject(Endpoint ep) throws Exception {
Madan Jampaniddf76222014-10-04 23:48:44 -0700195 Bootstrap bootstrap = new Bootstrap();
196 bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
197 bootstrap.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 32 * 1024);
198 bootstrap.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024);
Madan Jampani824a7c12014-10-21 09:46:15 -0700199 bootstrap.group(clientGroup);
Madan Jampaniab6d3112014-10-02 16:30:14 -0700200 // TODO: Make this faster:
201 // http://normanmaurer.me/presentations/2014-facebook-eng-netty/slides.html#37.0
Madan Jampani824a7c12014-10-21 09:46:15 -0700202 bootstrap.channel(clientChannelClass);
Madan Jampaniddf76222014-10-04 23:48:44 -0700203 bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
204 bootstrap.handler(new OnosCommunicationChannelInitializer());
Madan Jampaniab6d3112014-10-02 16:30:14 -0700205 // Start the client.
Madan Jampaniddf76222014-10-04 23:48:44 -0700206 ChannelFuture f = bootstrap.connect(ep.host(), ep.port()).sync();
Madan Jampaniab6d3112014-10-02 16:30:14 -0700207 return f.channel();
208 }
209
210 @Override
211 public void passivateObject(Endpoint ep, Channel channel)
212 throws Exception {
213 }
214
215 @Override
216 public boolean validateObject(Endpoint ep, Channel channel) {
217 return channel.isOpen();
218 }
219 }
220
221 private class OnosCommunicationChannelInitializer extends ChannelInitializer<SocketChannel> {
222
Madan Jampaniddf76222014-10-04 23:48:44 -0700223 private final ChannelHandler dispatcher = new InboundMessageDispatcher();
Madan Jampani53e44e62014-10-07 12:39:51 -0700224 private final ChannelHandler encoder = new MessageEncoder();
Madan Jampaniddf76222014-10-04 23:48:44 -0700225
Madan Jampaniab6d3112014-10-02 16:30:14 -0700226 @Override
227 protected void initChannel(SocketChannel channel) throws Exception {
228 channel.pipeline()
Madan Jampaniddf76222014-10-04 23:48:44 -0700229 .addLast("encoder", encoder)
Madan Jampani53e44e62014-10-07 12:39:51 -0700230 .addLast("decoder", new MessageDecoder(NettyMessagingService.this))
Madan Jampaniddf76222014-10-04 23:48:44 -0700231 .addLast("handler", dispatcher);
Madan Jampaniab6d3112014-10-02 16:30:14 -0700232 }
233 }
234
235 private class WriteTask implements Runnable {
236
Madan Jampani86ed0552014-10-03 16:45:42 -0700237 private final InternalMessage message;
Madan Jampaniab6d3112014-10-02 16:30:14 -0700238 private final Channel channel;
239
Madan Jampani86ed0552014-10-03 16:45:42 -0700240 public WriteTask(Channel channel, InternalMessage message) {
Madan Jampaniab6d3112014-10-02 16:30:14 -0700241 this.channel = channel;
Madan Jampani86ed0552014-10-03 16:45:42 -0700242 this.message = message;
Madan Jampaniab6d3112014-10-02 16:30:14 -0700243 }
244
245 @Override
246 public void run() {
Madan Jampaniddf76222014-10-04 23:48:44 -0700247 channel.writeAndFlush(message, channel.voidPromise());
Madan Jampaniab6d3112014-10-02 16:30:14 -0700248 }
249 }
250
Madan Jampaniddf76222014-10-04 23:48:44 -0700251 @ChannelHandler.Sharable
Madan Jampaniab6d3112014-10-02 16:30:14 -0700252 private class InboundMessageDispatcher extends SimpleChannelInboundHandler<InternalMessage> {
253
254 @Override
255 protected void channelRead0(ChannelHandlerContext ctx, InternalMessage message) throws Exception {
256 String type = message.type();
257 if (type.equals(InternalMessage.REPLY_MESSAGE_TYPE)) {
258 try {
Madan Jampani53e44e62014-10-07 12:39:51 -0700259 AsyncResponse futureResponse =
Madan Jampaniab6d3112014-10-02 16:30:14 -0700260 NettyMessagingService.this.responseFutures.getIfPresent(message.id());
261 if (futureResponse != null) {
262 futureResponse.setResponse(message.payload());
Madan Jampanif1d425a2014-10-07 09:52:36 -0700263 } else {
264 log.warn("Received a reply. But was unable to locate the request handle");
Madan Jampaniab6d3112014-10-02 16:30:14 -0700265 }
Madan Jampaniab6d3112014-10-02 16:30:14 -0700266 } finally {
267 NettyMessagingService.this.responseFutures.invalidate(message.id());
268 }
269 return;
270 }
271 MessageHandler handler = NettyMessagingService.this.getMessageHandler(type);
272 handler.handle(message);
273 }
Madan Jampani86ed0552014-10-03 16:45:42 -0700274
Madan Jampani86ed0552014-10-03 16:45:42 -0700275 @Override
276 public void exceptionCaught(ChannelHandlerContext context, Throwable cause) {
Madan Jampani29e5dfd2014-10-07 17:26:25 -0700277 log.error("Exception inside channel handling pipeline.", cause);
Madan Jampani86ed0552014-10-03 16:45:42 -0700278 context.close();
279 }
Madan Jampaniab6d3112014-10-02 16:30:14 -0700280 }
281}