blob: b611fadf0949ad64ce4f309dc34785b950d0e38e [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
Madan Jampaniab6d3112014-10-02 16:30:14 -070018import io.netty.bootstrap.Bootstrap;
19import io.netty.bootstrap.ServerBootstrap;
20import io.netty.buffer.PooledByteBufAllocator;
21import io.netty.channel.Channel;
22import io.netty.channel.ChannelFuture;
Madan Jampani5f9ec9a2014-10-29 13:45:52 -070023import io.netty.channel.ChannelFutureListener;
Madan Jampaniddf76222014-10-04 23:48:44 -070024import io.netty.channel.ChannelHandler;
Madan Jampaniab6d3112014-10-02 16:30:14 -070025import io.netty.channel.ChannelHandlerContext;
26import io.netty.channel.ChannelInitializer;
27import io.netty.channel.ChannelOption;
28import io.netty.channel.EventLoopGroup;
Madan Jampani824a7c12014-10-21 09:46:15 -070029import io.netty.channel.ServerChannel;
Madan Jampaniab6d3112014-10-02 16:30:14 -070030import io.netty.channel.SimpleChannelInboundHandler;
Madan Jampani824a7c12014-10-21 09:46:15 -070031import io.netty.channel.epoll.EpollEventLoopGroup;
32import io.netty.channel.epoll.EpollServerSocketChannel;
33import io.netty.channel.epoll.EpollSocketChannel;
Madan Jampaniab6d3112014-10-02 16:30:14 -070034import io.netty.channel.nio.NioEventLoopGroup;
35import io.netty.channel.socket.SocketChannel;
36import io.netty.channel.socket.nio.NioServerSocketChannel;
37import io.netty.channel.socket.nio.NioSocketChannel;
38
Madan Jampani348a9fe2014-11-09 01:37:51 -080039import java.io.IOException;
40import java.net.UnknownHostException;
41import java.util.concurrent.ConcurrentHashMap;
42import java.util.concurrent.ConcurrentMap;
43import java.util.concurrent.TimeUnit;
44import java.util.concurrent.TimeoutException;
45import java.util.concurrent.atomic.AtomicLong;
46
Madan Jampaniab6d3112014-10-02 16:30:14 -070047import org.apache.commons.pool.KeyedPoolableObjectFactory;
48import org.apache.commons.pool.impl.GenericKeyedObjectPool;
49import org.slf4j.Logger;
50import org.slf4j.LoggerFactory;
51
52import com.google.common.cache.Cache;
53import com.google.common.cache.CacheBuilder;
Madan Jampani5f9ec9a2014-10-29 13:45:52 -070054import com.google.common.cache.RemovalListener;
55import com.google.common.cache.RemovalNotification;
Madan Jampani24f9efb2014-10-24 18:56:23 -070056import com.google.common.util.concurrent.ListenableFuture;
57import com.google.common.util.concurrent.SettableFuture;
Madan Jampaniab6d3112014-10-02 16:30:14 -070058
59/**
60 * A Netty based implementation of MessagingService.
61 */
62public class NettyMessagingService implements MessagingService {
63
64 private final Logger log = LoggerFactory.getLogger(getClass());
65
Madan Jampaniddf76222014-10-04 23:48:44 -070066 private final Endpoint localEp;
Madan Jampaniab6d3112014-10-02 16:30:14 -070067 private final ConcurrentMap<String, MessageHandler> handlers = new ConcurrentHashMap<>();
Madan Jampani24f9efb2014-10-24 18:56:23 -070068 private final AtomicLong messageIdGenerator = new AtomicLong(0);
69 private final Cache<Long, SettableFuture<byte[]>> responseFutures = CacheBuilder.newBuilder()
Madan Jampaniddf76222014-10-04 23:48:44 -070070 .maximumSize(100000)
Madan Jampani5f9ec9a2014-10-29 13:45:52 -070071 .expireAfterWrite(10, TimeUnit.SECONDS)
72 .removalListener(new RemovalListener<Long, SettableFuture<byte[]>>() {
73 @Override
74 public void onRemoval(RemovalNotification<Long, SettableFuture<byte[]>> entry) {
Yuta HIGUCHIc611d922015-02-10 16:07:38 -080075 if (entry.wasEvicted()) {
76 entry.getValue().setException(new TimeoutException("Timedout waiting for reply"));
77 }
Madan Jampani5f9ec9a2014-10-29 13:45:52 -070078 }
79 })
Madan Jampaniddf76222014-10-04 23:48:44 -070080 .build();
81 private final GenericKeyedObjectPool<Endpoint, Channel> channels
82 = new GenericKeyedObjectPool<Endpoint, Channel>(new OnosCommunicationChannelFactory());
Madan Jampaniab6d3112014-10-02 16:30:14 -070083
Madan Jampani824a7c12014-10-21 09:46:15 -070084 private EventLoopGroup serverGroup;
85 private EventLoopGroup clientGroup;
86 private Class<? extends ServerChannel> serverChannelClass;
87 private Class<? extends Channel> clientChannelClass;
88
Madan Jampani5e83f332014-10-20 15:35:09 -070089 private void initEventLoopGroup() {
Madan Jampani824a7c12014-10-21 09:46:15 -070090 // try Epoll first and if that does work, use nio.
Madan Jampani824a7c12014-10-21 09:46:15 -070091 try {
Madan Jampani99e9fe22014-10-21 13:47:12 -070092 clientGroup = new EpollEventLoopGroup();
93 serverGroup = new EpollEventLoopGroup();
94 serverChannelClass = EpollServerSocketChannel.class;
95 clientChannelClass = EpollSocketChannel.class;
96 return;
Madan Jampani824a7c12014-10-21 09:46:15 -070097 } catch (Throwable t) {
Madan Jampanicfbc0542014-10-24 20:38:07 -070098 log.warn("Failed to initialize native (epoll) transport. Reason: {}. Proceeding with nio.", t.getMessage());
Madan Jampani824a7c12014-10-21 09:46:15 -070099 }
100 clientGroup = new NioEventLoopGroup();
101 serverGroup = new NioEventLoopGroup();
102 serverChannelClass = NioServerSocketChannel.class;
103 clientChannelClass = NioSocketChannel.class;
Madan Jampani5e83f332014-10-20 15:35:09 -0700104 }
105
Madan Jampani87100932014-10-21 16:46:12 -0700106 public NettyMessagingService(String ip, int port) {
107 localEp = new Endpoint(ip, port);
108 }
109
Madan Jampaniab6d3112014-10-02 16:30:14 -0700110 public NettyMessagingService() {
Madan Jampaniab6d3112014-10-02 16:30:14 -0700111 this(8080);
112 }
113
Madan Jampaniab6d3112014-10-02 16:30:14 -0700114 public NettyMessagingService(int port) {
Madan Jampaniab6d3112014-10-02 16:30:14 -0700115 try {
116 localEp = new Endpoint(java.net.InetAddress.getLocalHost().getHostName(), port);
117 } catch (UnknownHostException e) {
Ray Milkey3f0c97e2014-12-08 14:53:30 -0800118 // Cannot resolve the local host, something is very wrong. Bailing out.
119 throw new IllegalStateException("Cannot resolve local host", e);
Madan Jampaniab6d3112014-10-02 16:30:14 -0700120 }
121 }
122
Ray Milkey3f0c97e2014-12-08 14:53:30 -0800123 public void activate() throws InterruptedException {
Madan Jampani86ed0552014-10-03 16:45:42 -0700124 channels.setTestOnBorrow(true);
125 channels.setTestOnReturn(true);
Madan Jampani5e83f332014-10-20 15:35:09 -0700126 initEventLoopGroup();
Madan Jampaniab6d3112014-10-02 16:30:14 -0700127 startAcceptingConnections();
128 }
129
130 public void deactivate() throws Exception {
131 channels.close();
Madan Jampani824a7c12014-10-21 09:46:15 -0700132 serverGroup.shutdownGracefully();
133 clientGroup.shutdownGracefully();
Madan Jampaniab6d3112014-10-02 16:30:14 -0700134 }
135
Madan Jampani87100932014-10-21 16:46:12 -0700136 /**
137 * Returns the local endpoint for this instance.
138 * @return local end point.
139 */
140 public Endpoint localEp() {
141 return localEp;
142 }
143
Madan Jampaniab6d3112014-10-02 16:30:14 -0700144 @Override
Madan Jampani53e44e62014-10-07 12:39:51 -0700145 public void sendAsync(Endpoint ep, String type, byte[] payload) throws IOException {
Madan Jampaniab6d3112014-10-02 16:30:14 -0700146 InternalMessage message = new InternalMessage.Builder(this)
Madan Jampani24f9efb2014-10-24 18:56:23 -0700147 .withId(messageIdGenerator.incrementAndGet())
Madan Jampaniab6d3112014-10-02 16:30:14 -0700148 .withSender(localEp)
149 .withType(type)
150 .withPayload(payload)
151 .build();
152 sendAsync(ep, message);
153 }
154
155 protected void sendAsync(Endpoint ep, InternalMessage message) throws IOException {
156 Channel channel = null;
157 try {
Madan Jampani86ed0552014-10-03 16:45:42 -0700158 try {
159 channel = channels.borrowObject(ep);
160 channel.eventLoop().execute(new WriteTask(channel, message));
161 } finally {
162 channels.returnObject(ep, channel);
163 }
Madan Jampani5f9ec9a2014-10-29 13:45:52 -0700164 } catch (IOException e) {
165 throw e;
Madan Jampaniab6d3112014-10-02 16:30:14 -0700166 } catch (Exception e) {
Madan Jampani5f9ec9a2014-10-29 13:45:52 -0700167 throw new IOException(e);
Madan Jampaniab6d3112014-10-02 16:30:14 -0700168 }
Madan Jampani5f9ec9a2014-10-29 13:45:52 -0700169
Madan Jampaniab6d3112014-10-02 16:30:14 -0700170 }
171
172 @Override
Madan Jampani24f9efb2014-10-24 18:56:23 -0700173 public ListenableFuture<byte[]> sendAndReceive(Endpoint ep, String type, byte[] payload)
Madan Jampaniab6d3112014-10-02 16:30:14 -0700174 throws IOException {
Madan Jampani24f9efb2014-10-24 18:56:23 -0700175 SettableFuture<byte[]> futureResponse = SettableFuture.create();
176 Long messageId = messageIdGenerator.incrementAndGet();
Madan Jampaniab6d3112014-10-02 16:30:14 -0700177 responseFutures.put(messageId, futureResponse);
178 InternalMessage message = new InternalMessage.Builder(this)
179 .withId(messageId)
180 .withSender(localEp)
181 .withType(type)
182 .withPayload(payload)
183 .build();
Madan Jampani15cd0b82014-10-28 08:40:23 -0700184 try {
185 sendAsync(ep, message);
Madan Jampani5f9ec9a2014-10-29 13:45:52 -0700186 } catch (Exception e) {
Madan Jampani15cd0b82014-10-28 08:40:23 -0700187 responseFutures.invalidate(messageId);
188 throw e;
189 }
Madan Jampaniab6d3112014-10-02 16:30:14 -0700190 return futureResponse;
191 }
192
193 @Override
194 public void registerHandler(String type, MessageHandler handler) {
Madan Jampaniab6d3112014-10-02 16:30:14 -0700195 handlers.putIfAbsent(type, handler);
196 }
197
Yuta HIGUCHIe5ca93b2014-10-23 09:49:00 -0700198 @Override
Madan Jampaniab6d3112014-10-02 16:30:14 -0700199 public void unregisterHandler(String type) {
200 handlers.remove(type);
201 }
202
203 private MessageHandler getMessageHandler(String type) {
204 return handlers.get(type);
205 }
206
207 private void startAcceptingConnections() throws InterruptedException {
208 ServerBootstrap b = new ServerBootstrap();
Madan Jampani86ed0552014-10-03 16:45:42 -0700209 b.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 32 * 1024);
Madan Jampaniddf76222014-10-04 23:48:44 -0700210 b.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024);
Madan Jampaniab6d3112014-10-02 16:30:14 -0700211 b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
Madan Jampani824a7c12014-10-21 09:46:15 -0700212 b.group(serverGroup, clientGroup)
213 .channel(serverChannelClass)
Madan Jampaniab6d3112014-10-02 16:30:14 -0700214 .childHandler(new OnosCommunicationChannelInitializer())
215 .option(ChannelOption.SO_BACKLOG, 128)
216 .childOption(ChannelOption.SO_KEEPALIVE, true);
217
218 // Bind and start to accept incoming connections.
Madan Jampani87100932014-10-21 16:46:12 -0700219 b.bind(localEp.port()).sync();
Madan Jampaniab6d3112014-10-02 16:30:14 -0700220 }
221
222 private class OnosCommunicationChannelFactory
223 implements KeyedPoolableObjectFactory<Endpoint, Channel> {
224
225 @Override
226 public void activateObject(Endpoint endpoint, Channel channel)
227 throws Exception {
228 }
229
230 @Override
231 public void destroyObject(Endpoint ep, Channel channel) throws Exception {
232 channel.close();
233 }
234
235 @Override
236 public Channel makeObject(Endpoint ep) throws Exception {
Madan Jampaniddf76222014-10-04 23:48:44 -0700237 Bootstrap bootstrap = new Bootstrap();
238 bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
239 bootstrap.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 32 * 1024);
240 bootstrap.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024);
Madan Jampani824a7c12014-10-21 09:46:15 -0700241 bootstrap.group(clientGroup);
Madan Jampaniab6d3112014-10-02 16:30:14 -0700242 // TODO: Make this faster:
243 // http://normanmaurer.me/presentations/2014-facebook-eng-netty/slides.html#37.0
Madan Jampani824a7c12014-10-21 09:46:15 -0700244 bootstrap.channel(clientChannelClass);
Madan Jampaniddf76222014-10-04 23:48:44 -0700245 bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
246 bootstrap.handler(new OnosCommunicationChannelInitializer());
Madan Jampaniab6d3112014-10-02 16:30:14 -0700247 // Start the client.
Madan Jampaniddf76222014-10-04 23:48:44 -0700248 ChannelFuture f = bootstrap.connect(ep.host(), ep.port()).sync();
Madan Jampaniab6d3112014-10-02 16:30:14 -0700249 return f.channel();
250 }
251
252 @Override
253 public void passivateObject(Endpoint ep, Channel channel)
254 throws Exception {
255 }
256
257 @Override
258 public boolean validateObject(Endpoint ep, Channel channel) {
259 return channel.isOpen();
260 }
261 }
262
263 private class OnosCommunicationChannelInitializer extends ChannelInitializer<SocketChannel> {
264
Madan Jampaniddf76222014-10-04 23:48:44 -0700265 private final ChannelHandler dispatcher = new InboundMessageDispatcher();
Madan Jampani53e44e62014-10-07 12:39:51 -0700266 private final ChannelHandler encoder = new MessageEncoder();
Madan Jampaniddf76222014-10-04 23:48:44 -0700267
Madan Jampaniab6d3112014-10-02 16:30:14 -0700268 @Override
269 protected void initChannel(SocketChannel channel) throws Exception {
270 channel.pipeline()
Madan Jampaniddf76222014-10-04 23:48:44 -0700271 .addLast("encoder", encoder)
Madan Jampani53e44e62014-10-07 12:39:51 -0700272 .addLast("decoder", new MessageDecoder(NettyMessagingService.this))
Madan Jampaniddf76222014-10-04 23:48:44 -0700273 .addLast("handler", dispatcher);
Madan Jampaniab6d3112014-10-02 16:30:14 -0700274 }
275 }
276
Yuta HIGUCHIe5ca93b2014-10-23 09:49:00 -0700277 private static class WriteTask implements Runnable {
Madan Jampaniab6d3112014-10-02 16:30:14 -0700278
Madan Jampani86ed0552014-10-03 16:45:42 -0700279 private final InternalMessage message;
Madan Jampaniab6d3112014-10-02 16:30:14 -0700280 private final Channel channel;
281
Madan Jampani86ed0552014-10-03 16:45:42 -0700282 public WriteTask(Channel channel, InternalMessage message) {
Madan Jampaniab6d3112014-10-02 16:30:14 -0700283 this.channel = channel;
Madan Jampani86ed0552014-10-03 16:45:42 -0700284 this.message = message;
Madan Jampaniab6d3112014-10-02 16:30:14 -0700285 }
286
287 @Override
288 public void run() {
Madan Jampani5f9ec9a2014-10-29 13:45:52 -0700289 channel.writeAndFlush(message).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
Madan Jampaniab6d3112014-10-02 16:30:14 -0700290 }
291 }
292
Madan Jampaniddf76222014-10-04 23:48:44 -0700293 @ChannelHandler.Sharable
Madan Jampaniab6d3112014-10-02 16:30:14 -0700294 private class InboundMessageDispatcher extends SimpleChannelInboundHandler<InternalMessage> {
295
296 @Override
297 protected void channelRead0(ChannelHandlerContext ctx, InternalMessage message) throws Exception {
298 String type = message.type();
299 if (type.equals(InternalMessage.REPLY_MESSAGE_TYPE)) {
300 try {
Madan Jampani24f9efb2014-10-24 18:56:23 -0700301 SettableFuture<byte[]> futureResponse =
Madan Jampaniab6d3112014-10-02 16:30:14 -0700302 NettyMessagingService.this.responseFutures.getIfPresent(message.id());
303 if (futureResponse != null) {
Madan Jampani24f9efb2014-10-24 18:56:23 -0700304 futureResponse.set(message.payload());
Madan Jampanif1d425a2014-10-07 09:52:36 -0700305 } else {
Madan Jampani15cd0b82014-10-28 08:40:23 -0700306 log.warn("Received a reply for message id:[{}]. "
Madan Jampani348a9fe2014-11-09 01:37:51 -0800307 + " from {}. But was unable to locate the"
308 + " request handle", message.id(), message.sender());
Madan Jampaniab6d3112014-10-02 16:30:14 -0700309 }
Madan Jampaniab6d3112014-10-02 16:30:14 -0700310 } finally {
311 NettyMessagingService.this.responseFutures.invalidate(message.id());
312 }
313 return;
314 }
315 MessageHandler handler = NettyMessagingService.this.getMessageHandler(type);
Yuta HIGUCHI5f9d6962014-11-07 13:06:45 -0800316 if (handler != null) {
317 handler.handle(message);
318 } else {
319 log.debug("No handler registered for {}", type);
320 }
Madan Jampaniab6d3112014-10-02 16:30:14 -0700321 }
Madan Jampani86ed0552014-10-03 16:45:42 -0700322
Madan Jampani86ed0552014-10-03 16:45:42 -0700323 @Override
324 public void exceptionCaught(ChannelHandlerContext context, Throwable cause) {
Madan Jampani29e5dfd2014-10-07 17:26:25 -0700325 log.error("Exception inside channel handling pipeline.", cause);
Madan Jampani86ed0552014-10-03 16:45:42 -0700326 context.close();
327 }
Madan Jampaniab6d3112014-10-02 16:30:14 -0700328 }
329}