blob: 26d835d8225e37a13b81e4e4eceb8f38a33f1ac9 [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 Jampaniddf76222014-10-04 23:48:44 -070045 private final Endpoint localEp;
Madan Jampaniab6d3112014-10-02 16:30:14 -070046 private final ConcurrentMap<String, MessageHandler> handlers = new ConcurrentHashMap<>();
Madan Jampani53e44e62014-10-07 12:39:51 -070047 private final Cache<Long, AsyncResponse> responseFutures = CacheBuilder.newBuilder()
Madan Jampaniddf76222014-10-04 23:48:44 -070048 .maximumSize(100000)
49 .weakValues()
50 // TODO: Once the entry expires, notify blocking threads (if any).
51 .expireAfterWrite(10, TimeUnit.MINUTES)
52 .build();
53 private final GenericKeyedObjectPool<Endpoint, Channel> channels
54 = new GenericKeyedObjectPool<Endpoint, Channel>(new OnosCommunicationChannelFactory());
Madan Jampaniab6d3112014-10-02 16:30:14 -070055
Madan Jampani824a7c12014-10-21 09:46:15 -070056 private EventLoopGroup serverGroup;
57 private EventLoopGroup clientGroup;
58 private Class<? extends ServerChannel> serverChannelClass;
59 private Class<? extends Channel> clientChannelClass;
60
Madan Jampani5e83f332014-10-20 15:35:09 -070061 private void initEventLoopGroup() {
Madan Jampani824a7c12014-10-21 09:46:15 -070062 // try Epoll first and if that does work, use nio.
63 // TODO: make this configurable.
64 try {
Madan Jampani99e9fe22014-10-21 13:47:12 -070065 clientGroup = new EpollEventLoopGroup();
66 serverGroup = new EpollEventLoopGroup();
67 serverChannelClass = EpollServerSocketChannel.class;
68 clientChannelClass = EpollSocketChannel.class;
69 return;
Madan Jampani824a7c12014-10-21 09:46:15 -070070 } catch (Throwable t) {
Madan Jampani99e9fe22014-10-21 13:47:12 -070071 log.warn("Failed to initialize native (epoll) transport. Proceeding with nio.", t);
Madan Jampani824a7c12014-10-21 09:46:15 -070072 }
73 clientGroup = new NioEventLoopGroup();
74 serverGroup = new NioEventLoopGroup();
75 serverChannelClass = NioServerSocketChannel.class;
76 clientChannelClass = NioSocketChannel.class;
Madan Jampani5e83f332014-10-20 15:35:09 -070077 }
78
Madan Jampani87100932014-10-21 16:46:12 -070079 public NettyMessagingService(String ip, int port) {
80 localEp = new Endpoint(ip, port);
81 }
82
Madan Jampaniab6d3112014-10-02 16:30:14 -070083 public NettyMessagingService() {
84 // TODO: Default port should be configurable.
85 this(8080);
86 }
87
88 // FIXME: Constructor should not throw exceptions.
89 public NettyMessagingService(int port) {
Madan Jampaniab6d3112014-10-02 16:30:14 -070090 try {
91 localEp = new Endpoint(java.net.InetAddress.getLocalHost().getHostName(), port);
92 } catch (UnknownHostException e) {
93 // bailing out.
94 throw new RuntimeException(e);
95 }
96 }
97
98 public void activate() throws Exception {
Madan Jampani86ed0552014-10-03 16:45:42 -070099 channels.setTestOnBorrow(true);
100 channels.setTestOnReturn(true);
Madan Jampani5e83f332014-10-20 15:35:09 -0700101 initEventLoopGroup();
Madan Jampaniab6d3112014-10-02 16:30:14 -0700102 startAcceptingConnections();
103 }
104
105 public void deactivate() throws Exception {
106 channels.close();
Madan Jampani824a7c12014-10-21 09:46:15 -0700107 serverGroup.shutdownGracefully();
108 clientGroup.shutdownGracefully();
Madan Jampaniab6d3112014-10-02 16:30:14 -0700109 }
110
Madan Jampani87100932014-10-21 16:46:12 -0700111 /**
112 * Returns the local endpoint for this instance.
113 * @return local end point.
114 */
115 public Endpoint localEp() {
116 return localEp;
117 }
118
Madan Jampaniab6d3112014-10-02 16:30:14 -0700119 @Override
Madan Jampani53e44e62014-10-07 12:39:51 -0700120 public void sendAsync(Endpoint ep, String type, byte[] payload) throws IOException {
Madan Jampaniab6d3112014-10-02 16:30:14 -0700121 InternalMessage message = new InternalMessage.Builder(this)
122 .withId(RandomUtils.nextLong())
123 .withSender(localEp)
124 .withType(type)
125 .withPayload(payload)
126 .build();
127 sendAsync(ep, message);
128 }
129
130 protected void sendAsync(Endpoint ep, InternalMessage message) throws IOException {
131 Channel channel = null;
132 try {
Madan Jampani86ed0552014-10-03 16:45:42 -0700133 try {
134 channel = channels.borrowObject(ep);
135 channel.eventLoop().execute(new WriteTask(channel, message));
136 } finally {
137 channels.returnObject(ep, channel);
138 }
Madan Jampaniab6d3112014-10-02 16:30:14 -0700139 } catch (Exception e) {
Madan Jampani87100932014-10-21 16:46:12 -0700140 throw new IOException("Failed to send message to " + ep.toString(), e);
Madan Jampaniab6d3112014-10-02 16:30:14 -0700141 }
142 }
143
144 @Override
Madan Jampani53e44e62014-10-07 12:39:51 -0700145 public Response sendAndReceive(Endpoint ep, String type, byte[] payload)
Madan Jampaniab6d3112014-10-02 16:30:14 -0700146 throws IOException {
Madan Jampani53e44e62014-10-07 12:39:51 -0700147 AsyncResponse futureResponse = new AsyncResponse();
Madan Jampaniab6d3112014-10-02 16:30:14 -0700148 Long messageId = RandomUtils.nextLong();
149 responseFutures.put(messageId, futureResponse);
150 InternalMessage message = new InternalMessage.Builder(this)
151 .withId(messageId)
152 .withSender(localEp)
153 .withType(type)
154 .withPayload(payload)
155 .build();
156 sendAsync(ep, message);
157 return futureResponse;
158 }
159
160 @Override
161 public void registerHandler(String type, MessageHandler handler) {
162 // TODO: Is this the right semantics for handler registration?
163 handlers.putIfAbsent(type, handler);
164 }
165
Yuta HIGUCHIe5ca93b2014-10-23 09:49:00 -0700166 @Override
Madan Jampaniab6d3112014-10-02 16:30:14 -0700167 public void unregisterHandler(String type) {
168 handlers.remove(type);
169 }
170
171 private MessageHandler getMessageHandler(String type) {
172 return handlers.get(type);
173 }
174
175 private void startAcceptingConnections() throws InterruptedException {
176 ServerBootstrap b = new ServerBootstrap();
Madan Jampani86ed0552014-10-03 16:45:42 -0700177 b.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 32 * 1024);
Madan Jampaniddf76222014-10-04 23:48:44 -0700178 b.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024);
179 // TODO: Need JVM options to configure PooledByteBufAllocator.
Madan Jampaniab6d3112014-10-02 16:30:14 -0700180 b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
Madan Jampani824a7c12014-10-21 09:46:15 -0700181 b.group(serverGroup, clientGroup)
182 .channel(serverChannelClass)
Madan Jampaniab6d3112014-10-02 16:30:14 -0700183 .childHandler(new OnosCommunicationChannelInitializer())
184 .option(ChannelOption.SO_BACKLOG, 128)
185 .childOption(ChannelOption.SO_KEEPALIVE, true);
186
187 // Bind and start to accept incoming connections.
Madan Jampani87100932014-10-21 16:46:12 -0700188 b.bind(localEp.port()).sync();
Madan Jampaniab6d3112014-10-02 16:30:14 -0700189 }
190
191 private class OnosCommunicationChannelFactory
192 implements KeyedPoolableObjectFactory<Endpoint, Channel> {
193
194 @Override
195 public void activateObject(Endpoint endpoint, Channel channel)
196 throws Exception {
197 }
198
199 @Override
200 public void destroyObject(Endpoint ep, Channel channel) throws Exception {
201 channel.close();
202 }
203
204 @Override
205 public Channel makeObject(Endpoint ep) throws Exception {
Madan Jampaniddf76222014-10-04 23:48:44 -0700206 Bootstrap bootstrap = new Bootstrap();
207 bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
208 bootstrap.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 32 * 1024);
209 bootstrap.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024);
Madan Jampani824a7c12014-10-21 09:46:15 -0700210 bootstrap.group(clientGroup);
Madan Jampaniab6d3112014-10-02 16:30:14 -0700211 // TODO: Make this faster:
212 // http://normanmaurer.me/presentations/2014-facebook-eng-netty/slides.html#37.0
Madan Jampani824a7c12014-10-21 09:46:15 -0700213 bootstrap.channel(clientChannelClass);
Madan Jampaniddf76222014-10-04 23:48:44 -0700214 bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
215 bootstrap.handler(new OnosCommunicationChannelInitializer());
Madan Jampaniab6d3112014-10-02 16:30:14 -0700216 // Start the client.
Madan Jampaniddf76222014-10-04 23:48:44 -0700217 ChannelFuture f = bootstrap.connect(ep.host(), ep.port()).sync();
Madan Jampaniab6d3112014-10-02 16:30:14 -0700218 return f.channel();
219 }
220
221 @Override
222 public void passivateObject(Endpoint ep, Channel channel)
223 throws Exception {
224 }
225
226 @Override
227 public boolean validateObject(Endpoint ep, Channel channel) {
228 return channel.isOpen();
229 }
230 }
231
232 private class OnosCommunicationChannelInitializer extends ChannelInitializer<SocketChannel> {
233
Madan Jampaniddf76222014-10-04 23:48:44 -0700234 private final ChannelHandler dispatcher = new InboundMessageDispatcher();
Madan Jampani53e44e62014-10-07 12:39:51 -0700235 private final ChannelHandler encoder = new MessageEncoder();
Madan Jampaniddf76222014-10-04 23:48:44 -0700236
Madan Jampaniab6d3112014-10-02 16:30:14 -0700237 @Override
238 protected void initChannel(SocketChannel channel) throws Exception {
239 channel.pipeline()
Madan Jampaniddf76222014-10-04 23:48:44 -0700240 .addLast("encoder", encoder)
Madan Jampani53e44e62014-10-07 12:39:51 -0700241 .addLast("decoder", new MessageDecoder(NettyMessagingService.this))
Madan Jampaniddf76222014-10-04 23:48:44 -0700242 .addLast("handler", dispatcher);
Madan Jampaniab6d3112014-10-02 16:30:14 -0700243 }
244 }
245
Yuta HIGUCHIe5ca93b2014-10-23 09:49:00 -0700246 private static class WriteTask implements Runnable {
Madan Jampaniab6d3112014-10-02 16:30:14 -0700247
Madan Jampani86ed0552014-10-03 16:45:42 -0700248 private final InternalMessage message;
Madan Jampaniab6d3112014-10-02 16:30:14 -0700249 private final Channel channel;
250
Madan Jampani86ed0552014-10-03 16:45:42 -0700251 public WriteTask(Channel channel, InternalMessage message) {
Madan Jampaniab6d3112014-10-02 16:30:14 -0700252 this.channel = channel;
Madan Jampani86ed0552014-10-03 16:45:42 -0700253 this.message = message;
Madan Jampaniab6d3112014-10-02 16:30:14 -0700254 }
255
256 @Override
257 public void run() {
Madan Jampaniddf76222014-10-04 23:48:44 -0700258 channel.writeAndFlush(message, channel.voidPromise());
Madan Jampaniab6d3112014-10-02 16:30:14 -0700259 }
260 }
261
Madan Jampaniddf76222014-10-04 23:48:44 -0700262 @ChannelHandler.Sharable
Madan Jampaniab6d3112014-10-02 16:30:14 -0700263 private class InboundMessageDispatcher extends SimpleChannelInboundHandler<InternalMessage> {
264
265 @Override
266 protected void channelRead0(ChannelHandlerContext ctx, InternalMessage message) throws Exception {
267 String type = message.type();
268 if (type.equals(InternalMessage.REPLY_MESSAGE_TYPE)) {
269 try {
Madan Jampani53e44e62014-10-07 12:39:51 -0700270 AsyncResponse futureResponse =
Madan Jampaniab6d3112014-10-02 16:30:14 -0700271 NettyMessagingService.this.responseFutures.getIfPresent(message.id());
272 if (futureResponse != null) {
273 futureResponse.setResponse(message.payload());
Madan Jampanif1d425a2014-10-07 09:52:36 -0700274 } else {
275 log.warn("Received a reply. But was unable to locate the request handle");
Madan Jampaniab6d3112014-10-02 16:30:14 -0700276 }
Madan Jampaniab6d3112014-10-02 16:30:14 -0700277 } finally {
278 NettyMessagingService.this.responseFutures.invalidate(message.id());
279 }
280 return;
281 }
282 MessageHandler handler = NettyMessagingService.this.getMessageHandler(type);
283 handler.handle(message);
284 }
Madan Jampani86ed0552014-10-03 16:45:42 -0700285
Madan Jampani86ed0552014-10-03 16:45:42 -0700286 @Override
287 public void exceptionCaught(ChannelHandlerContext context, Throwable cause) {
Madan Jampani29e5dfd2014-10-07 17:26:25 -0700288 log.error("Exception inside channel handling pipeline.", cause);
Madan Jampani86ed0552014-10-03 16:45:42 -0700289 context.close();
290 }
Madan Jampaniab6d3112014-10-02 16:30:14 -0700291 }
292}