blob: e10ba29fcc9187c8c4d8d69faa96c72727575224 [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)
70 .weakValues()
71 // TODO: Once the entry expires, notify blocking threads (if any).
72 .expireAfterWrite(10, TimeUnit.MINUTES)
73 .build();
74 private final GenericKeyedObjectPool<Endpoint, Channel> channels
75 = new GenericKeyedObjectPool<Endpoint, Channel>(new OnosCommunicationChannelFactory());
Madan Jampaniab6d3112014-10-02 16:30:14 -070076
Madan Jampani824a7c12014-10-21 09:46:15 -070077 private EventLoopGroup serverGroup;
78 private EventLoopGroup clientGroup;
79 private Class<? extends ServerChannel> serverChannelClass;
80 private Class<? extends Channel> clientChannelClass;
81
Madan Jampani5e83f332014-10-20 15:35:09 -070082 private void initEventLoopGroup() {
Madan Jampani824a7c12014-10-21 09:46:15 -070083 // try Epoll first and if that does work, use nio.
84 // TODO: make this configurable.
85 try {
Madan Jampani99e9fe22014-10-21 13:47:12 -070086 clientGroup = new EpollEventLoopGroup();
87 serverGroup = new EpollEventLoopGroup();
88 serverChannelClass = EpollServerSocketChannel.class;
89 clientChannelClass = EpollSocketChannel.class;
90 return;
Madan Jampani824a7c12014-10-21 09:46:15 -070091 } catch (Throwable t) {
Madan Jampanicfbc0542014-10-24 20:38:07 -070092 log.warn("Failed to initialize native (epoll) transport. Reason: {}. Proceeding with nio.", t.getMessage());
Madan Jampani824a7c12014-10-21 09:46:15 -070093 }
94 clientGroup = new NioEventLoopGroup();
95 serverGroup = new NioEventLoopGroup();
96 serverChannelClass = NioServerSocketChannel.class;
97 clientChannelClass = NioSocketChannel.class;
Madan Jampani5e83f332014-10-20 15:35:09 -070098 }
99
Madan Jampani87100932014-10-21 16:46:12 -0700100 public NettyMessagingService(String ip, int port) {
101 localEp = new Endpoint(ip, port);
102 }
103
Madan Jampaniab6d3112014-10-02 16:30:14 -0700104 public NettyMessagingService() {
105 // TODO: Default port should be configurable.
106 this(8080);
107 }
108
109 // FIXME: Constructor should not throw exceptions.
110 public NettyMessagingService(int port) {
Madan Jampaniab6d3112014-10-02 16:30:14 -0700111 try {
112 localEp = new Endpoint(java.net.InetAddress.getLocalHost().getHostName(), port);
113 } catch (UnknownHostException e) {
114 // bailing out.
115 throw new RuntimeException(e);
116 }
117 }
118
119 public void activate() throws Exception {
Madan Jampani86ed0552014-10-03 16:45:42 -0700120 channels.setTestOnBorrow(true);
121 channels.setTestOnReturn(true);
Madan Jampani5e83f332014-10-20 15:35:09 -0700122 initEventLoopGroup();
Madan Jampaniab6d3112014-10-02 16:30:14 -0700123 startAcceptingConnections();
124 }
125
126 public void deactivate() throws Exception {
127 channels.close();
Madan Jampani824a7c12014-10-21 09:46:15 -0700128 serverGroup.shutdownGracefully();
129 clientGroup.shutdownGracefully();
Madan Jampaniab6d3112014-10-02 16:30:14 -0700130 }
131
Madan Jampani87100932014-10-21 16:46:12 -0700132 /**
133 * Returns the local endpoint for this instance.
134 * @return local end point.
135 */
136 public Endpoint localEp() {
137 return localEp;
138 }
139
Madan Jampaniab6d3112014-10-02 16:30:14 -0700140 @Override
Madan Jampani53e44e62014-10-07 12:39:51 -0700141 public void sendAsync(Endpoint ep, String type, byte[] payload) throws IOException {
Madan Jampaniab6d3112014-10-02 16:30:14 -0700142 InternalMessage message = new InternalMessage.Builder(this)
Madan Jampani24f9efb2014-10-24 18:56:23 -0700143 .withId(messageIdGenerator.incrementAndGet())
Madan Jampaniab6d3112014-10-02 16:30:14 -0700144 .withSender(localEp)
145 .withType(type)
146 .withPayload(payload)
147 .build();
148 sendAsync(ep, message);
149 }
150
151 protected void sendAsync(Endpoint ep, InternalMessage message) throws IOException {
152 Channel channel = null;
153 try {
Madan Jampani86ed0552014-10-03 16:45:42 -0700154 try {
155 channel = channels.borrowObject(ep);
156 channel.eventLoop().execute(new WriteTask(channel, message));
157 } finally {
158 channels.returnObject(ep, channel);
159 }
Madan Jampaniab6d3112014-10-02 16:30:14 -0700160 } catch (Exception e) {
Madan Jampani87100932014-10-21 16:46:12 -0700161 throw new IOException("Failed to send message to " + ep.toString(), e);
Madan Jampaniab6d3112014-10-02 16:30:14 -0700162 }
163 }
164
165 @Override
Madan Jampani24f9efb2014-10-24 18:56:23 -0700166 public ListenableFuture<byte[]> sendAndReceive(Endpoint ep, String type, byte[] payload)
Madan Jampaniab6d3112014-10-02 16:30:14 -0700167 throws IOException {
Madan Jampani24f9efb2014-10-24 18:56:23 -0700168 SettableFuture<byte[]> futureResponse = SettableFuture.create();
169 Long messageId = messageIdGenerator.incrementAndGet();
Madan Jampaniab6d3112014-10-02 16:30:14 -0700170 responseFutures.put(messageId, futureResponse);
171 InternalMessage message = new InternalMessage.Builder(this)
172 .withId(messageId)
173 .withSender(localEp)
174 .withType(type)
175 .withPayload(payload)
176 .build();
177 sendAsync(ep, message);
178 return futureResponse;
179 }
180
181 @Override
182 public void registerHandler(String type, MessageHandler handler) {
183 // TODO: Is this the right semantics for handler registration?
184 handlers.putIfAbsent(type, handler);
185 }
186
Yuta HIGUCHIe5ca93b2014-10-23 09:49:00 -0700187 @Override
Madan Jampaniab6d3112014-10-02 16:30:14 -0700188 public void unregisterHandler(String type) {
189 handlers.remove(type);
190 }
191
192 private MessageHandler getMessageHandler(String type) {
193 return handlers.get(type);
194 }
195
196 private void startAcceptingConnections() throws InterruptedException {
197 ServerBootstrap b = new ServerBootstrap();
Madan Jampani86ed0552014-10-03 16:45:42 -0700198 b.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 32 * 1024);
Madan Jampaniddf76222014-10-04 23:48:44 -0700199 b.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024);
200 // TODO: Need JVM options to configure PooledByteBufAllocator.
Madan Jampaniab6d3112014-10-02 16:30:14 -0700201 b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
Madan Jampani824a7c12014-10-21 09:46:15 -0700202 b.group(serverGroup, clientGroup)
203 .channel(serverChannelClass)
Madan Jampaniab6d3112014-10-02 16:30:14 -0700204 .childHandler(new OnosCommunicationChannelInitializer())
205 .option(ChannelOption.SO_BACKLOG, 128)
206 .childOption(ChannelOption.SO_KEEPALIVE, true);
207
208 // Bind and start to accept incoming connections.
Madan Jampani87100932014-10-21 16:46:12 -0700209 b.bind(localEp.port()).sync();
Madan Jampaniab6d3112014-10-02 16:30:14 -0700210 }
211
212 private class OnosCommunicationChannelFactory
213 implements KeyedPoolableObjectFactory<Endpoint, Channel> {
214
215 @Override
216 public void activateObject(Endpoint endpoint, Channel channel)
217 throws Exception {
218 }
219
220 @Override
221 public void destroyObject(Endpoint ep, Channel channel) throws Exception {
222 channel.close();
223 }
224
225 @Override
226 public Channel makeObject(Endpoint ep) throws Exception {
Madan Jampaniddf76222014-10-04 23:48:44 -0700227 Bootstrap bootstrap = new Bootstrap();
228 bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
229 bootstrap.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 32 * 1024);
230 bootstrap.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024);
Madan Jampani824a7c12014-10-21 09:46:15 -0700231 bootstrap.group(clientGroup);
Madan Jampaniab6d3112014-10-02 16:30:14 -0700232 // TODO: Make this faster:
233 // http://normanmaurer.me/presentations/2014-facebook-eng-netty/slides.html#37.0
Madan Jampani824a7c12014-10-21 09:46:15 -0700234 bootstrap.channel(clientChannelClass);
Madan Jampaniddf76222014-10-04 23:48:44 -0700235 bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
236 bootstrap.handler(new OnosCommunicationChannelInitializer());
Madan Jampaniab6d3112014-10-02 16:30:14 -0700237 // Start the client.
Madan Jampaniddf76222014-10-04 23:48:44 -0700238 ChannelFuture f = bootstrap.connect(ep.host(), ep.port()).sync();
Madan Jampaniab6d3112014-10-02 16:30:14 -0700239 return f.channel();
240 }
241
242 @Override
243 public void passivateObject(Endpoint ep, Channel channel)
244 throws Exception {
245 }
246
247 @Override
248 public boolean validateObject(Endpoint ep, Channel channel) {
249 return channel.isOpen();
250 }
251 }
252
253 private class OnosCommunicationChannelInitializer extends ChannelInitializer<SocketChannel> {
254
Madan Jampaniddf76222014-10-04 23:48:44 -0700255 private final ChannelHandler dispatcher = new InboundMessageDispatcher();
Madan Jampani53e44e62014-10-07 12:39:51 -0700256 private final ChannelHandler encoder = new MessageEncoder();
Madan Jampaniddf76222014-10-04 23:48:44 -0700257
Madan Jampaniab6d3112014-10-02 16:30:14 -0700258 @Override
259 protected void initChannel(SocketChannel channel) throws Exception {
260 channel.pipeline()
Madan Jampaniddf76222014-10-04 23:48:44 -0700261 .addLast("encoder", encoder)
Madan Jampani53e44e62014-10-07 12:39:51 -0700262 .addLast("decoder", new MessageDecoder(NettyMessagingService.this))
Madan Jampaniddf76222014-10-04 23:48:44 -0700263 .addLast("handler", dispatcher);
Madan Jampaniab6d3112014-10-02 16:30:14 -0700264 }
265 }
266
Yuta HIGUCHIe5ca93b2014-10-23 09:49:00 -0700267 private static class WriteTask implements Runnable {
Madan Jampaniab6d3112014-10-02 16:30:14 -0700268
Madan Jampani86ed0552014-10-03 16:45:42 -0700269 private final InternalMessage message;
Madan Jampaniab6d3112014-10-02 16:30:14 -0700270 private final Channel channel;
271
Madan Jampani86ed0552014-10-03 16:45:42 -0700272 public WriteTask(Channel channel, InternalMessage message) {
Madan Jampaniab6d3112014-10-02 16:30:14 -0700273 this.channel = channel;
Madan Jampani86ed0552014-10-03 16:45:42 -0700274 this.message = message;
Madan Jampaniab6d3112014-10-02 16:30:14 -0700275 }
276
277 @Override
278 public void run() {
Madan Jampaniddf76222014-10-04 23:48:44 -0700279 channel.writeAndFlush(message, channel.voidPromise());
Madan Jampaniab6d3112014-10-02 16:30:14 -0700280 }
281 }
282
Madan Jampaniddf76222014-10-04 23:48:44 -0700283 @ChannelHandler.Sharable
Madan Jampaniab6d3112014-10-02 16:30:14 -0700284 private class InboundMessageDispatcher extends SimpleChannelInboundHandler<InternalMessage> {
285
286 @Override
287 protected void channelRead0(ChannelHandlerContext ctx, InternalMessage message) throws Exception {
288 String type = message.type();
289 if (type.equals(InternalMessage.REPLY_MESSAGE_TYPE)) {
290 try {
Madan Jampani24f9efb2014-10-24 18:56:23 -0700291 SettableFuture<byte[]> futureResponse =
Madan Jampaniab6d3112014-10-02 16:30:14 -0700292 NettyMessagingService.this.responseFutures.getIfPresent(message.id());
293 if (futureResponse != null) {
Madan Jampani24f9efb2014-10-24 18:56:23 -0700294 futureResponse.set(message.payload());
Madan Jampanif1d425a2014-10-07 09:52:36 -0700295 } else {
296 log.warn("Received a reply. But was unable to locate the request handle");
Madan Jampaniab6d3112014-10-02 16:30:14 -0700297 }
Madan Jampaniab6d3112014-10-02 16:30:14 -0700298 } finally {
299 NettyMessagingService.this.responseFutures.invalidate(message.id());
300 }
301 return;
302 }
303 MessageHandler handler = NettyMessagingService.this.getMessageHandler(type);
304 handler.handle(message);
305 }
Madan Jampani86ed0552014-10-03 16:45:42 -0700306
Madan Jampani86ed0552014-10-03 16:45:42 -0700307 @Override
308 public void exceptionCaught(ChannelHandlerContext context, Throwable cause) {
Madan Jampani29e5dfd2014-10-07 17:26:25 -0700309 log.error("Exception inside channel handling pipeline.", cause);
Madan Jampani86ed0552014-10-03 16:45:42 -0700310 context.close();
311 }
Madan Jampaniab6d3112014-10-02 16:30:14 -0700312 }
313}