blob: 9fe62dbdaedefe55f6be49a4a7f093e4e8f36d45 [file] [log] [blame]
Thomas Vachuska24c849c2014-10-27 09:53:05 -07001/*
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07002 * Copyright 2014 Open Networking Laboratory
Thomas Vachuska24c849c2014-10-27 09:53:05 -07003 *
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07004 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
Thomas Vachuska24c849c2014-10-27 09:53:05 -07007 *
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07008 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
Thomas Vachuska24c849c2014-10-27 09:53:05 -070015 */
Madan Jampaniab6d3112014-10-02 16:30:14 -070016package org.onlab.netty;
17
18import java.io.IOException;
19import java.net.UnknownHostException;
20import java.util.concurrent.ConcurrentHashMap;
21import java.util.concurrent.ConcurrentMap;
22import java.util.concurrent.TimeUnit;
Madan Jampani24f9efb2014-10-24 18:56:23 -070023import java.util.concurrent.atomic.AtomicLong;
Madan Jampaniab6d3112014-10-02 16:30:14 -070024
25import io.netty.bootstrap.Bootstrap;
26import io.netty.bootstrap.ServerBootstrap;
27import io.netty.buffer.PooledByteBufAllocator;
28import io.netty.channel.Channel;
29import io.netty.channel.ChannelFuture;
Madan Jampaniddf76222014-10-04 23:48:44 -070030import io.netty.channel.ChannelHandler;
Madan Jampaniab6d3112014-10-02 16:30:14 -070031import io.netty.channel.ChannelHandlerContext;
32import io.netty.channel.ChannelInitializer;
33import io.netty.channel.ChannelOption;
34import io.netty.channel.EventLoopGroup;
Madan Jampani824a7c12014-10-21 09:46:15 -070035import io.netty.channel.ServerChannel;
Madan Jampaniab6d3112014-10-02 16:30:14 -070036import io.netty.channel.SimpleChannelInboundHandler;
Madan Jampani824a7c12014-10-21 09:46:15 -070037import io.netty.channel.epoll.EpollEventLoopGroup;
38import io.netty.channel.epoll.EpollServerSocketChannel;
39import io.netty.channel.epoll.EpollSocketChannel;
Madan Jampaniab6d3112014-10-02 16:30:14 -070040import io.netty.channel.nio.NioEventLoopGroup;
41import io.netty.channel.socket.SocketChannel;
42import io.netty.channel.socket.nio.NioServerSocketChannel;
43import io.netty.channel.socket.nio.NioSocketChannel;
44
Madan Jampaniab6d3112014-10-02 16:30:14 -070045import org.apache.commons.pool.KeyedPoolableObjectFactory;
46import org.apache.commons.pool.impl.GenericKeyedObjectPool;
47import org.slf4j.Logger;
48import org.slf4j.LoggerFactory;
49
50import com.google.common.cache.Cache;
51import com.google.common.cache.CacheBuilder;
Madan Jampani24f9efb2014-10-24 18:56:23 -070052import com.google.common.util.concurrent.ListenableFuture;
53import com.google.common.util.concurrent.SettableFuture;
Madan Jampaniab6d3112014-10-02 16:30:14 -070054
55/**
56 * A Netty based implementation of MessagingService.
57 */
58public class NettyMessagingService implements MessagingService {
59
60 private final Logger log = LoggerFactory.getLogger(getClass());
61
Madan Jampaniddf76222014-10-04 23:48:44 -070062 private final Endpoint localEp;
Madan Jampaniab6d3112014-10-02 16:30:14 -070063 private final ConcurrentMap<String, MessageHandler> handlers = new ConcurrentHashMap<>();
Madan Jampani24f9efb2014-10-24 18:56:23 -070064 private final AtomicLong messageIdGenerator = new AtomicLong(0);
65 private final Cache<Long, SettableFuture<byte[]>> responseFutures = CacheBuilder.newBuilder()
Madan Jampaniddf76222014-10-04 23:48:44 -070066 .maximumSize(100000)
Madan Jampaniddf76222014-10-04 23:48:44 -070067 // TODO: Once the entry expires, notify blocking threads (if any).
68 .expireAfterWrite(10, TimeUnit.MINUTES)
69 .build();
70 private final GenericKeyedObjectPool<Endpoint, Channel> channels
71 = new GenericKeyedObjectPool<Endpoint, Channel>(new OnosCommunicationChannelFactory());
Madan Jampaniab6d3112014-10-02 16:30:14 -070072
Madan Jampani824a7c12014-10-21 09:46:15 -070073 private EventLoopGroup serverGroup;
74 private EventLoopGroup clientGroup;
75 private Class<? extends ServerChannel> serverChannelClass;
76 private Class<? extends Channel> clientChannelClass;
77
Madan Jampani5e83f332014-10-20 15:35:09 -070078 private void initEventLoopGroup() {
Madan Jampani824a7c12014-10-21 09:46:15 -070079 // try Epoll first and if that does work, use nio.
80 // TODO: make this configurable.
81 try {
Madan Jampani99e9fe22014-10-21 13:47:12 -070082 clientGroup = new EpollEventLoopGroup();
83 serverGroup = new EpollEventLoopGroup();
84 serverChannelClass = EpollServerSocketChannel.class;
85 clientChannelClass = EpollSocketChannel.class;
86 return;
Madan Jampani824a7c12014-10-21 09:46:15 -070087 } catch (Throwable t) {
Madan Jampanicfbc0542014-10-24 20:38:07 -070088 log.warn("Failed to initialize native (epoll) transport. Reason: {}. Proceeding with nio.", t.getMessage());
Madan Jampani824a7c12014-10-21 09:46:15 -070089 }
90 clientGroup = new NioEventLoopGroup();
91 serverGroup = new NioEventLoopGroup();
92 serverChannelClass = NioServerSocketChannel.class;
93 clientChannelClass = NioSocketChannel.class;
Madan Jampani5e83f332014-10-20 15:35:09 -070094 }
95
Madan Jampani87100932014-10-21 16:46:12 -070096 public NettyMessagingService(String ip, int port) {
97 localEp = new Endpoint(ip, port);
98 }
99
Madan Jampaniab6d3112014-10-02 16:30:14 -0700100 public NettyMessagingService() {
101 // TODO: Default port should be configurable.
102 this(8080);
103 }
104
105 // FIXME: Constructor should not throw exceptions.
106 public NettyMessagingService(int port) {
Madan Jampaniab6d3112014-10-02 16:30:14 -0700107 try {
108 localEp = new Endpoint(java.net.InetAddress.getLocalHost().getHostName(), port);
109 } catch (UnknownHostException e) {
110 // bailing out.
111 throw new RuntimeException(e);
112 }
113 }
114
115 public void activate() throws Exception {
Madan Jampani86ed0552014-10-03 16:45:42 -0700116 channels.setTestOnBorrow(true);
117 channels.setTestOnReturn(true);
Madan Jampani5e83f332014-10-20 15:35:09 -0700118 initEventLoopGroup();
Madan Jampaniab6d3112014-10-02 16:30:14 -0700119 startAcceptingConnections();
120 }
121
122 public void deactivate() throws Exception {
123 channels.close();
Madan Jampani824a7c12014-10-21 09:46:15 -0700124 serverGroup.shutdownGracefully();
125 clientGroup.shutdownGracefully();
Madan Jampaniab6d3112014-10-02 16:30:14 -0700126 }
127
Madan Jampani87100932014-10-21 16:46:12 -0700128 /**
129 * Returns the local endpoint for this instance.
130 * @return local end point.
131 */
132 public Endpoint localEp() {
133 return localEp;
134 }
135
Madan Jampaniab6d3112014-10-02 16:30:14 -0700136 @Override
Madan Jampani53e44e62014-10-07 12:39:51 -0700137 public void sendAsync(Endpoint ep, String type, byte[] payload) throws IOException {
Madan Jampaniab6d3112014-10-02 16:30:14 -0700138 InternalMessage message = new InternalMessage.Builder(this)
Madan Jampani24f9efb2014-10-24 18:56:23 -0700139 .withId(messageIdGenerator.incrementAndGet())
Madan Jampaniab6d3112014-10-02 16:30:14 -0700140 .withSender(localEp)
141 .withType(type)
142 .withPayload(payload)
143 .build();
144 sendAsync(ep, message);
145 }
146
147 protected void sendAsync(Endpoint ep, InternalMessage message) throws IOException {
148 Channel channel = null;
149 try {
Madan Jampani86ed0552014-10-03 16:45:42 -0700150 try {
151 channel = channels.borrowObject(ep);
152 channel.eventLoop().execute(new WriteTask(channel, message));
153 } finally {
154 channels.returnObject(ep, channel);
155 }
Madan Jampaniab6d3112014-10-02 16:30:14 -0700156 } catch (Exception e) {
Madan Jampani87100932014-10-21 16:46:12 -0700157 throw new IOException("Failed to send message to " + ep.toString(), e);
Madan Jampaniab6d3112014-10-02 16:30:14 -0700158 }
159 }
160
161 @Override
Madan Jampani24f9efb2014-10-24 18:56:23 -0700162 public ListenableFuture<byte[]> sendAndReceive(Endpoint ep, String type, byte[] payload)
Madan Jampaniab6d3112014-10-02 16:30:14 -0700163 throws IOException {
Madan Jampani24f9efb2014-10-24 18:56:23 -0700164 SettableFuture<byte[]> futureResponse = SettableFuture.create();
165 Long messageId = messageIdGenerator.incrementAndGet();
Madan Jampaniab6d3112014-10-02 16:30:14 -0700166 responseFutures.put(messageId, futureResponse);
167 InternalMessage message = new InternalMessage.Builder(this)
168 .withId(messageId)
169 .withSender(localEp)
170 .withType(type)
171 .withPayload(payload)
172 .build();
Madan Jampani15cd0b82014-10-28 08:40:23 -0700173 try {
174 sendAsync(ep, message);
175 } catch (IOException e) {
176 responseFutures.invalidate(messageId);
177 throw e;
178 }
Madan Jampaniab6d3112014-10-02 16:30:14 -0700179 return futureResponse;
180 }
181
182 @Override
183 public void registerHandler(String type, MessageHandler handler) {
184 // TODO: Is this the right semantics for handler registration?
185 handlers.putIfAbsent(type, handler);
186 }
187
Yuta HIGUCHIe5ca93b2014-10-23 09:49:00 -0700188 @Override
Madan Jampaniab6d3112014-10-02 16:30:14 -0700189 public void unregisterHandler(String type) {
190 handlers.remove(type);
191 }
192
193 private MessageHandler getMessageHandler(String type) {
194 return handlers.get(type);
195 }
196
197 private void startAcceptingConnections() throws InterruptedException {
198 ServerBootstrap b = new ServerBootstrap();
Madan Jampani86ed0552014-10-03 16:45:42 -0700199 b.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 32 * 1024);
Madan Jampaniddf76222014-10-04 23:48:44 -0700200 b.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024);
201 // TODO: Need JVM options to configure PooledByteBufAllocator.
Madan Jampaniab6d3112014-10-02 16:30:14 -0700202 b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
Madan Jampani824a7c12014-10-21 09:46:15 -0700203 b.group(serverGroup, clientGroup)
204 .channel(serverChannelClass)
Madan Jampaniab6d3112014-10-02 16:30:14 -0700205 .childHandler(new OnosCommunicationChannelInitializer())
206 .option(ChannelOption.SO_BACKLOG, 128)
207 .childOption(ChannelOption.SO_KEEPALIVE, true);
208
209 // Bind and start to accept incoming connections.
Madan Jampani87100932014-10-21 16:46:12 -0700210 b.bind(localEp.port()).sync();
Madan Jampaniab6d3112014-10-02 16:30:14 -0700211 }
212
213 private class OnosCommunicationChannelFactory
214 implements KeyedPoolableObjectFactory<Endpoint, Channel> {
215
216 @Override
217 public void activateObject(Endpoint endpoint, Channel channel)
218 throws Exception {
219 }
220
221 @Override
222 public void destroyObject(Endpoint ep, Channel channel) throws Exception {
223 channel.close();
224 }
225
226 @Override
227 public Channel makeObject(Endpoint ep) throws Exception {
Madan Jampaniddf76222014-10-04 23:48:44 -0700228 Bootstrap bootstrap = new Bootstrap();
229 bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
230 bootstrap.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 32 * 1024);
231 bootstrap.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024);
Madan Jampani824a7c12014-10-21 09:46:15 -0700232 bootstrap.group(clientGroup);
Madan Jampaniab6d3112014-10-02 16:30:14 -0700233 // TODO: Make this faster:
234 // http://normanmaurer.me/presentations/2014-facebook-eng-netty/slides.html#37.0
Madan Jampani824a7c12014-10-21 09:46:15 -0700235 bootstrap.channel(clientChannelClass);
Madan Jampaniddf76222014-10-04 23:48:44 -0700236 bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
237 bootstrap.handler(new OnosCommunicationChannelInitializer());
Madan Jampaniab6d3112014-10-02 16:30:14 -0700238 // Start the client.
Madan Jampaniddf76222014-10-04 23:48:44 -0700239 ChannelFuture f = bootstrap.connect(ep.host(), ep.port()).sync();
Madan Jampaniab6d3112014-10-02 16:30:14 -0700240 return f.channel();
241 }
242
243 @Override
244 public void passivateObject(Endpoint ep, Channel channel)
245 throws Exception {
246 }
247
248 @Override
249 public boolean validateObject(Endpoint ep, Channel channel) {
250 return channel.isOpen();
251 }
252 }
253
254 private class OnosCommunicationChannelInitializer extends ChannelInitializer<SocketChannel> {
255
Madan Jampaniddf76222014-10-04 23:48:44 -0700256 private final ChannelHandler dispatcher = new InboundMessageDispatcher();
Madan Jampani53e44e62014-10-07 12:39:51 -0700257 private final ChannelHandler encoder = new MessageEncoder();
Madan Jampaniddf76222014-10-04 23:48:44 -0700258
Madan Jampaniab6d3112014-10-02 16:30:14 -0700259 @Override
260 protected void initChannel(SocketChannel channel) throws Exception {
261 channel.pipeline()
Madan Jampaniddf76222014-10-04 23:48:44 -0700262 .addLast("encoder", encoder)
Madan Jampani53e44e62014-10-07 12:39:51 -0700263 .addLast("decoder", new MessageDecoder(NettyMessagingService.this))
Madan Jampaniddf76222014-10-04 23:48:44 -0700264 .addLast("handler", dispatcher);
Madan Jampaniab6d3112014-10-02 16:30:14 -0700265 }
266 }
267
Yuta HIGUCHIe5ca93b2014-10-23 09:49:00 -0700268 private static class WriteTask implements Runnable {
Madan Jampaniab6d3112014-10-02 16:30:14 -0700269
Madan Jampani86ed0552014-10-03 16:45:42 -0700270 private final InternalMessage message;
Madan Jampaniab6d3112014-10-02 16:30:14 -0700271 private final Channel channel;
272
Madan Jampani86ed0552014-10-03 16:45:42 -0700273 public WriteTask(Channel channel, InternalMessage message) {
Madan Jampaniab6d3112014-10-02 16:30:14 -0700274 this.channel = channel;
Madan Jampani86ed0552014-10-03 16:45:42 -0700275 this.message = message;
Madan Jampaniab6d3112014-10-02 16:30:14 -0700276 }
277
278 @Override
279 public void run() {
Madan Jampaniddf76222014-10-04 23:48:44 -0700280 channel.writeAndFlush(message, channel.voidPromise());
Madan Jampaniab6d3112014-10-02 16:30:14 -0700281 }
282 }
283
Madan Jampaniddf76222014-10-04 23:48:44 -0700284 @ChannelHandler.Sharable
Madan Jampaniab6d3112014-10-02 16:30:14 -0700285 private class InboundMessageDispatcher extends SimpleChannelInboundHandler<InternalMessage> {
286
287 @Override
288 protected void channelRead0(ChannelHandlerContext ctx, InternalMessage message) throws Exception {
289 String type = message.type();
290 if (type.equals(InternalMessage.REPLY_MESSAGE_TYPE)) {
291 try {
Madan Jampani24f9efb2014-10-24 18:56:23 -0700292 SettableFuture<byte[]> futureResponse =
Madan Jampaniab6d3112014-10-02 16:30:14 -0700293 NettyMessagingService.this.responseFutures.getIfPresent(message.id());
294 if (futureResponse != null) {
Madan Jampani24f9efb2014-10-24 18:56:23 -0700295 futureResponse.set(message.payload());
Madan Jampanif1d425a2014-10-07 09:52:36 -0700296 } else {
Madan Jampani15cd0b82014-10-28 08:40:23 -0700297 log.warn("Received a reply for message id:[{}]. "
298 + "But was unable to locate the request handle", message.id());
Madan Jampaniab6d3112014-10-02 16:30:14 -0700299 }
Madan Jampaniab6d3112014-10-02 16:30:14 -0700300 } finally {
301 NettyMessagingService.this.responseFutures.invalidate(message.id());
302 }
303 return;
304 }
305 MessageHandler handler = NettyMessagingService.this.getMessageHandler(type);
306 handler.handle(message);
307 }
Madan Jampani86ed0552014-10-03 16:45:42 -0700308
Madan Jampani86ed0552014-10-03 16:45:42 -0700309 @Override
310 public void exceptionCaught(ChannelHandlerContext context, Throwable cause) {
Madan Jampani29e5dfd2014-10-07 17:26:25 -0700311 log.error("Exception inside channel handling pipeline.", cause);
Madan Jampani86ed0552014-10-03 16:45:42 -0700312 context.close();
313 }
Madan Jampaniab6d3112014-10-02 16:30:14 -0700314 }
315}