blob: ae646b69c7f02d149cd0640641223e94e7b984be [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) {
75 entry.getValue().setException(new TimeoutException("Timedout waiting for reply"));
76 }
77 })
Madan Jampaniddf76222014-10-04 23:48:44 -070078 .build();
79 private final GenericKeyedObjectPool<Endpoint, Channel> channels
80 = new GenericKeyedObjectPool<Endpoint, Channel>(new OnosCommunicationChannelFactory());
Madan Jampaniab6d3112014-10-02 16:30:14 -070081
Madan Jampani824a7c12014-10-21 09:46:15 -070082 private EventLoopGroup serverGroup;
83 private EventLoopGroup clientGroup;
84 private Class<? extends ServerChannel> serverChannelClass;
85 private Class<? extends Channel> clientChannelClass;
86
Madan Jampani5e83f332014-10-20 15:35:09 -070087 private void initEventLoopGroup() {
Madan Jampani824a7c12014-10-21 09:46:15 -070088 // try Epoll first and if that does work, use nio.
Madan Jampani824a7c12014-10-21 09:46:15 -070089 try {
Madan Jampani99e9fe22014-10-21 13:47:12 -070090 clientGroup = new EpollEventLoopGroup();
91 serverGroup = new EpollEventLoopGroup();
92 serverChannelClass = EpollServerSocketChannel.class;
93 clientChannelClass = EpollSocketChannel.class;
94 return;
Madan Jampani824a7c12014-10-21 09:46:15 -070095 } catch (Throwable t) {
Madan Jampanicfbc0542014-10-24 20:38:07 -070096 log.warn("Failed to initialize native (epoll) transport. Reason: {}. Proceeding with nio.", t.getMessage());
Madan Jampani824a7c12014-10-21 09:46:15 -070097 }
98 clientGroup = new NioEventLoopGroup();
99 serverGroup = new NioEventLoopGroup();
100 serverChannelClass = NioServerSocketChannel.class;
101 clientChannelClass = NioSocketChannel.class;
Madan Jampani5e83f332014-10-20 15:35:09 -0700102 }
103
Madan Jampani87100932014-10-21 16:46:12 -0700104 public NettyMessagingService(String ip, int port) {
105 localEp = new Endpoint(ip, port);
106 }
107
Madan Jampaniab6d3112014-10-02 16:30:14 -0700108 public NettyMessagingService() {
Madan Jampaniab6d3112014-10-02 16:30:14 -0700109 this(8080);
110 }
111
Madan Jampaniab6d3112014-10-02 16:30:14 -0700112 public NettyMessagingService(int port) {
Madan Jampaniab6d3112014-10-02 16:30:14 -0700113 try {
114 localEp = new Endpoint(java.net.InetAddress.getLocalHost().getHostName(), port);
115 } catch (UnknownHostException e) {
Ray Milkey3f0c97e2014-12-08 14:53:30 -0800116 // Cannot resolve the local host, something is very wrong. Bailing out.
117 throw new IllegalStateException("Cannot resolve local host", e);
Madan Jampaniab6d3112014-10-02 16:30:14 -0700118 }
119 }
120
Ray Milkey3f0c97e2014-12-08 14:53:30 -0800121 public void activate() throws InterruptedException {
Madan Jampani86ed0552014-10-03 16:45:42 -0700122 channels.setTestOnBorrow(true);
123 channels.setTestOnReturn(true);
Madan Jampani5e83f332014-10-20 15:35:09 -0700124 initEventLoopGroup();
Madan Jampaniab6d3112014-10-02 16:30:14 -0700125 startAcceptingConnections();
126 }
127
128 public void deactivate() throws Exception {
129 channels.close();
Madan Jampani824a7c12014-10-21 09:46:15 -0700130 serverGroup.shutdownGracefully();
131 clientGroup.shutdownGracefully();
Madan Jampaniab6d3112014-10-02 16:30:14 -0700132 }
133
Madan Jampani87100932014-10-21 16:46:12 -0700134 /**
135 * Returns the local endpoint for this instance.
136 * @return local end point.
137 */
138 public Endpoint localEp() {
139 return localEp;
140 }
141
Madan Jampaniab6d3112014-10-02 16:30:14 -0700142 @Override
Madan Jampani53e44e62014-10-07 12:39:51 -0700143 public void sendAsync(Endpoint ep, String type, byte[] payload) throws IOException {
Madan Jampaniab6d3112014-10-02 16:30:14 -0700144 InternalMessage message = new InternalMessage.Builder(this)
Madan Jampani24f9efb2014-10-24 18:56:23 -0700145 .withId(messageIdGenerator.incrementAndGet())
Madan Jampaniab6d3112014-10-02 16:30:14 -0700146 .withSender(localEp)
147 .withType(type)
148 .withPayload(payload)
149 .build();
150 sendAsync(ep, message);
151 }
152
153 protected void sendAsync(Endpoint ep, InternalMessage message) throws IOException {
154 Channel channel = null;
155 try {
Madan Jampani86ed0552014-10-03 16:45:42 -0700156 try {
157 channel = channels.borrowObject(ep);
158 channel.eventLoop().execute(new WriteTask(channel, message));
159 } finally {
160 channels.returnObject(ep, channel);
161 }
Madan Jampani5f9ec9a2014-10-29 13:45:52 -0700162 } catch (IOException e) {
163 throw e;
Madan Jampaniab6d3112014-10-02 16:30:14 -0700164 } catch (Exception e) {
Madan Jampani5f9ec9a2014-10-29 13:45:52 -0700165 throw new IOException(e);
Madan Jampaniab6d3112014-10-02 16:30:14 -0700166 }
Madan Jampani5f9ec9a2014-10-29 13:45:52 -0700167
Madan Jampaniab6d3112014-10-02 16:30:14 -0700168 }
169
170 @Override
Madan Jampani24f9efb2014-10-24 18:56:23 -0700171 public ListenableFuture<byte[]> sendAndReceive(Endpoint ep, String type, byte[] payload)
Madan Jampaniab6d3112014-10-02 16:30:14 -0700172 throws IOException {
Madan Jampani24f9efb2014-10-24 18:56:23 -0700173 SettableFuture<byte[]> futureResponse = SettableFuture.create();
174 Long messageId = messageIdGenerator.incrementAndGet();
Madan Jampaniab6d3112014-10-02 16:30:14 -0700175 responseFutures.put(messageId, futureResponse);
176 InternalMessage message = new InternalMessage.Builder(this)
177 .withId(messageId)
178 .withSender(localEp)
179 .withType(type)
180 .withPayload(payload)
181 .build();
Madan Jampani15cd0b82014-10-28 08:40:23 -0700182 try {
183 sendAsync(ep, message);
Madan Jampani5f9ec9a2014-10-29 13:45:52 -0700184 } catch (Exception e) {
Madan Jampani15cd0b82014-10-28 08:40:23 -0700185 responseFutures.invalidate(messageId);
186 throw e;
187 }
Madan Jampaniab6d3112014-10-02 16:30:14 -0700188 return futureResponse;
189 }
190
191 @Override
192 public void registerHandler(String type, MessageHandler handler) {
Madan Jampaniab6d3112014-10-02 16:30:14 -0700193 handlers.putIfAbsent(type, handler);
194 }
195
Yuta HIGUCHIe5ca93b2014-10-23 09:49:00 -0700196 @Override
Madan Jampaniab6d3112014-10-02 16:30:14 -0700197 public void unregisterHandler(String type) {
198 handlers.remove(type);
199 }
200
201 private MessageHandler getMessageHandler(String type) {
202 return handlers.get(type);
203 }
204
205 private void startAcceptingConnections() throws InterruptedException {
206 ServerBootstrap b = new ServerBootstrap();
Madan Jampani86ed0552014-10-03 16:45:42 -0700207 b.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 32 * 1024);
Madan Jampaniddf76222014-10-04 23:48:44 -0700208 b.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024);
Madan Jampaniab6d3112014-10-02 16:30:14 -0700209 b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
Madan Jampani824a7c12014-10-21 09:46:15 -0700210 b.group(serverGroup, clientGroup)
211 .channel(serverChannelClass)
Madan Jampaniab6d3112014-10-02 16:30:14 -0700212 .childHandler(new OnosCommunicationChannelInitializer())
213 .option(ChannelOption.SO_BACKLOG, 128)
214 .childOption(ChannelOption.SO_KEEPALIVE, true);
215
216 // Bind and start to accept incoming connections.
Madan Jampani87100932014-10-21 16:46:12 -0700217 b.bind(localEp.port()).sync();
Madan Jampaniab6d3112014-10-02 16:30:14 -0700218 }
219
220 private class OnosCommunicationChannelFactory
221 implements KeyedPoolableObjectFactory<Endpoint, Channel> {
222
223 @Override
224 public void activateObject(Endpoint endpoint, Channel channel)
225 throws Exception {
226 }
227
228 @Override
229 public void destroyObject(Endpoint ep, Channel channel) throws Exception {
230 channel.close();
231 }
232
233 @Override
234 public Channel makeObject(Endpoint ep) throws Exception {
Madan Jampaniddf76222014-10-04 23:48:44 -0700235 Bootstrap bootstrap = new Bootstrap();
236 bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
237 bootstrap.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 32 * 1024);
238 bootstrap.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024);
Madan Jampani824a7c12014-10-21 09:46:15 -0700239 bootstrap.group(clientGroup);
Madan Jampaniab6d3112014-10-02 16:30:14 -0700240 // TODO: Make this faster:
241 // http://normanmaurer.me/presentations/2014-facebook-eng-netty/slides.html#37.0
Madan Jampani824a7c12014-10-21 09:46:15 -0700242 bootstrap.channel(clientChannelClass);
Madan Jampaniddf76222014-10-04 23:48:44 -0700243 bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
244 bootstrap.handler(new OnosCommunicationChannelInitializer());
Madan Jampaniab6d3112014-10-02 16:30:14 -0700245 // Start the client.
Madan Jampaniddf76222014-10-04 23:48:44 -0700246 ChannelFuture f = bootstrap.connect(ep.host(), ep.port()).sync();
Madan Jampaniab6d3112014-10-02 16:30:14 -0700247 return f.channel();
248 }
249
250 @Override
251 public void passivateObject(Endpoint ep, Channel channel)
252 throws Exception {
253 }
254
255 @Override
256 public boolean validateObject(Endpoint ep, Channel channel) {
257 return channel.isOpen();
258 }
259 }
260
261 private class OnosCommunicationChannelInitializer extends ChannelInitializer<SocketChannel> {
262
Madan Jampaniddf76222014-10-04 23:48:44 -0700263 private final ChannelHandler dispatcher = new InboundMessageDispatcher();
Madan Jampani53e44e62014-10-07 12:39:51 -0700264 private final ChannelHandler encoder = new MessageEncoder();
Madan Jampaniddf76222014-10-04 23:48:44 -0700265
Madan Jampaniab6d3112014-10-02 16:30:14 -0700266 @Override
267 protected void initChannel(SocketChannel channel) throws Exception {
268 channel.pipeline()
Madan Jampaniddf76222014-10-04 23:48:44 -0700269 .addLast("encoder", encoder)
Madan Jampani53e44e62014-10-07 12:39:51 -0700270 .addLast("decoder", new MessageDecoder(NettyMessagingService.this))
Madan Jampaniddf76222014-10-04 23:48:44 -0700271 .addLast("handler", dispatcher);
Madan Jampaniab6d3112014-10-02 16:30:14 -0700272 }
273 }
274
Yuta HIGUCHIe5ca93b2014-10-23 09:49:00 -0700275 private static class WriteTask implements Runnable {
Madan Jampaniab6d3112014-10-02 16:30:14 -0700276
Madan Jampani86ed0552014-10-03 16:45:42 -0700277 private final InternalMessage message;
Madan Jampaniab6d3112014-10-02 16:30:14 -0700278 private final Channel channel;
279
Madan Jampani86ed0552014-10-03 16:45:42 -0700280 public WriteTask(Channel channel, InternalMessage message) {
Madan Jampaniab6d3112014-10-02 16:30:14 -0700281 this.channel = channel;
Madan Jampani86ed0552014-10-03 16:45:42 -0700282 this.message = message;
Madan Jampaniab6d3112014-10-02 16:30:14 -0700283 }
284
285 @Override
286 public void run() {
Madan Jampani5f9ec9a2014-10-29 13:45:52 -0700287 channel.writeAndFlush(message).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
Madan Jampaniab6d3112014-10-02 16:30:14 -0700288 }
289 }
290
Madan Jampaniddf76222014-10-04 23:48:44 -0700291 @ChannelHandler.Sharable
Madan Jampaniab6d3112014-10-02 16:30:14 -0700292 private class InboundMessageDispatcher extends SimpleChannelInboundHandler<InternalMessage> {
293
294 @Override
295 protected void channelRead0(ChannelHandlerContext ctx, InternalMessage message) throws Exception {
296 String type = message.type();
297 if (type.equals(InternalMessage.REPLY_MESSAGE_TYPE)) {
298 try {
Madan Jampani24f9efb2014-10-24 18:56:23 -0700299 SettableFuture<byte[]> futureResponse =
Madan Jampaniab6d3112014-10-02 16:30:14 -0700300 NettyMessagingService.this.responseFutures.getIfPresent(message.id());
301 if (futureResponse != null) {
Madan Jampani24f9efb2014-10-24 18:56:23 -0700302 futureResponse.set(message.payload());
Madan Jampanif1d425a2014-10-07 09:52:36 -0700303 } else {
Madan Jampani15cd0b82014-10-28 08:40:23 -0700304 log.warn("Received a reply for message id:[{}]. "
Madan Jampani348a9fe2014-11-09 01:37:51 -0800305 + " from {}. But was unable to locate the"
306 + " request handle", message.id(), message.sender());
Madan Jampaniab6d3112014-10-02 16:30:14 -0700307 }
Madan Jampaniab6d3112014-10-02 16:30:14 -0700308 } finally {
309 NettyMessagingService.this.responseFutures.invalidate(message.id());
310 }
311 return;
312 }
313 MessageHandler handler = NettyMessagingService.this.getMessageHandler(type);
Yuta HIGUCHI5f9d6962014-11-07 13:06:45 -0800314 if (handler != null) {
315 handler.handle(message);
316 } else {
317 log.debug("No handler registered for {}", type);
318 }
Madan Jampaniab6d3112014-10-02 16:30:14 -0700319 }
Madan Jampani86ed0552014-10-03 16:45:42 -0700320
Madan Jampani86ed0552014-10-03 16:45:42 -0700321 @Override
322 public void exceptionCaught(ChannelHandlerContext context, Throwable cause) {
Madan Jampani29e5dfd2014-10-07 17:26:25 -0700323 log.error("Exception inside channel handling pipeline.", cause);
Madan Jampani86ed0552014-10-03 16:45:42 -0700324 context.close();
325 }
Madan Jampaniab6d3112014-10-02 16:30:14 -0700326 }
327}