blob: 5ef17687496ff77183f96d5cce43fe2079e348bf [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
166 public void unregisterHandler(String type) {
167 handlers.remove(type);
168 }
169
170 private MessageHandler getMessageHandler(String type) {
171 return handlers.get(type);
172 }
173
174 private void startAcceptingConnections() throws InterruptedException {
175 ServerBootstrap b = new ServerBootstrap();
Madan Jampani86ed0552014-10-03 16:45:42 -0700176 b.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 32 * 1024);
Madan Jampaniddf76222014-10-04 23:48:44 -0700177 b.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024);
178 // TODO: Need JVM options to configure PooledByteBufAllocator.
Madan Jampaniab6d3112014-10-02 16:30:14 -0700179 b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
Madan Jampani824a7c12014-10-21 09:46:15 -0700180 b.group(serverGroup, clientGroup)
181 .channel(serverChannelClass)
Madan Jampaniab6d3112014-10-02 16:30:14 -0700182 .childHandler(new OnosCommunicationChannelInitializer())
183 .option(ChannelOption.SO_BACKLOG, 128)
184 .childOption(ChannelOption.SO_KEEPALIVE, true);
185
186 // Bind and start to accept incoming connections.
Madan Jampani87100932014-10-21 16:46:12 -0700187 b.bind(localEp.port()).sync();
Madan Jampaniab6d3112014-10-02 16:30:14 -0700188 }
189
190 private class OnosCommunicationChannelFactory
191 implements KeyedPoolableObjectFactory<Endpoint, Channel> {
192
193 @Override
194 public void activateObject(Endpoint endpoint, Channel channel)
195 throws Exception {
196 }
197
198 @Override
199 public void destroyObject(Endpoint ep, Channel channel) throws Exception {
200 channel.close();
201 }
202
203 @Override
204 public Channel makeObject(Endpoint ep) throws Exception {
Madan Jampaniddf76222014-10-04 23:48:44 -0700205 Bootstrap bootstrap = new Bootstrap();
206 bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
207 bootstrap.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 32 * 1024);
208 bootstrap.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024);
Madan Jampani824a7c12014-10-21 09:46:15 -0700209 bootstrap.group(clientGroup);
Madan Jampaniab6d3112014-10-02 16:30:14 -0700210 // TODO: Make this faster:
211 // http://normanmaurer.me/presentations/2014-facebook-eng-netty/slides.html#37.0
Madan Jampani824a7c12014-10-21 09:46:15 -0700212 bootstrap.channel(clientChannelClass);
Madan Jampaniddf76222014-10-04 23:48:44 -0700213 bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
214 bootstrap.handler(new OnosCommunicationChannelInitializer());
Madan Jampaniab6d3112014-10-02 16:30:14 -0700215 // Start the client.
Madan Jampaniddf76222014-10-04 23:48:44 -0700216 ChannelFuture f = bootstrap.connect(ep.host(), ep.port()).sync();
Madan Jampaniab6d3112014-10-02 16:30:14 -0700217 return f.channel();
218 }
219
220 @Override
221 public void passivateObject(Endpoint ep, Channel channel)
222 throws Exception {
223 }
224
225 @Override
226 public boolean validateObject(Endpoint ep, Channel channel) {
227 return channel.isOpen();
228 }
229 }
230
231 private class OnosCommunicationChannelInitializer extends ChannelInitializer<SocketChannel> {
232
Madan Jampaniddf76222014-10-04 23:48:44 -0700233 private final ChannelHandler dispatcher = new InboundMessageDispatcher();
Madan Jampani53e44e62014-10-07 12:39:51 -0700234 private final ChannelHandler encoder = new MessageEncoder();
Madan Jampaniddf76222014-10-04 23:48:44 -0700235
Madan Jampaniab6d3112014-10-02 16:30:14 -0700236 @Override
237 protected void initChannel(SocketChannel channel) throws Exception {
238 channel.pipeline()
Madan Jampaniddf76222014-10-04 23:48:44 -0700239 .addLast("encoder", encoder)
Madan Jampani53e44e62014-10-07 12:39:51 -0700240 .addLast("decoder", new MessageDecoder(NettyMessagingService.this))
Madan Jampaniddf76222014-10-04 23:48:44 -0700241 .addLast("handler", dispatcher);
Madan Jampaniab6d3112014-10-02 16:30:14 -0700242 }
243 }
244
245 private class WriteTask implements Runnable {
246
Madan Jampani86ed0552014-10-03 16:45:42 -0700247 private final InternalMessage message;
Madan Jampaniab6d3112014-10-02 16:30:14 -0700248 private final Channel channel;
249
Madan Jampani86ed0552014-10-03 16:45:42 -0700250 public WriteTask(Channel channel, InternalMessage message) {
Madan Jampaniab6d3112014-10-02 16:30:14 -0700251 this.channel = channel;
Madan Jampani86ed0552014-10-03 16:45:42 -0700252 this.message = message;
Madan Jampaniab6d3112014-10-02 16:30:14 -0700253 }
254
255 @Override
256 public void run() {
Madan Jampaniddf76222014-10-04 23:48:44 -0700257 channel.writeAndFlush(message, channel.voidPromise());
Madan Jampaniab6d3112014-10-02 16:30:14 -0700258 }
259 }
260
Madan Jampaniddf76222014-10-04 23:48:44 -0700261 @ChannelHandler.Sharable
Madan Jampaniab6d3112014-10-02 16:30:14 -0700262 private class InboundMessageDispatcher extends SimpleChannelInboundHandler<InternalMessage> {
263
264 @Override
265 protected void channelRead0(ChannelHandlerContext ctx, InternalMessage message) throws Exception {
266 String type = message.type();
267 if (type.equals(InternalMessage.REPLY_MESSAGE_TYPE)) {
268 try {
Madan Jampani53e44e62014-10-07 12:39:51 -0700269 AsyncResponse futureResponse =
Madan Jampaniab6d3112014-10-02 16:30:14 -0700270 NettyMessagingService.this.responseFutures.getIfPresent(message.id());
271 if (futureResponse != null) {
272 futureResponse.setResponse(message.payload());
Madan Jampanif1d425a2014-10-07 09:52:36 -0700273 } else {
274 log.warn("Received a reply. But was unable to locate the request handle");
Madan Jampaniab6d3112014-10-02 16:30:14 -0700275 }
Madan Jampaniab6d3112014-10-02 16:30:14 -0700276 } finally {
277 NettyMessagingService.this.responseFutures.invalidate(message.id());
278 }
279 return;
280 }
281 MessageHandler handler = NettyMessagingService.this.getMessageHandler(type);
282 handler.handle(message);
283 }
Madan Jampani86ed0552014-10-03 16:45:42 -0700284
Madan Jampani86ed0552014-10-03 16:45:42 -0700285 @Override
286 public void exceptionCaught(ChannelHandlerContext context, Throwable cause) {
Madan Jampani29e5dfd2014-10-07 17:26:25 -0700287 log.error("Exception inside channel handling pipeline.", cause);
Madan Jampani86ed0552014-10-03 16:45:42 -0700288 context.close();
289 }
Madan Jampaniab6d3112014-10-02 16:30:14 -0700290 }
291}