blob: 5b7266ed36ba448d24c2a00964d3f6d50a13a1d1 [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 Jampani5f9ec9a2014-10-29 13:45:52 -070023import java.util.concurrent.TimeoutException;
Madan Jampani24f9efb2014-10-24 18:56:23 -070024import java.util.concurrent.atomic.AtomicLong;
Madan Jampaniab6d3112014-10-02 16:30:14 -070025
26import io.netty.bootstrap.Bootstrap;
27import io.netty.bootstrap.ServerBootstrap;
28import io.netty.buffer.PooledByteBufAllocator;
29import io.netty.channel.Channel;
30import io.netty.channel.ChannelFuture;
Madan Jampani5f9ec9a2014-10-29 13:45:52 -070031import io.netty.channel.ChannelFutureListener;
Madan Jampaniddf76222014-10-04 23:48:44 -070032import io.netty.channel.ChannelHandler;
Madan Jampaniab6d3112014-10-02 16:30:14 -070033import io.netty.channel.ChannelHandlerContext;
34import io.netty.channel.ChannelInitializer;
35import io.netty.channel.ChannelOption;
36import io.netty.channel.EventLoopGroup;
Madan Jampani824a7c12014-10-21 09:46:15 -070037import io.netty.channel.ServerChannel;
Madan Jampaniab6d3112014-10-02 16:30:14 -070038import io.netty.channel.SimpleChannelInboundHandler;
Madan Jampani824a7c12014-10-21 09:46:15 -070039import io.netty.channel.epoll.EpollEventLoopGroup;
40import io.netty.channel.epoll.EpollServerSocketChannel;
41import io.netty.channel.epoll.EpollSocketChannel;
Madan Jampaniab6d3112014-10-02 16:30:14 -070042import io.netty.channel.nio.NioEventLoopGroup;
43import io.netty.channel.socket.SocketChannel;
44import io.netty.channel.socket.nio.NioServerSocketChannel;
45import io.netty.channel.socket.nio.NioSocketChannel;
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.
89 // TODO: make this configurable.
90 try {
Madan Jampani99e9fe22014-10-21 13:47:12 -070091 clientGroup = new EpollEventLoopGroup();
92 serverGroup = new EpollEventLoopGroup();
93 serverChannelClass = EpollServerSocketChannel.class;
94 clientChannelClass = EpollSocketChannel.class;
95 return;
Madan Jampani824a7c12014-10-21 09:46:15 -070096 } catch (Throwable t) {
Madan Jampanicfbc0542014-10-24 20:38:07 -070097 log.warn("Failed to initialize native (epoll) transport. Reason: {}. Proceeding with nio.", t.getMessage());
Madan Jampani824a7c12014-10-21 09:46:15 -070098 }
99 clientGroup = new NioEventLoopGroup();
100 serverGroup = new NioEventLoopGroup();
101 serverChannelClass = NioServerSocketChannel.class;
102 clientChannelClass = NioSocketChannel.class;
Madan Jampani5e83f332014-10-20 15:35:09 -0700103 }
104
Madan Jampani87100932014-10-21 16:46:12 -0700105 public NettyMessagingService(String ip, int port) {
106 localEp = new Endpoint(ip, port);
107 }
108
Madan Jampaniab6d3112014-10-02 16:30:14 -0700109 public NettyMessagingService() {
110 // TODO: Default port should be configurable.
111 this(8080);
112 }
113
114 // FIXME: Constructor should not throw exceptions.
115 public NettyMessagingService(int port) {
Madan Jampaniab6d3112014-10-02 16:30:14 -0700116 try {
117 localEp = new Endpoint(java.net.InetAddress.getLocalHost().getHostName(), port);
118 } catch (UnknownHostException e) {
119 // bailing out.
120 throw new RuntimeException(e);
121 }
122 }
123
124 public void activate() throws Exception {
Madan Jampani86ed0552014-10-03 16:45:42 -0700125 channels.setTestOnBorrow(true);
126 channels.setTestOnReturn(true);
Madan Jampani5e83f332014-10-20 15:35:09 -0700127 initEventLoopGroup();
Madan Jampaniab6d3112014-10-02 16:30:14 -0700128 startAcceptingConnections();
129 }
130
131 public void deactivate() throws Exception {
132 channels.close();
Madan Jampani824a7c12014-10-21 09:46:15 -0700133 serverGroup.shutdownGracefully();
134 clientGroup.shutdownGracefully();
Madan Jampaniab6d3112014-10-02 16:30:14 -0700135 }
136
Madan Jampani87100932014-10-21 16:46:12 -0700137 /**
138 * Returns the local endpoint for this instance.
139 * @return local end point.
140 */
141 public Endpoint localEp() {
142 return localEp;
143 }
144
Madan Jampaniab6d3112014-10-02 16:30:14 -0700145 @Override
Madan Jampani53e44e62014-10-07 12:39:51 -0700146 public void sendAsync(Endpoint ep, String type, byte[] payload) throws IOException {
Madan Jampaniab6d3112014-10-02 16:30:14 -0700147 InternalMessage message = new InternalMessage.Builder(this)
Madan Jampani24f9efb2014-10-24 18:56:23 -0700148 .withId(messageIdGenerator.incrementAndGet())
Madan Jampaniab6d3112014-10-02 16:30:14 -0700149 .withSender(localEp)
150 .withType(type)
151 .withPayload(payload)
152 .build();
153 sendAsync(ep, message);
154 }
155
156 protected void sendAsync(Endpoint ep, InternalMessage message) throws IOException {
157 Channel channel = null;
158 try {
Madan Jampani86ed0552014-10-03 16:45:42 -0700159 try {
160 channel = channels.borrowObject(ep);
161 channel.eventLoop().execute(new WriteTask(channel, message));
162 } finally {
163 channels.returnObject(ep, channel);
164 }
Madan Jampani5f9ec9a2014-10-29 13:45:52 -0700165 } catch (IOException e) {
166 throw e;
Madan Jampaniab6d3112014-10-02 16:30:14 -0700167 } catch (Exception e) {
Madan Jampani5f9ec9a2014-10-29 13:45:52 -0700168 throw new IOException(e);
Madan Jampaniab6d3112014-10-02 16:30:14 -0700169 }
Madan Jampani5f9ec9a2014-10-29 13:45:52 -0700170
Madan Jampaniab6d3112014-10-02 16:30:14 -0700171 }
172
173 @Override
Madan Jampani24f9efb2014-10-24 18:56:23 -0700174 public ListenableFuture<byte[]> sendAndReceive(Endpoint ep, String type, byte[] payload)
Madan Jampaniab6d3112014-10-02 16:30:14 -0700175 throws IOException {
Madan Jampani24f9efb2014-10-24 18:56:23 -0700176 SettableFuture<byte[]> futureResponse = SettableFuture.create();
177 Long messageId = messageIdGenerator.incrementAndGet();
Madan Jampaniab6d3112014-10-02 16:30:14 -0700178 responseFutures.put(messageId, futureResponse);
179 InternalMessage message = new InternalMessage.Builder(this)
180 .withId(messageId)
181 .withSender(localEp)
182 .withType(type)
183 .withPayload(payload)
184 .build();
Madan Jampani15cd0b82014-10-28 08:40:23 -0700185 try {
186 sendAsync(ep, message);
Madan Jampani5f9ec9a2014-10-29 13:45:52 -0700187 } catch (Exception e) {
Madan Jampani15cd0b82014-10-28 08:40:23 -0700188 responseFutures.invalidate(messageId);
189 throw e;
190 }
Madan Jampaniab6d3112014-10-02 16:30:14 -0700191 return futureResponse;
192 }
193
194 @Override
195 public void registerHandler(String type, MessageHandler handler) {
196 // TODO: Is this the right semantics for handler registration?
197 handlers.putIfAbsent(type, handler);
198 }
199
Yuta HIGUCHIe5ca93b2014-10-23 09:49:00 -0700200 @Override
Madan Jampaniab6d3112014-10-02 16:30:14 -0700201 public void unregisterHandler(String type) {
202 handlers.remove(type);
203 }
204
205 private MessageHandler getMessageHandler(String type) {
206 return handlers.get(type);
207 }
208
209 private void startAcceptingConnections() throws InterruptedException {
210 ServerBootstrap b = new ServerBootstrap();
Madan Jampani86ed0552014-10-03 16:45:42 -0700211 b.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 32 * 1024);
Madan Jampaniddf76222014-10-04 23:48:44 -0700212 b.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024);
213 // TODO: Need JVM options to configure PooledByteBufAllocator.
Madan Jampaniab6d3112014-10-02 16:30:14 -0700214 b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
Madan Jampani824a7c12014-10-21 09:46:15 -0700215 b.group(serverGroup, clientGroup)
216 .channel(serverChannelClass)
Madan Jampaniab6d3112014-10-02 16:30:14 -0700217 .childHandler(new OnosCommunicationChannelInitializer())
218 .option(ChannelOption.SO_BACKLOG, 128)
219 .childOption(ChannelOption.SO_KEEPALIVE, true);
220
221 // Bind and start to accept incoming connections.
Madan Jampani87100932014-10-21 16:46:12 -0700222 b.bind(localEp.port()).sync();
Madan Jampaniab6d3112014-10-02 16:30:14 -0700223 }
224
225 private class OnosCommunicationChannelFactory
226 implements KeyedPoolableObjectFactory<Endpoint, Channel> {
227
228 @Override
229 public void activateObject(Endpoint endpoint, Channel channel)
230 throws Exception {
231 }
232
233 @Override
234 public void destroyObject(Endpoint ep, Channel channel) throws Exception {
235 channel.close();
236 }
237
238 @Override
239 public Channel makeObject(Endpoint ep) throws Exception {
Madan Jampaniddf76222014-10-04 23:48:44 -0700240 Bootstrap bootstrap = new Bootstrap();
241 bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
242 bootstrap.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 32 * 1024);
243 bootstrap.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024);
Madan Jampani824a7c12014-10-21 09:46:15 -0700244 bootstrap.group(clientGroup);
Madan Jampaniab6d3112014-10-02 16:30:14 -0700245 // TODO: Make this faster:
246 // http://normanmaurer.me/presentations/2014-facebook-eng-netty/slides.html#37.0
Madan Jampani824a7c12014-10-21 09:46:15 -0700247 bootstrap.channel(clientChannelClass);
Madan Jampaniddf76222014-10-04 23:48:44 -0700248 bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
249 bootstrap.handler(new OnosCommunicationChannelInitializer());
Madan Jampaniab6d3112014-10-02 16:30:14 -0700250 // Start the client.
Madan Jampaniddf76222014-10-04 23:48:44 -0700251 ChannelFuture f = bootstrap.connect(ep.host(), ep.port()).sync();
Madan Jampaniab6d3112014-10-02 16:30:14 -0700252 return f.channel();
253 }
254
255 @Override
256 public void passivateObject(Endpoint ep, Channel channel)
257 throws Exception {
258 }
259
260 @Override
261 public boolean validateObject(Endpoint ep, Channel channel) {
262 return channel.isOpen();
263 }
264 }
265
266 private class OnosCommunicationChannelInitializer extends ChannelInitializer<SocketChannel> {
267
Madan Jampaniddf76222014-10-04 23:48:44 -0700268 private final ChannelHandler dispatcher = new InboundMessageDispatcher();
Madan Jampani53e44e62014-10-07 12:39:51 -0700269 private final ChannelHandler encoder = new MessageEncoder();
Madan Jampaniddf76222014-10-04 23:48:44 -0700270
Madan Jampaniab6d3112014-10-02 16:30:14 -0700271 @Override
272 protected void initChannel(SocketChannel channel) throws Exception {
273 channel.pipeline()
Madan Jampaniddf76222014-10-04 23:48:44 -0700274 .addLast("encoder", encoder)
Madan Jampani53e44e62014-10-07 12:39:51 -0700275 .addLast("decoder", new MessageDecoder(NettyMessagingService.this))
Madan Jampaniddf76222014-10-04 23:48:44 -0700276 .addLast("handler", dispatcher);
Madan Jampaniab6d3112014-10-02 16:30:14 -0700277 }
278 }
279
Yuta HIGUCHIe5ca93b2014-10-23 09:49:00 -0700280 private static class WriteTask implements Runnable {
Madan Jampaniab6d3112014-10-02 16:30:14 -0700281
Madan Jampani86ed0552014-10-03 16:45:42 -0700282 private final InternalMessage message;
Madan Jampaniab6d3112014-10-02 16:30:14 -0700283 private final Channel channel;
284
Madan Jampani86ed0552014-10-03 16:45:42 -0700285 public WriteTask(Channel channel, InternalMessage message) {
Madan Jampaniab6d3112014-10-02 16:30:14 -0700286 this.channel = channel;
Madan Jampani86ed0552014-10-03 16:45:42 -0700287 this.message = message;
Madan Jampaniab6d3112014-10-02 16:30:14 -0700288 }
289
290 @Override
291 public void run() {
Madan Jampani5f9ec9a2014-10-29 13:45:52 -0700292 channel.writeAndFlush(message).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
Madan Jampaniab6d3112014-10-02 16:30:14 -0700293 }
294 }
295
Madan Jampaniddf76222014-10-04 23:48:44 -0700296 @ChannelHandler.Sharable
Madan Jampaniab6d3112014-10-02 16:30:14 -0700297 private class InboundMessageDispatcher extends SimpleChannelInboundHandler<InternalMessage> {
298
299 @Override
300 protected void channelRead0(ChannelHandlerContext ctx, InternalMessage message) throws Exception {
301 String type = message.type();
302 if (type.equals(InternalMessage.REPLY_MESSAGE_TYPE)) {
303 try {
Madan Jampani24f9efb2014-10-24 18:56:23 -0700304 SettableFuture<byte[]> futureResponse =
Madan Jampaniab6d3112014-10-02 16:30:14 -0700305 NettyMessagingService.this.responseFutures.getIfPresent(message.id());
306 if (futureResponse != null) {
Madan Jampani24f9efb2014-10-24 18:56:23 -0700307 futureResponse.set(message.payload());
Madan Jampanif1d425a2014-10-07 09:52:36 -0700308 } else {
Madan Jampani15cd0b82014-10-28 08:40:23 -0700309 log.warn("Received a reply for message id:[{}]. "
310 + "But was unable to locate the request handle", message.id());
Madan Jampaniab6d3112014-10-02 16:30:14 -0700311 }
Madan Jampaniab6d3112014-10-02 16:30:14 -0700312 } finally {
313 NettyMessagingService.this.responseFutures.invalidate(message.id());
314 }
315 return;
316 }
317 MessageHandler handler = NettyMessagingService.this.getMessageHandler(type);
Yuta HIGUCHI5f9d6962014-11-07 13:06:45 -0800318 if (handler != null) {
319 handler.handle(message);
320 } else {
321 log.debug("No handler registered for {}", type);
322 }
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 }
331}