blob: 6628bb24c8240b903686d11850cec80952578a83 [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;
Madan Jampani2e5f87b2015-02-22 10:37:15 -080040import java.net.InetAddress;
Madan Jampani348a9fe2014-11-09 01:37:51 -080041import java.net.UnknownHostException;
42import java.util.concurrent.ConcurrentHashMap;
43import java.util.concurrent.ConcurrentMap;
Madan Jampani2af244a2015-02-22 13:12:01 -080044import java.util.concurrent.ExecutorService;
Madan Jampani348a9fe2014-11-09 01:37:51 -080045import java.util.concurrent.TimeUnit;
46import java.util.concurrent.TimeoutException;
47import java.util.concurrent.atomic.AtomicLong;
48
Madan Jampaniab6d3112014-10-02 16:30:14 -070049import org.apache.commons.pool.KeyedPoolableObjectFactory;
50import org.apache.commons.pool.impl.GenericKeyedObjectPool;
Madan Jampani2e5f87b2015-02-22 10:37:15 -080051import org.onlab.packet.IpAddress;
Madan Jampaniab6d3112014-10-02 16:30:14 -070052import 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 Jampani49115e92015-03-14 10:43:33 -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) {
Yuta HIGUCHIc611d922015-02-10 16:07:38 -080078 if (entry.wasEvicted()) {
79 entry.getValue().setException(new TimeoutException("Timedout waiting for reply"));
80 }
Madan Jampani5f9ec9a2014-10-29 13:45:52 -070081 }
82 })
Madan Jampaniddf76222014-10-04 23:48:44 -070083 .build();
Madan Jampani2e5f87b2015-02-22 10:37:15 -080084
Madan Jampaniddf76222014-10-04 23:48:44 -070085 private final GenericKeyedObjectPool<Endpoint, Channel> channels
86 = new GenericKeyedObjectPool<Endpoint, Channel>(new OnosCommunicationChannelFactory());
Madan Jampaniab6d3112014-10-02 16:30:14 -070087
Madan Jampani824a7c12014-10-21 09:46:15 -070088 private EventLoopGroup serverGroup;
89 private EventLoopGroup clientGroup;
90 private Class<? extends ServerChannel> serverChannelClass;
91 private Class<? extends Channel> clientChannelClass;
92
Madan Jampani5e83f332014-10-20 15:35:09 -070093 private void initEventLoopGroup() {
Madan Jampani824a7c12014-10-21 09:46:15 -070094 // try Epoll first and if that does work, use nio.
Madan Jampani824a7c12014-10-21 09:46:15 -070095 try {
Madan Jampani99e9fe22014-10-21 13:47:12 -070096 clientGroup = new EpollEventLoopGroup();
97 serverGroup = new EpollEventLoopGroup();
98 serverChannelClass = EpollServerSocketChannel.class;
99 clientChannelClass = EpollSocketChannel.class;
100 return;
Madan Jampani824a7c12014-10-21 09:46:15 -0700101 } catch (Throwable t) {
Madan Jampanicfbc0542014-10-24 20:38:07 -0700102 log.warn("Failed to initialize native (epoll) transport. Reason: {}. Proceeding with nio.", t.getMessage());
Madan Jampani824a7c12014-10-21 09:46:15 -0700103 }
104 clientGroup = new NioEventLoopGroup();
105 serverGroup = new NioEventLoopGroup();
106 serverChannelClass = NioServerSocketChannel.class;
107 clientChannelClass = NioSocketChannel.class;
Madan Jampani5e83f332014-10-20 15:35:09 -0700108 }
109
Madan Jampani2e5f87b2015-02-22 10:37:15 -0800110 public NettyMessagingService(IpAddress ip, int port) {
Madan Jampani87100932014-10-21 16:46:12 -0700111 localEp = new Endpoint(ip, port);
112 }
113
Madan Jampaniab6d3112014-10-02 16:30:14 -0700114 public NettyMessagingService() {
Madan Jampaniab6d3112014-10-02 16:30:14 -0700115 this(8080);
116 }
117
Madan Jampaniab6d3112014-10-02 16:30:14 -0700118 public NettyMessagingService(int port) {
Madan Jampaniab6d3112014-10-02 16:30:14 -0700119 try {
Madan Jampani2e5f87b2015-02-22 10:37:15 -0800120 localEp = new Endpoint(IpAddress.valueOf(InetAddress.getLocalHost()), port);
Madan Jampaniab6d3112014-10-02 16:30:14 -0700121 } catch (UnknownHostException e) {
Ray Milkey3f0c97e2014-12-08 14:53:30 -0800122 // Cannot resolve the local host, something is very wrong. Bailing out.
123 throw new IllegalStateException("Cannot resolve local host", e);
Madan Jampaniab6d3112014-10-02 16:30:14 -0700124 }
125 }
126
Ray Milkey3f0c97e2014-12-08 14:53:30 -0800127 public void activate() throws InterruptedException {
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)
Madan Jampani49115e92015-03-14 10:43:33 -0700153 .withType(type)
Madan Jampaniab6d3112014-10-02 16:30:14 -0700154 .withPayload(payload)
155 .build();
156 sendAsync(ep, message);
157 }
158
159 protected void sendAsync(Endpoint ep, InternalMessage message) throws IOException {
Madan Jampaniba472232015-03-04 13:00:50 -0800160 if (ep.equals(localEp)) {
161 dispatchLocally(message);
162 return;
163 }
Madan Jampaniab6d3112014-10-02 16:30:14 -0700164 Channel channel = null;
165 try {
Madan Jampani86ed0552014-10-03 16:45:42 -0700166 try {
167 channel = channels.borrowObject(ep);
168 channel.eventLoop().execute(new WriteTask(channel, message));
169 } finally {
170 channels.returnObject(ep, channel);
171 }
Madan Jampani5f9ec9a2014-10-29 13:45:52 -0700172 } catch (IOException e) {
173 throw e;
Madan Jampaniab6d3112014-10-02 16:30:14 -0700174 } catch (Exception e) {
Madan Jampani5f9ec9a2014-10-29 13:45:52 -0700175 throw new IOException(e);
Madan Jampaniab6d3112014-10-02 16:30:14 -0700176 }
Madan Jampani5f9ec9a2014-10-29 13:45:52 -0700177
Madan Jampaniab6d3112014-10-02 16:30:14 -0700178 }
179
180 @Override
Madan Jampani24f9efb2014-10-24 18:56:23 -0700181 public ListenableFuture<byte[]> sendAndReceive(Endpoint ep, String type, byte[] payload)
Madan Jampaniab6d3112014-10-02 16:30:14 -0700182 throws IOException {
Madan Jampani24f9efb2014-10-24 18:56:23 -0700183 SettableFuture<byte[]> futureResponse = SettableFuture.create();
184 Long messageId = messageIdGenerator.incrementAndGet();
Madan Jampaniab6d3112014-10-02 16:30:14 -0700185 responseFutures.put(messageId, futureResponse);
186 InternalMessage message = new InternalMessage.Builder(this)
187 .withId(messageId)
188 .withSender(localEp)
Madan Jampani49115e92015-03-14 10:43:33 -0700189 .withType(type)
Madan Jampaniab6d3112014-10-02 16:30:14 -0700190 .withPayload(payload)
191 .build();
Madan Jampani15cd0b82014-10-28 08:40:23 -0700192 try {
193 sendAsync(ep, message);
Madan Jampani5f9ec9a2014-10-29 13:45:52 -0700194 } catch (Exception e) {
Madan Jampani15cd0b82014-10-28 08:40:23 -0700195 responseFutures.invalidate(messageId);
196 throw e;
197 }
Madan Jampaniab6d3112014-10-02 16:30:14 -0700198 return futureResponse;
199 }
200
201 @Override
202 public void registerHandler(String type, MessageHandler handler) {
Madan Jampani49115e92015-03-14 10:43:33 -0700203 handlers.putIfAbsent(type, handler);
Madan Jampaniab6d3112014-10-02 16:30:14 -0700204 }
205
Yuta HIGUCHIe5ca93b2014-10-23 09:49:00 -0700206 @Override
Madan Jampani2af244a2015-02-22 13:12:01 -0800207 public void registerHandler(String type, MessageHandler handler, ExecutorService executor) {
Madan Jampani49115e92015-03-14 10:43:33 -0700208 handlers.putIfAbsent(type, new MessageHandler() {
Madan Jampani2af244a2015-02-22 13:12:01 -0800209 @Override
210 public void handle(Message message) throws IOException {
211 executor.submit(() -> {
212 try {
213 handler.handle(message);
214 } catch (Exception e) {
Madan Jampani52860be2015-02-27 12:52:37 -0800215 log.debug("Failed to process message of type {}", type, e);
Madan Jampani2af244a2015-02-22 13:12:01 -0800216 }
217 });
218 }
219 });
220 }
221
222 @Override
Madan Jampaniab6d3112014-10-02 16:30:14 -0700223 public void unregisterHandler(String type) {
Madan Jampani49115e92015-03-14 10:43:33 -0700224 handlers.remove(type);
Madan Jampaniab6d3112014-10-02 16:30:14 -0700225 }
226
Madan Jampani49115e92015-03-14 10:43:33 -0700227 private MessageHandler getMessageHandler(String type) {
Madan Jampaniab6d3112014-10-02 16:30:14 -0700228 return handlers.get(type);
229 }
230
231 private void startAcceptingConnections() throws InterruptedException {
232 ServerBootstrap b = new ServerBootstrap();
Madan Jampani86ed0552014-10-03 16:45:42 -0700233 b.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 32 * 1024);
Madan Jampaniddf76222014-10-04 23:48:44 -0700234 b.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024);
Madan Jampaniab6d3112014-10-02 16:30:14 -0700235 b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
Madan Jampani824a7c12014-10-21 09:46:15 -0700236 b.group(serverGroup, clientGroup)
237 .channel(serverChannelClass)
Madan Jampaniab6d3112014-10-02 16:30:14 -0700238 .childHandler(new OnosCommunicationChannelInitializer())
239 .option(ChannelOption.SO_BACKLOG, 128)
240 .childOption(ChannelOption.SO_KEEPALIVE, true);
241
242 // Bind and start to accept incoming connections.
Madan Jampani87100932014-10-21 16:46:12 -0700243 b.bind(localEp.port()).sync();
Madan Jampaniab6d3112014-10-02 16:30:14 -0700244 }
245
246 private class OnosCommunicationChannelFactory
247 implements KeyedPoolableObjectFactory<Endpoint, Channel> {
248
249 @Override
250 public void activateObject(Endpoint endpoint, Channel channel)
251 throws Exception {
252 }
253
254 @Override
255 public void destroyObject(Endpoint ep, Channel channel) throws Exception {
256 channel.close();
257 }
258
259 @Override
260 public Channel makeObject(Endpoint ep) throws Exception {
Madan Jampaniddf76222014-10-04 23:48:44 -0700261 Bootstrap bootstrap = new Bootstrap();
262 bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
263 bootstrap.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 32 * 1024);
264 bootstrap.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024);
Madan Jampani824a7c12014-10-21 09:46:15 -0700265 bootstrap.group(clientGroup);
Madan Jampaniab6d3112014-10-02 16:30:14 -0700266 // TODO: Make this faster:
267 // http://normanmaurer.me/presentations/2014-facebook-eng-netty/slides.html#37.0
Madan Jampani824a7c12014-10-21 09:46:15 -0700268 bootstrap.channel(clientChannelClass);
Madan Jampaniddf76222014-10-04 23:48:44 -0700269 bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
270 bootstrap.handler(new OnosCommunicationChannelInitializer());
Madan Jampaniab6d3112014-10-02 16:30:14 -0700271 // Start the client.
Madan Jampani2e5f87b2015-02-22 10:37:15 -0800272 ChannelFuture f = bootstrap.connect(ep.host().toString(), ep.port()).sync();
Madan Jampaniab6d3112014-10-02 16:30:14 -0700273 return f.channel();
274 }
275
276 @Override
277 public void passivateObject(Endpoint ep, Channel channel)
278 throws Exception {
279 }
280
281 @Override
282 public boolean validateObject(Endpoint ep, Channel channel) {
283 return channel.isOpen();
284 }
285 }
286
287 private class OnosCommunicationChannelInitializer extends ChannelInitializer<SocketChannel> {
288
Madan Jampaniddf76222014-10-04 23:48:44 -0700289 private final ChannelHandler dispatcher = new InboundMessageDispatcher();
Madan Jampani53e44e62014-10-07 12:39:51 -0700290 private final ChannelHandler encoder = new MessageEncoder();
Madan Jampaniddf76222014-10-04 23:48:44 -0700291
Madan Jampaniab6d3112014-10-02 16:30:14 -0700292 @Override
293 protected void initChannel(SocketChannel channel) throws Exception {
294 channel.pipeline()
Madan Jampaniddf76222014-10-04 23:48:44 -0700295 .addLast("encoder", encoder)
Madan Jampani53e44e62014-10-07 12:39:51 -0700296 .addLast("decoder", new MessageDecoder(NettyMessagingService.this))
Madan Jampaniddf76222014-10-04 23:48:44 -0700297 .addLast("handler", dispatcher);
Madan Jampaniab6d3112014-10-02 16:30:14 -0700298 }
299 }
300
Yuta HIGUCHIe5ca93b2014-10-23 09:49:00 -0700301 private static class WriteTask implements Runnable {
Madan Jampaniab6d3112014-10-02 16:30:14 -0700302
Madan Jampani86ed0552014-10-03 16:45:42 -0700303 private final InternalMessage message;
Madan Jampaniab6d3112014-10-02 16:30:14 -0700304 private final Channel channel;
305
Madan Jampani86ed0552014-10-03 16:45:42 -0700306 public WriteTask(Channel channel, InternalMessage message) {
Madan Jampaniab6d3112014-10-02 16:30:14 -0700307 this.channel = channel;
Madan Jampani86ed0552014-10-03 16:45:42 -0700308 this.message = message;
Madan Jampaniab6d3112014-10-02 16:30:14 -0700309 }
310
311 @Override
312 public void run() {
Madan Jampani5f9ec9a2014-10-29 13:45:52 -0700313 channel.writeAndFlush(message).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
Madan Jampaniab6d3112014-10-02 16:30:14 -0700314 }
315 }
316
Madan Jampaniddf76222014-10-04 23:48:44 -0700317 @ChannelHandler.Sharable
Madan Jampaniab6d3112014-10-02 16:30:14 -0700318 private class InboundMessageDispatcher extends SimpleChannelInboundHandler<InternalMessage> {
319
320 @Override
321 protected void channelRead0(ChannelHandlerContext ctx, InternalMessage message) throws Exception {
Madan Jampaniba472232015-03-04 13:00:50 -0800322 dispatchLocally(message);
Madan Jampaniab6d3112014-10-02 16:30:14 -0700323 }
Madan Jampani86ed0552014-10-03 16:45:42 -0700324
Madan Jampani86ed0552014-10-03 16:45:42 -0700325 @Override
326 public void exceptionCaught(ChannelHandlerContext context, Throwable cause) {
Madan Jampani29e5dfd2014-10-07 17:26:25 -0700327 log.error("Exception inside channel handling pipeline.", cause);
Madan Jampani86ed0552014-10-03 16:45:42 -0700328 context.close();
329 }
Madan Jampaniab6d3112014-10-02 16:30:14 -0700330 }
Madan Jampani2e5f87b2015-02-22 10:37:15 -0800331
Madan Jampaniba472232015-03-04 13:00:50 -0800332 private void dispatchLocally(InternalMessage message) throws IOException {
Madan Jampani49115e92015-03-14 10:43:33 -0700333 String type = message.type();
334 if (InternalMessage.REPLY_MESSAGE_TYPE.equals(type)) {
Madan Jampaniba472232015-03-04 13:00:50 -0800335 try {
336 SettableFuture<byte[]> futureResponse =
337 NettyMessagingService.this.responseFutures.getIfPresent(message.id());
338 if (futureResponse != null) {
339 futureResponse.set(message.payload());
340 } else {
341 log.warn("Received a reply for message id:[{}]. "
342 + " from {}. But was unable to locate the"
343 + " request handle", message.id(), message.sender());
344 }
345 } finally {
346 NettyMessagingService.this.responseFutures.invalidate(message.id());
347 }
348 return;
349 }
350 MessageHandler handler = NettyMessagingService.this.getMessageHandler(type);
351 if (handler != null) {
352 handler.handle(message);
353 } else {
354 log.debug("No handler registered for {}", type);
355 }
356 }
Madan Jampani2e5f87b2015-02-22 10:37:15 -0800357}