blob: 6e5aa89252ec30029e1c9df663d13f940e0d42c8 [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;
Madan Jampani24f9efb2014-10-24 18:56:23 -07008import java.util.concurrent.atomic.AtomicLong;
Madan Jampaniab6d3112014-10-02 16:30:14 -07009
10import io.netty.bootstrap.Bootstrap;
11import io.netty.bootstrap.ServerBootstrap;
12import io.netty.buffer.PooledByteBufAllocator;
13import io.netty.channel.Channel;
14import io.netty.channel.ChannelFuture;
Madan Jampaniddf76222014-10-04 23:48:44 -070015import io.netty.channel.ChannelHandler;
Madan Jampaniab6d3112014-10-02 16:30:14 -070016import io.netty.channel.ChannelHandlerContext;
17import io.netty.channel.ChannelInitializer;
18import io.netty.channel.ChannelOption;
19import io.netty.channel.EventLoopGroup;
Madan Jampani824a7c12014-10-21 09:46:15 -070020import io.netty.channel.ServerChannel;
Madan Jampaniab6d3112014-10-02 16:30:14 -070021import io.netty.channel.SimpleChannelInboundHandler;
Madan Jampani824a7c12014-10-21 09:46:15 -070022import io.netty.channel.epoll.EpollEventLoopGroup;
23import io.netty.channel.epoll.EpollServerSocketChannel;
24import io.netty.channel.epoll.EpollSocketChannel;
Madan Jampaniab6d3112014-10-02 16:30:14 -070025import io.netty.channel.nio.NioEventLoopGroup;
26import io.netty.channel.socket.SocketChannel;
27import io.netty.channel.socket.nio.NioServerSocketChannel;
28import io.netty.channel.socket.nio.NioSocketChannel;
29
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;
Madan Jampani24f9efb2014-10-24 18:56:23 -070037import com.google.common.util.concurrent.ListenableFuture;
38import com.google.common.util.concurrent.SettableFuture;
Madan Jampaniab6d3112014-10-02 16:30:14 -070039
40/**
41 * A Netty based implementation of MessagingService.
42 */
43public class NettyMessagingService implements MessagingService {
44
45 private final Logger log = LoggerFactory.getLogger(getClass());
46
Madan Jampaniddf76222014-10-04 23:48:44 -070047 private final Endpoint localEp;
Madan Jampaniab6d3112014-10-02 16:30:14 -070048 private final ConcurrentMap<String, MessageHandler> handlers = new ConcurrentHashMap<>();
Madan Jampani24f9efb2014-10-24 18:56:23 -070049 private final AtomicLong messageIdGenerator = new AtomicLong(0);
50 private final Cache<Long, SettableFuture<byte[]>> responseFutures = CacheBuilder.newBuilder()
Madan Jampaniddf76222014-10-04 23:48:44 -070051 .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 Jampaniab6d3112014-10-02 16:30:14 -070058
Madan Jampani824a7c12014-10-21 09:46:15 -070059 private EventLoopGroup serverGroup;
60 private EventLoopGroup clientGroup;
61 private Class<? extends ServerChannel> serverChannelClass;
62 private Class<? extends Channel> clientChannelClass;
63
Madan Jampani5e83f332014-10-20 15:35:09 -070064 private void initEventLoopGroup() {
Madan Jampani824a7c12014-10-21 09:46:15 -070065 // try Epoll first and if that does work, use nio.
66 // TODO: make this configurable.
67 try {
Madan Jampani99e9fe22014-10-21 13:47:12 -070068 clientGroup = new EpollEventLoopGroup();
69 serverGroup = new EpollEventLoopGroup();
70 serverChannelClass = EpollServerSocketChannel.class;
71 clientChannelClass = EpollSocketChannel.class;
72 return;
Madan Jampani824a7c12014-10-21 09:46:15 -070073 } catch (Throwable t) {
Madan Jampani99e9fe22014-10-21 13:47:12 -070074 log.warn("Failed to initialize native (epoll) transport. Proceeding with nio.", t);
Madan Jampani824a7c12014-10-21 09:46:15 -070075 }
76 clientGroup = new NioEventLoopGroup();
77 serverGroup = new NioEventLoopGroup();
78 serverChannelClass = NioServerSocketChannel.class;
79 clientChannelClass = NioSocketChannel.class;
Madan Jampani5e83f332014-10-20 15:35:09 -070080 }
81
Madan Jampani87100932014-10-21 16:46:12 -070082 public NettyMessagingService(String ip, int port) {
83 localEp = new Endpoint(ip, port);
84 }
85
Madan Jampaniab6d3112014-10-02 16:30:14 -070086 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 Jampaniab6d3112014-10-02 16:30:14 -070093 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 Jampani86ed0552014-10-03 16:45:42 -0700102 channels.setTestOnBorrow(true);
103 channels.setTestOnReturn(true);
Madan Jampani5e83f332014-10-20 15:35:09 -0700104 initEventLoopGroup();
Madan Jampaniab6d3112014-10-02 16:30:14 -0700105 startAcceptingConnections();
106 }
107
108 public void deactivate() throws Exception {
109 channels.close();
Madan Jampani824a7c12014-10-21 09:46:15 -0700110 serverGroup.shutdownGracefully();
111 clientGroup.shutdownGracefully();
Madan Jampaniab6d3112014-10-02 16:30:14 -0700112 }
113
Madan Jampani87100932014-10-21 16:46:12 -0700114 /**
115 * Returns the local endpoint for this instance.
116 * @return local end point.
117 */
118 public Endpoint localEp() {
119 return localEp;
120 }
121
Madan Jampaniab6d3112014-10-02 16:30:14 -0700122 @Override
Madan Jampani53e44e62014-10-07 12:39:51 -0700123 public void sendAsync(Endpoint ep, String type, byte[] payload) throws IOException {
Madan Jampaniab6d3112014-10-02 16:30:14 -0700124 InternalMessage message = new InternalMessage.Builder(this)
Madan Jampani24f9efb2014-10-24 18:56:23 -0700125 .withId(messageIdGenerator.incrementAndGet())
Madan Jampaniab6d3112014-10-02 16:30:14 -0700126 .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 Jampani86ed0552014-10-03 16:45:42 -0700136 try {
137 channel = channels.borrowObject(ep);
138 channel.eventLoop().execute(new WriteTask(channel, message));
139 } finally {
140 channels.returnObject(ep, channel);
141 }
Madan Jampaniab6d3112014-10-02 16:30:14 -0700142 } catch (Exception e) {
Madan Jampani87100932014-10-21 16:46:12 -0700143 throw new IOException("Failed to send message to " + ep.toString(), e);
Madan Jampaniab6d3112014-10-02 16:30:14 -0700144 }
145 }
146
147 @Override
Madan Jampani24f9efb2014-10-24 18:56:23 -0700148 public ListenableFuture<byte[]> sendAndReceive(Endpoint ep, String type, byte[] payload)
Madan Jampaniab6d3112014-10-02 16:30:14 -0700149 throws IOException {
Madan Jampani24f9efb2014-10-24 18:56:23 -0700150 SettableFuture<byte[]> futureResponse = SettableFuture.create();
151 Long messageId = messageIdGenerator.incrementAndGet();
Madan Jampaniab6d3112014-10-02 16:30:14 -0700152 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 HIGUCHIe5ca93b2014-10-23 09:49:00 -0700169 @Override
Madan Jampaniab6d3112014-10-02 16:30:14 -0700170 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 Jampani86ed0552014-10-03 16:45:42 -0700180 b.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 32 * 1024);
Madan Jampaniddf76222014-10-04 23:48:44 -0700181 b.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024);
182 // TODO: Need JVM options to configure PooledByteBufAllocator.
Madan Jampaniab6d3112014-10-02 16:30:14 -0700183 b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
Madan Jampani824a7c12014-10-21 09:46:15 -0700184 b.group(serverGroup, clientGroup)
185 .channel(serverChannelClass)
Madan Jampaniab6d3112014-10-02 16:30:14 -0700186 .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 Jampani87100932014-10-21 16:46:12 -0700191 b.bind(localEp.port()).sync();
Madan Jampaniab6d3112014-10-02 16:30:14 -0700192 }
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 Jampaniddf76222014-10-04 23:48:44 -0700209 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 Jampani824a7c12014-10-21 09:46:15 -0700213 bootstrap.group(clientGroup);
Madan Jampaniab6d3112014-10-02 16:30:14 -0700214 // TODO: Make this faster:
215 // http://normanmaurer.me/presentations/2014-facebook-eng-netty/slides.html#37.0
Madan Jampani824a7c12014-10-21 09:46:15 -0700216 bootstrap.channel(clientChannelClass);
Madan Jampaniddf76222014-10-04 23:48:44 -0700217 bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
218 bootstrap.handler(new OnosCommunicationChannelInitializer());
Madan Jampaniab6d3112014-10-02 16:30:14 -0700219 // Start the client.
Madan Jampaniddf76222014-10-04 23:48:44 -0700220 ChannelFuture f = bootstrap.connect(ep.host(), ep.port()).sync();
Madan Jampaniab6d3112014-10-02 16:30:14 -0700221 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 Jampaniddf76222014-10-04 23:48:44 -0700237 private final ChannelHandler dispatcher = new InboundMessageDispatcher();
Madan Jampani53e44e62014-10-07 12:39:51 -0700238 private final ChannelHandler encoder = new MessageEncoder();
Madan Jampaniddf76222014-10-04 23:48:44 -0700239
Madan Jampaniab6d3112014-10-02 16:30:14 -0700240 @Override
241 protected void initChannel(SocketChannel channel) throws Exception {
242 channel.pipeline()
Madan Jampaniddf76222014-10-04 23:48:44 -0700243 .addLast("encoder", encoder)
Madan Jampani53e44e62014-10-07 12:39:51 -0700244 .addLast("decoder", new MessageDecoder(NettyMessagingService.this))
Madan Jampaniddf76222014-10-04 23:48:44 -0700245 .addLast("handler", dispatcher);
Madan Jampaniab6d3112014-10-02 16:30:14 -0700246 }
247 }
248
Yuta HIGUCHIe5ca93b2014-10-23 09:49:00 -0700249 private static class WriteTask implements Runnable {
Madan Jampaniab6d3112014-10-02 16:30:14 -0700250
Madan Jampani86ed0552014-10-03 16:45:42 -0700251 private final InternalMessage message;
Madan Jampaniab6d3112014-10-02 16:30:14 -0700252 private final Channel channel;
253
Madan Jampani86ed0552014-10-03 16:45:42 -0700254 public WriteTask(Channel channel, InternalMessage message) {
Madan Jampaniab6d3112014-10-02 16:30:14 -0700255 this.channel = channel;
Madan Jampani86ed0552014-10-03 16:45:42 -0700256 this.message = message;
Madan Jampaniab6d3112014-10-02 16:30:14 -0700257 }
258
259 @Override
260 public void run() {
Madan Jampaniddf76222014-10-04 23:48:44 -0700261 channel.writeAndFlush(message, channel.voidPromise());
Madan Jampaniab6d3112014-10-02 16:30:14 -0700262 }
263 }
264
Madan Jampaniddf76222014-10-04 23:48:44 -0700265 @ChannelHandler.Sharable
Madan Jampaniab6d3112014-10-02 16:30:14 -0700266 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 Jampani24f9efb2014-10-24 18:56:23 -0700273 SettableFuture<byte[]> futureResponse =
Madan Jampaniab6d3112014-10-02 16:30:14 -0700274 NettyMessagingService.this.responseFutures.getIfPresent(message.id());
275 if (futureResponse != null) {
Madan Jampani24f9efb2014-10-24 18:56:23 -0700276 futureResponse.set(message.payload());
Madan Jampanif1d425a2014-10-07 09:52:36 -0700277 } else {
278 log.warn("Received a reply. But was unable to locate the request handle");
Madan Jampaniab6d3112014-10-02 16:30:14 -0700279 }
Madan Jampaniab6d3112014-10-02 16:30:14 -0700280 } 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 Jampani86ed0552014-10-03 16:45:42 -0700288
Madan Jampani86ed0552014-10-03 16:45:42 -0700289 @Override
290 public void exceptionCaught(ChannelHandlerContext context, Throwable cause) {
Madan Jampani29e5dfd2014-10-07 17:26:25 -0700291 log.error("Exception inside channel handling pipeline.", cause);
Madan Jampani86ed0552014-10-03 16:45:42 -0700292 context.close();
293 }
Madan Jampaniab6d3112014-10-02 16:30:14 -0700294 }
295}