blob: 33870e205a21705f597f5ba244c43a86d35120e3 [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 Jampani24f9efb2014-10-24 18:56:23 -070026import java.util.concurrent.atomic.AtomicLong;
Madan Jampaniab6d3112014-10-02 16:30:14 -070027
28import io.netty.bootstrap.Bootstrap;
29import io.netty.bootstrap.ServerBootstrap;
30import io.netty.buffer.PooledByteBufAllocator;
31import io.netty.channel.Channel;
32import io.netty.channel.ChannelFuture;
Madan Jampaniddf76222014-10-04 23:48:44 -070033import io.netty.channel.ChannelHandler;
Madan Jampaniab6d3112014-10-02 16:30:14 -070034import io.netty.channel.ChannelHandlerContext;
35import io.netty.channel.ChannelInitializer;
36import io.netty.channel.ChannelOption;
37import io.netty.channel.EventLoopGroup;
Madan Jampani824a7c12014-10-21 09:46:15 -070038import io.netty.channel.ServerChannel;
Madan Jampaniab6d3112014-10-02 16:30:14 -070039import io.netty.channel.SimpleChannelInboundHandler;
Madan Jampani824a7c12014-10-21 09:46:15 -070040import io.netty.channel.epoll.EpollEventLoopGroup;
41import io.netty.channel.epoll.EpollServerSocketChannel;
42import io.netty.channel.epoll.EpollSocketChannel;
Madan Jampaniab6d3112014-10-02 16:30:14 -070043import io.netty.channel.nio.NioEventLoopGroup;
44import io.netty.channel.socket.SocketChannel;
45import io.netty.channel.socket.nio.NioServerSocketChannel;
46import io.netty.channel.socket.nio.NioSocketChannel;
47
Madan Jampaniab6d3112014-10-02 16:30:14 -070048import org.apache.commons.pool.KeyedPoolableObjectFactory;
49import org.apache.commons.pool.impl.GenericKeyedObjectPool;
50import org.slf4j.Logger;
51import org.slf4j.LoggerFactory;
52
53import com.google.common.cache.Cache;
54import com.google.common.cache.CacheBuilder;
Madan Jampani24f9efb2014-10-24 18:56:23 -070055import com.google.common.util.concurrent.ListenableFuture;
56import com.google.common.util.concurrent.SettableFuture;
Madan Jampaniab6d3112014-10-02 16:30:14 -070057
58/**
59 * A Netty based implementation of MessagingService.
60 */
61public class NettyMessagingService implements MessagingService {
62
63 private final Logger log = LoggerFactory.getLogger(getClass());
64
Madan Jampaniddf76222014-10-04 23:48:44 -070065 private final Endpoint localEp;
Madan Jampaniab6d3112014-10-02 16:30:14 -070066 private final ConcurrentMap<String, MessageHandler> handlers = new ConcurrentHashMap<>();
Madan Jampani24f9efb2014-10-24 18:56:23 -070067 private final AtomicLong messageIdGenerator = new AtomicLong(0);
68 private final Cache<Long, SettableFuture<byte[]>> responseFutures = CacheBuilder.newBuilder()
Madan Jampaniddf76222014-10-04 23:48:44 -070069 .maximumSize(100000)
Madan Jampaniddf76222014-10-04 23:48:44 -070070 // TODO: Once the entry expires, notify blocking threads (if any).
71 .expireAfterWrite(10, TimeUnit.MINUTES)
72 .build();
73 private final GenericKeyedObjectPool<Endpoint, Channel> channels
74 = new GenericKeyedObjectPool<Endpoint, Channel>(new OnosCommunicationChannelFactory());
Madan Jampaniab6d3112014-10-02 16:30:14 -070075
Madan Jampani824a7c12014-10-21 09:46:15 -070076 private EventLoopGroup serverGroup;
77 private EventLoopGroup clientGroup;
78 private Class<? extends ServerChannel> serverChannelClass;
79 private Class<? extends Channel> clientChannelClass;
80
Madan Jampani5e83f332014-10-20 15:35:09 -070081 private void initEventLoopGroup() {
Madan Jampani824a7c12014-10-21 09:46:15 -070082 // try Epoll first and if that does work, use nio.
83 // TODO: make this configurable.
84 try {
Madan Jampani99e9fe22014-10-21 13:47:12 -070085 clientGroup = new EpollEventLoopGroup();
86 serverGroup = new EpollEventLoopGroup();
87 serverChannelClass = EpollServerSocketChannel.class;
88 clientChannelClass = EpollSocketChannel.class;
89 return;
Madan Jampani824a7c12014-10-21 09:46:15 -070090 } catch (Throwable t) {
Madan Jampanicfbc0542014-10-24 20:38:07 -070091 log.warn("Failed to initialize native (epoll) transport. Reason: {}. Proceeding with nio.", t.getMessage());
Madan Jampani824a7c12014-10-21 09:46:15 -070092 }
93 clientGroup = new NioEventLoopGroup();
94 serverGroup = new NioEventLoopGroup();
95 serverChannelClass = NioServerSocketChannel.class;
96 clientChannelClass = NioSocketChannel.class;
Madan Jampani5e83f332014-10-20 15:35:09 -070097 }
98
Madan Jampani87100932014-10-21 16:46:12 -070099 public NettyMessagingService(String ip, int port) {
100 localEp = new Endpoint(ip, port);
101 }
102
Madan Jampaniab6d3112014-10-02 16:30:14 -0700103 public NettyMessagingService() {
104 // TODO: Default port should be configurable.
105 this(8080);
106 }
107
108 // FIXME: Constructor should not throw exceptions.
109 public NettyMessagingService(int port) {
Madan Jampaniab6d3112014-10-02 16:30:14 -0700110 try {
111 localEp = new Endpoint(java.net.InetAddress.getLocalHost().getHostName(), port);
112 } catch (UnknownHostException e) {
113 // bailing out.
114 throw new RuntimeException(e);
115 }
116 }
117
118 public void activate() throws Exception {
Madan Jampani86ed0552014-10-03 16:45:42 -0700119 channels.setTestOnBorrow(true);
120 channels.setTestOnReturn(true);
Madan Jampani5e83f332014-10-20 15:35:09 -0700121 initEventLoopGroup();
Madan Jampaniab6d3112014-10-02 16:30:14 -0700122 startAcceptingConnections();
123 }
124
125 public void deactivate() throws Exception {
126 channels.close();
Madan Jampani824a7c12014-10-21 09:46:15 -0700127 serverGroup.shutdownGracefully();
128 clientGroup.shutdownGracefully();
Madan Jampaniab6d3112014-10-02 16:30:14 -0700129 }
130
Madan Jampani87100932014-10-21 16:46:12 -0700131 /**
132 * Returns the local endpoint for this instance.
133 * @return local end point.
134 */
135 public Endpoint localEp() {
136 return localEp;
137 }
138
Madan Jampaniab6d3112014-10-02 16:30:14 -0700139 @Override
Madan Jampani53e44e62014-10-07 12:39:51 -0700140 public void sendAsync(Endpoint ep, String type, byte[] payload) throws IOException {
Madan Jampaniab6d3112014-10-02 16:30:14 -0700141 InternalMessage message = new InternalMessage.Builder(this)
Madan Jampani24f9efb2014-10-24 18:56:23 -0700142 .withId(messageIdGenerator.incrementAndGet())
Madan Jampaniab6d3112014-10-02 16:30:14 -0700143 .withSender(localEp)
144 .withType(type)
145 .withPayload(payload)
146 .build();
147 sendAsync(ep, message);
148 }
149
150 protected void sendAsync(Endpoint ep, InternalMessage message) throws IOException {
151 Channel channel = null;
152 try {
Madan Jampani86ed0552014-10-03 16:45:42 -0700153 try {
154 channel = channels.borrowObject(ep);
155 channel.eventLoop().execute(new WriteTask(channel, message));
156 } finally {
157 channels.returnObject(ep, channel);
158 }
Madan Jampaniab6d3112014-10-02 16:30:14 -0700159 } catch (Exception e) {
Madan Jampani87100932014-10-21 16:46:12 -0700160 throw new IOException("Failed to send message to " + ep.toString(), e);
Madan Jampaniab6d3112014-10-02 16:30:14 -0700161 }
162 }
163
164 @Override
Madan Jampani24f9efb2014-10-24 18:56:23 -0700165 public ListenableFuture<byte[]> sendAndReceive(Endpoint ep, String type, byte[] payload)
Madan Jampaniab6d3112014-10-02 16:30:14 -0700166 throws IOException {
Madan Jampani24f9efb2014-10-24 18:56:23 -0700167 SettableFuture<byte[]> futureResponse = SettableFuture.create();
168 Long messageId = messageIdGenerator.incrementAndGet();
Madan Jampaniab6d3112014-10-02 16:30:14 -0700169 responseFutures.put(messageId, futureResponse);
170 InternalMessage message = new InternalMessage.Builder(this)
171 .withId(messageId)
172 .withSender(localEp)
173 .withType(type)
174 .withPayload(payload)
175 .build();
Madan Jampani15cd0b82014-10-28 08:40:23 -0700176 try {
177 sendAsync(ep, message);
178 } catch (IOException e) {
179 responseFutures.invalidate(messageId);
180 throw e;
181 }
Madan Jampaniab6d3112014-10-02 16:30:14 -0700182 return futureResponse;
183 }
184
185 @Override
186 public void registerHandler(String type, MessageHandler handler) {
187 // TODO: Is this the right semantics for handler registration?
188 handlers.putIfAbsent(type, handler);
189 }
190
Yuta HIGUCHIe5ca93b2014-10-23 09:49:00 -0700191 @Override
Madan Jampaniab6d3112014-10-02 16:30:14 -0700192 public void unregisterHandler(String type) {
193 handlers.remove(type);
194 }
195
196 private MessageHandler getMessageHandler(String type) {
197 return handlers.get(type);
198 }
199
200 private void startAcceptingConnections() throws InterruptedException {
201 ServerBootstrap b = new ServerBootstrap();
Madan Jampani86ed0552014-10-03 16:45:42 -0700202 b.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 32 * 1024);
Madan Jampaniddf76222014-10-04 23:48:44 -0700203 b.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024);
204 // TODO: Need JVM options to configure PooledByteBufAllocator.
Madan Jampaniab6d3112014-10-02 16:30:14 -0700205 b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
Madan Jampani824a7c12014-10-21 09:46:15 -0700206 b.group(serverGroup, clientGroup)
207 .channel(serverChannelClass)
Madan Jampaniab6d3112014-10-02 16:30:14 -0700208 .childHandler(new OnosCommunicationChannelInitializer())
209 .option(ChannelOption.SO_BACKLOG, 128)
210 .childOption(ChannelOption.SO_KEEPALIVE, true);
211
212 // Bind and start to accept incoming connections.
Madan Jampani87100932014-10-21 16:46:12 -0700213 b.bind(localEp.port()).sync();
Madan Jampaniab6d3112014-10-02 16:30:14 -0700214 }
215
216 private class OnosCommunicationChannelFactory
217 implements KeyedPoolableObjectFactory<Endpoint, Channel> {
218
219 @Override
220 public void activateObject(Endpoint endpoint, Channel channel)
221 throws Exception {
222 }
223
224 @Override
225 public void destroyObject(Endpoint ep, Channel channel) throws Exception {
226 channel.close();
227 }
228
229 @Override
230 public Channel makeObject(Endpoint ep) throws Exception {
Madan Jampaniddf76222014-10-04 23:48:44 -0700231 Bootstrap bootstrap = new Bootstrap();
232 bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
233 bootstrap.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 32 * 1024);
234 bootstrap.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024);
Madan Jampani824a7c12014-10-21 09:46:15 -0700235 bootstrap.group(clientGroup);
Madan Jampaniab6d3112014-10-02 16:30:14 -0700236 // TODO: Make this faster:
237 // http://normanmaurer.me/presentations/2014-facebook-eng-netty/slides.html#37.0
Madan Jampani824a7c12014-10-21 09:46:15 -0700238 bootstrap.channel(clientChannelClass);
Madan Jampaniddf76222014-10-04 23:48:44 -0700239 bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
240 bootstrap.handler(new OnosCommunicationChannelInitializer());
Madan Jampaniab6d3112014-10-02 16:30:14 -0700241 // Start the client.
Madan Jampaniddf76222014-10-04 23:48:44 -0700242 ChannelFuture f = bootstrap.connect(ep.host(), ep.port()).sync();
Madan Jampaniab6d3112014-10-02 16:30:14 -0700243 return f.channel();
244 }
245
246 @Override
247 public void passivateObject(Endpoint ep, Channel channel)
248 throws Exception {
249 }
250
251 @Override
252 public boolean validateObject(Endpoint ep, Channel channel) {
253 return channel.isOpen();
254 }
255 }
256
257 private class OnosCommunicationChannelInitializer extends ChannelInitializer<SocketChannel> {
258
Madan Jampaniddf76222014-10-04 23:48:44 -0700259 private final ChannelHandler dispatcher = new InboundMessageDispatcher();
Madan Jampani53e44e62014-10-07 12:39:51 -0700260 private final ChannelHandler encoder = new MessageEncoder();
Madan Jampaniddf76222014-10-04 23:48:44 -0700261
Madan Jampaniab6d3112014-10-02 16:30:14 -0700262 @Override
263 protected void initChannel(SocketChannel channel) throws Exception {
264 channel.pipeline()
Madan Jampaniddf76222014-10-04 23:48:44 -0700265 .addLast("encoder", encoder)
Madan Jampani53e44e62014-10-07 12:39:51 -0700266 .addLast("decoder", new MessageDecoder(NettyMessagingService.this))
Madan Jampaniddf76222014-10-04 23:48:44 -0700267 .addLast("handler", dispatcher);
Madan Jampaniab6d3112014-10-02 16:30:14 -0700268 }
269 }
270
Yuta HIGUCHIe5ca93b2014-10-23 09:49:00 -0700271 private static class WriteTask implements Runnable {
Madan Jampaniab6d3112014-10-02 16:30:14 -0700272
Madan Jampani86ed0552014-10-03 16:45:42 -0700273 private final InternalMessage message;
Madan Jampaniab6d3112014-10-02 16:30:14 -0700274 private final Channel channel;
275
Madan Jampani86ed0552014-10-03 16:45:42 -0700276 public WriteTask(Channel channel, InternalMessage message) {
Madan Jampaniab6d3112014-10-02 16:30:14 -0700277 this.channel = channel;
Madan Jampani86ed0552014-10-03 16:45:42 -0700278 this.message = message;
Madan Jampaniab6d3112014-10-02 16:30:14 -0700279 }
280
281 @Override
282 public void run() {
Madan Jampaniddf76222014-10-04 23:48:44 -0700283 channel.writeAndFlush(message, channel.voidPromise());
Madan Jampaniab6d3112014-10-02 16:30:14 -0700284 }
285 }
286
Madan Jampaniddf76222014-10-04 23:48:44 -0700287 @ChannelHandler.Sharable
Madan Jampaniab6d3112014-10-02 16:30:14 -0700288 private class InboundMessageDispatcher extends SimpleChannelInboundHandler<InternalMessage> {
289
290 @Override
291 protected void channelRead0(ChannelHandlerContext ctx, InternalMessage message) throws Exception {
292 String type = message.type();
293 if (type.equals(InternalMessage.REPLY_MESSAGE_TYPE)) {
294 try {
Madan Jampani24f9efb2014-10-24 18:56:23 -0700295 SettableFuture<byte[]> futureResponse =
Madan Jampaniab6d3112014-10-02 16:30:14 -0700296 NettyMessagingService.this.responseFutures.getIfPresent(message.id());
297 if (futureResponse != null) {
Madan Jampani24f9efb2014-10-24 18:56:23 -0700298 futureResponse.set(message.payload());
Madan Jampanif1d425a2014-10-07 09:52:36 -0700299 } else {
Madan Jampani15cd0b82014-10-28 08:40:23 -0700300 log.warn("Received a reply for message id:[{}]. "
301 + "But was unable to locate the request handle", message.id());
Madan Jampaniab6d3112014-10-02 16:30:14 -0700302 }
Madan Jampaniab6d3112014-10-02 16:30:14 -0700303 } finally {
304 NettyMessagingService.this.responseFutures.invalidate(message.id());
305 }
306 return;
307 }
308 MessageHandler handler = NettyMessagingService.this.getMessageHandler(type);
309 handler.handle(message);
310 }
Madan Jampani86ed0552014-10-03 16:45:42 -0700311
Madan Jampani86ed0552014-10-03 16:45:42 -0700312 @Override
313 public void exceptionCaught(ChannelHandlerContext context, Throwable cause) {
Madan Jampani29e5dfd2014-10-07 17:26:25 -0700314 log.error("Exception inside channel handling pipeline.", cause);
Madan Jampani86ed0552014-10-03 16:45:42 -0700315 context.close();
316 }
Madan Jampaniab6d3112014-10-02 16:30:14 -0700317 }
318}