blob: 6a9cf68eb42ddf2c0576aa70e0eab288ab1fa34f [file] [log] [blame]
Thomas Vachuska24c849c2014-10-27 09:53:05 -07001/*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
Madan Jampaniab6d3112014-10-02 16:30:14 -070019package org.onlab.netty;
20
21import java.io.IOException;
22import java.net.UnknownHostException;
23import java.util.concurrent.ConcurrentHashMap;
24import java.util.concurrent.ConcurrentMap;
25import java.util.concurrent.TimeUnit;
Madan Jampani5f9ec9a2014-10-29 13:45:52 -070026import java.util.concurrent.TimeoutException;
Madan Jampani24f9efb2014-10-24 18:56:23 -070027import java.util.concurrent.atomic.AtomicLong;
Madan Jampaniab6d3112014-10-02 16:30:14 -070028
29import io.netty.bootstrap.Bootstrap;
30import io.netty.bootstrap.ServerBootstrap;
31import io.netty.buffer.PooledByteBufAllocator;
32import io.netty.channel.Channel;
33import io.netty.channel.ChannelFuture;
Madan Jampani5f9ec9a2014-10-29 13:45:52 -070034import io.netty.channel.ChannelFutureListener;
Madan Jampaniddf76222014-10-04 23:48:44 -070035import io.netty.channel.ChannelHandler;
Madan Jampaniab6d3112014-10-02 16:30:14 -070036import io.netty.channel.ChannelHandlerContext;
37import io.netty.channel.ChannelInitializer;
38import io.netty.channel.ChannelOption;
39import io.netty.channel.EventLoopGroup;
Madan Jampani824a7c12014-10-21 09:46:15 -070040import io.netty.channel.ServerChannel;
Madan Jampaniab6d3112014-10-02 16:30:14 -070041import io.netty.channel.SimpleChannelInboundHandler;
Madan Jampani824a7c12014-10-21 09:46:15 -070042import io.netty.channel.epoll.EpollEventLoopGroup;
43import io.netty.channel.epoll.EpollServerSocketChannel;
44import io.netty.channel.epoll.EpollSocketChannel;
Madan Jampaniab6d3112014-10-02 16:30:14 -070045import io.netty.channel.nio.NioEventLoopGroup;
46import io.netty.channel.socket.SocketChannel;
47import io.netty.channel.socket.nio.NioServerSocketChannel;
48import io.netty.channel.socket.nio.NioSocketChannel;
49
Madan Jampaniab6d3112014-10-02 16:30:14 -070050import org.apache.commons.pool.KeyedPoolableObjectFactory;
51import org.apache.commons.pool.impl.GenericKeyedObjectPool;
52import org.slf4j.Logger;
53import org.slf4j.LoggerFactory;
54
55import com.google.common.cache.Cache;
56import com.google.common.cache.CacheBuilder;
Madan Jampani5f9ec9a2014-10-29 13:45:52 -070057import com.google.common.cache.RemovalListener;
58import com.google.common.cache.RemovalNotification;
Madan Jampani24f9efb2014-10-24 18:56:23 -070059import com.google.common.util.concurrent.ListenableFuture;
60import com.google.common.util.concurrent.SettableFuture;
Madan Jampaniab6d3112014-10-02 16:30:14 -070061
62/**
63 * A Netty based implementation of MessagingService.
64 */
65public class NettyMessagingService implements MessagingService {
66
67 private final Logger log = LoggerFactory.getLogger(getClass());
68
Madan Jampaniddf76222014-10-04 23:48:44 -070069 private final Endpoint localEp;
Madan Jampaniab6d3112014-10-02 16:30:14 -070070 private final ConcurrentMap<String, MessageHandler> handlers = new ConcurrentHashMap<>();
Madan Jampani24f9efb2014-10-24 18:56:23 -070071 private final AtomicLong messageIdGenerator = new AtomicLong(0);
72 private final Cache<Long, SettableFuture<byte[]>> responseFutures = CacheBuilder.newBuilder()
Madan Jampaniddf76222014-10-04 23:48:44 -070073 .maximumSize(100000)
Madan Jampani5f9ec9a2014-10-29 13:45:52 -070074 .expireAfterWrite(10, TimeUnit.SECONDS)
75 .removalListener(new RemovalListener<Long, SettableFuture<byte[]>>() {
76 @Override
77 public void onRemoval(RemovalNotification<Long, SettableFuture<byte[]>> entry) {
78 entry.getValue().setException(new TimeoutException("Timedout waiting for reply"));
79 }
80 })
Madan Jampaniddf76222014-10-04 23:48:44 -070081 .build();
82 private final GenericKeyedObjectPool<Endpoint, Channel> channels
83 = new GenericKeyedObjectPool<Endpoint, Channel>(new OnosCommunicationChannelFactory());
Madan Jampaniab6d3112014-10-02 16:30:14 -070084
Madan Jampani824a7c12014-10-21 09:46:15 -070085 private EventLoopGroup serverGroup;
86 private EventLoopGroup clientGroup;
87 private Class<? extends ServerChannel> serverChannelClass;
88 private Class<? extends Channel> clientChannelClass;
89
Madan Jampani5e83f332014-10-20 15:35:09 -070090 private void initEventLoopGroup() {
Madan Jampani824a7c12014-10-21 09:46:15 -070091 // try Epoll first and if that does work, use nio.
92 // TODO: make this configurable.
93 try {
Madan Jampani99e9fe22014-10-21 13:47:12 -070094 clientGroup = new EpollEventLoopGroup();
95 serverGroup = new EpollEventLoopGroup();
96 serverChannelClass = EpollServerSocketChannel.class;
97 clientChannelClass = EpollSocketChannel.class;
98 return;
Madan Jampani824a7c12014-10-21 09:46:15 -070099 } catch (Throwable t) {
Madan Jampanicfbc0542014-10-24 20:38:07 -0700100 log.warn("Failed to initialize native (epoll) transport. Reason: {}. Proceeding with nio.", t.getMessage());
Madan Jampani824a7c12014-10-21 09:46:15 -0700101 }
102 clientGroup = new NioEventLoopGroup();
103 serverGroup = new NioEventLoopGroup();
104 serverChannelClass = NioServerSocketChannel.class;
105 clientChannelClass = NioSocketChannel.class;
Madan Jampani5e83f332014-10-20 15:35:09 -0700106 }
107
Madan Jampani87100932014-10-21 16:46:12 -0700108 public NettyMessagingService(String ip, int port) {
109 localEp = new Endpoint(ip, port);
110 }
111
Madan Jampaniab6d3112014-10-02 16:30:14 -0700112 public NettyMessagingService() {
113 // TODO: Default port should be configurable.
114 this(8080);
115 }
116
117 // FIXME: Constructor should not throw exceptions.
118 public NettyMessagingService(int port) {
Madan Jampaniab6d3112014-10-02 16:30:14 -0700119 try {
120 localEp = new Endpoint(java.net.InetAddress.getLocalHost().getHostName(), port);
121 } catch (UnknownHostException e) {
122 // bailing out.
123 throw new RuntimeException(e);
124 }
125 }
126
127 public void activate() throws Exception {
Madan Jampani86ed0552014-10-03 16:45:42 -0700128 channels.setTestOnBorrow(true);
129 channels.setTestOnReturn(true);
Madan Jampani5e83f332014-10-20 15:35:09 -0700130 initEventLoopGroup();
Madan Jampaniab6d3112014-10-02 16:30:14 -0700131 startAcceptingConnections();
132 }
133
134 public void deactivate() throws Exception {
135 channels.close();
Madan Jampani824a7c12014-10-21 09:46:15 -0700136 serverGroup.shutdownGracefully();
137 clientGroup.shutdownGracefully();
Madan Jampaniab6d3112014-10-02 16:30:14 -0700138 }
139
Madan Jampani87100932014-10-21 16:46:12 -0700140 /**
141 * Returns the local endpoint for this instance.
142 * @return local end point.
143 */
144 public Endpoint localEp() {
145 return localEp;
146 }
147
Madan Jampaniab6d3112014-10-02 16:30:14 -0700148 @Override
Madan Jampani53e44e62014-10-07 12:39:51 -0700149 public void sendAsync(Endpoint ep, String type, byte[] payload) throws IOException {
Madan Jampaniab6d3112014-10-02 16:30:14 -0700150 InternalMessage message = new InternalMessage.Builder(this)
Madan Jampani24f9efb2014-10-24 18:56:23 -0700151 .withId(messageIdGenerator.incrementAndGet())
Madan Jampaniab6d3112014-10-02 16:30:14 -0700152 .withSender(localEp)
153 .withType(type)
154 .withPayload(payload)
155 .build();
156 sendAsync(ep, message);
157 }
158
159 protected void sendAsync(Endpoint ep, InternalMessage message) throws IOException {
160 Channel channel = null;
161 try {
Madan Jampani86ed0552014-10-03 16:45:42 -0700162 try {
163 channel = channels.borrowObject(ep);
164 channel.eventLoop().execute(new WriteTask(channel, message));
165 } finally {
166 channels.returnObject(ep, channel);
167 }
Madan Jampani5f9ec9a2014-10-29 13:45:52 -0700168 } catch (IOException e) {
169 throw e;
Madan Jampaniab6d3112014-10-02 16:30:14 -0700170 } catch (Exception e) {
Madan Jampani5f9ec9a2014-10-29 13:45:52 -0700171 throw new IOException(e);
Madan Jampaniab6d3112014-10-02 16:30:14 -0700172 }
Madan Jampani5f9ec9a2014-10-29 13:45:52 -0700173
Madan Jampaniab6d3112014-10-02 16:30:14 -0700174 }
175
176 @Override
Madan Jampani24f9efb2014-10-24 18:56:23 -0700177 public ListenableFuture<byte[]> sendAndReceive(Endpoint ep, String type, byte[] payload)
Madan Jampaniab6d3112014-10-02 16:30:14 -0700178 throws IOException {
Madan Jampani24f9efb2014-10-24 18:56:23 -0700179 SettableFuture<byte[]> futureResponse = SettableFuture.create();
180 Long messageId = messageIdGenerator.incrementAndGet();
Madan Jampaniab6d3112014-10-02 16:30:14 -0700181 responseFutures.put(messageId, futureResponse);
182 InternalMessage message = new InternalMessage.Builder(this)
183 .withId(messageId)
184 .withSender(localEp)
185 .withType(type)
186 .withPayload(payload)
187 .build();
Madan Jampani15cd0b82014-10-28 08:40:23 -0700188 try {
189 sendAsync(ep, message);
Madan Jampani5f9ec9a2014-10-29 13:45:52 -0700190 } catch (Exception e) {
Madan Jampani15cd0b82014-10-28 08:40:23 -0700191 responseFutures.invalidate(messageId);
192 throw e;
193 }
Madan Jampaniab6d3112014-10-02 16:30:14 -0700194 return futureResponse;
195 }
196
197 @Override
198 public void registerHandler(String type, MessageHandler handler) {
199 // TODO: Is this the right semantics for handler registration?
200 handlers.putIfAbsent(type, handler);
201 }
202
Yuta HIGUCHIe5ca93b2014-10-23 09:49:00 -0700203 @Override
Madan Jampaniab6d3112014-10-02 16:30:14 -0700204 public void unregisterHandler(String type) {
205 handlers.remove(type);
206 }
207
208 private MessageHandler getMessageHandler(String type) {
209 return handlers.get(type);
210 }
211
212 private void startAcceptingConnections() throws InterruptedException {
213 ServerBootstrap b = new ServerBootstrap();
Madan Jampani86ed0552014-10-03 16:45:42 -0700214 b.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 32 * 1024);
Madan Jampaniddf76222014-10-04 23:48:44 -0700215 b.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024);
216 // TODO: Need JVM options to configure PooledByteBufAllocator.
Madan Jampaniab6d3112014-10-02 16:30:14 -0700217 b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
Madan Jampani824a7c12014-10-21 09:46:15 -0700218 b.group(serverGroup, clientGroup)
219 .channel(serverChannelClass)
Madan Jampaniab6d3112014-10-02 16:30:14 -0700220 .childHandler(new OnosCommunicationChannelInitializer())
221 .option(ChannelOption.SO_BACKLOG, 128)
222 .childOption(ChannelOption.SO_KEEPALIVE, true);
223
224 // Bind and start to accept incoming connections.
Madan Jampani87100932014-10-21 16:46:12 -0700225 b.bind(localEp.port()).sync();
Madan Jampaniab6d3112014-10-02 16:30:14 -0700226 }
227
228 private class OnosCommunicationChannelFactory
229 implements KeyedPoolableObjectFactory<Endpoint, Channel> {
230
231 @Override
232 public void activateObject(Endpoint endpoint, Channel channel)
233 throws Exception {
234 }
235
236 @Override
237 public void destroyObject(Endpoint ep, Channel channel) throws Exception {
238 channel.close();
239 }
240
241 @Override
242 public Channel makeObject(Endpoint ep) throws Exception {
Madan Jampaniddf76222014-10-04 23:48:44 -0700243 Bootstrap bootstrap = new Bootstrap();
244 bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
245 bootstrap.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 32 * 1024);
246 bootstrap.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024);
Madan Jampani824a7c12014-10-21 09:46:15 -0700247 bootstrap.group(clientGroup);
Madan Jampaniab6d3112014-10-02 16:30:14 -0700248 // TODO: Make this faster:
249 // http://normanmaurer.me/presentations/2014-facebook-eng-netty/slides.html#37.0
Madan Jampani824a7c12014-10-21 09:46:15 -0700250 bootstrap.channel(clientChannelClass);
Madan Jampaniddf76222014-10-04 23:48:44 -0700251 bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
252 bootstrap.handler(new OnosCommunicationChannelInitializer());
Madan Jampaniab6d3112014-10-02 16:30:14 -0700253 // Start the client.
Madan Jampaniddf76222014-10-04 23:48:44 -0700254 ChannelFuture f = bootstrap.connect(ep.host(), ep.port()).sync();
Madan Jampaniab6d3112014-10-02 16:30:14 -0700255 return f.channel();
256 }
257
258 @Override
259 public void passivateObject(Endpoint ep, Channel channel)
260 throws Exception {
261 }
262
263 @Override
264 public boolean validateObject(Endpoint ep, Channel channel) {
265 return channel.isOpen();
266 }
267 }
268
269 private class OnosCommunicationChannelInitializer extends ChannelInitializer<SocketChannel> {
270
Madan Jampaniddf76222014-10-04 23:48:44 -0700271 private final ChannelHandler dispatcher = new InboundMessageDispatcher();
Madan Jampani53e44e62014-10-07 12:39:51 -0700272 private final ChannelHandler encoder = new MessageEncoder();
Madan Jampaniddf76222014-10-04 23:48:44 -0700273
Madan Jampaniab6d3112014-10-02 16:30:14 -0700274 @Override
275 protected void initChannel(SocketChannel channel) throws Exception {
276 channel.pipeline()
Madan Jampaniddf76222014-10-04 23:48:44 -0700277 .addLast("encoder", encoder)
Madan Jampani53e44e62014-10-07 12:39:51 -0700278 .addLast("decoder", new MessageDecoder(NettyMessagingService.this))
Madan Jampaniddf76222014-10-04 23:48:44 -0700279 .addLast("handler", dispatcher);
Madan Jampaniab6d3112014-10-02 16:30:14 -0700280 }
281 }
282
Yuta HIGUCHIe5ca93b2014-10-23 09:49:00 -0700283 private static class WriteTask implements Runnable {
Madan Jampaniab6d3112014-10-02 16:30:14 -0700284
Madan Jampani86ed0552014-10-03 16:45:42 -0700285 private final InternalMessage message;
Madan Jampaniab6d3112014-10-02 16:30:14 -0700286 private final Channel channel;
287
Madan Jampani86ed0552014-10-03 16:45:42 -0700288 public WriteTask(Channel channel, InternalMessage message) {
Madan Jampaniab6d3112014-10-02 16:30:14 -0700289 this.channel = channel;
Madan Jampani86ed0552014-10-03 16:45:42 -0700290 this.message = message;
Madan Jampaniab6d3112014-10-02 16:30:14 -0700291 }
292
293 @Override
294 public void run() {
Madan Jampani5f9ec9a2014-10-29 13:45:52 -0700295 channel.writeAndFlush(message).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
Madan Jampaniab6d3112014-10-02 16:30:14 -0700296 }
297 }
298
Madan Jampaniddf76222014-10-04 23:48:44 -0700299 @ChannelHandler.Sharable
Madan Jampaniab6d3112014-10-02 16:30:14 -0700300 private class InboundMessageDispatcher extends SimpleChannelInboundHandler<InternalMessage> {
301
302 @Override
303 protected void channelRead0(ChannelHandlerContext ctx, InternalMessage message) throws Exception {
304 String type = message.type();
305 if (type.equals(InternalMessage.REPLY_MESSAGE_TYPE)) {
306 try {
Madan Jampani24f9efb2014-10-24 18:56:23 -0700307 SettableFuture<byte[]> futureResponse =
Madan Jampaniab6d3112014-10-02 16:30:14 -0700308 NettyMessagingService.this.responseFutures.getIfPresent(message.id());
309 if (futureResponse != null) {
Madan Jampani24f9efb2014-10-24 18:56:23 -0700310 futureResponse.set(message.payload());
Madan Jampanif1d425a2014-10-07 09:52:36 -0700311 } else {
Madan Jampani15cd0b82014-10-28 08:40:23 -0700312 log.warn("Received a reply for message id:[{}]. "
313 + "But was unable to locate the request handle", message.id());
Madan Jampaniab6d3112014-10-02 16:30:14 -0700314 }
Madan Jampaniab6d3112014-10-02 16:30:14 -0700315 } finally {
316 NettyMessagingService.this.responseFutures.invalidate(message.id());
317 }
318 return;
319 }
320 MessageHandler handler = NettyMessagingService.this.getMessageHandler(type);
321 handler.handle(message);
322 }
Madan Jampani86ed0552014-10-03 16:45:42 -0700323
Madan Jampani86ed0552014-10-03 16:45:42 -0700324 @Override
325 public void exceptionCaught(ChannelHandlerContext context, Throwable cause) {
Madan Jampani29e5dfd2014-10-07 17:26:25 -0700326 log.error("Exception inside channel handling pipeline.", cause);
Madan Jampani86ed0552014-10-03 16:45:42 -0700327 context.close();
328 }
Madan Jampaniab6d3112014-10-02 16:30:14 -0700329 }
330}