2 * Copyright (c) 2014 Contextream, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.lispflowmapping.southbound;
10 import static io.netty.buffer.Unpooled.wrappedBuffer;
11 import static java.util.Objects.requireNonNull;
13 import com.google.common.util.concurrent.Futures;
14 import com.google.common.util.concurrent.ListenableFuture;
15 import io.netty.bootstrap.Bootstrap;
16 import io.netty.buffer.ByteBuf;
17 import io.netty.buffer.ByteBufUtil;
18 import io.netty.buffer.PooledByteBufAllocator;
19 import io.netty.channel.Channel;
20 import io.netty.channel.ChannelOption;
21 import io.netty.channel.EventLoopGroup;
22 import io.netty.channel.epoll.Epoll;
23 import io.netty.channel.epoll.EpollChannelOption;
24 import io.netty.channel.epoll.EpollDatagramChannel;
25 import io.netty.channel.epoll.EpollEventLoopGroup;
26 import io.netty.channel.nio.NioEventLoopGroup;
27 import io.netty.channel.socket.DatagramChannel;
28 import io.netty.channel.socket.DatagramPacket;
29 import io.netty.channel.socket.nio.NioDatagramChannel;
30 import io.netty.util.concurrent.DefaultThreadFactory;
31 import java.net.InetAddress;
32 import java.net.InetSocketAddress;
33 import java.net.UnknownHostException;
34 import java.nio.ByteBuffer;
35 import java.util.List;
36 import java.util.concurrent.ThreadFactory;
37 import javax.annotation.PostConstruct;
38 import javax.annotation.PreDestroy;
39 import javax.inject.Inject;
40 import javax.inject.Singleton;
41 import org.opendaylight.lispflowmapping.dsbackend.DataStoreBackEnd;
42 import org.opendaylight.lispflowmapping.inmemorydb.HashMapDb;
43 import org.opendaylight.lispflowmapping.lisp.type.LispMessage;
44 import org.opendaylight.lispflowmapping.lisp.util.LispAddressStringifier;
45 import org.opendaylight.lispflowmapping.mapcache.AuthKeyDb;
46 import org.opendaylight.lispflowmapping.southbound.lisp.AuthenticationKeyDataListener;
47 import org.opendaylight.lispflowmapping.southbound.lisp.LispSouthboundHandler;
48 import org.opendaylight.lispflowmapping.southbound.lisp.LispXtrSouthboundHandler;
49 import org.opendaylight.lispflowmapping.southbound.lisp.cache.MapRegisterCache;
50 import org.opendaylight.lispflowmapping.type.sbplugin.IConfigLispSouthboundPlugin;
51 import org.opendaylight.mdsal.binding.api.DataBroker;
52 import org.opendaylight.mdsal.binding.api.NotificationPublishService;
53 import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonService;
54 import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceProvider;
55 import org.opendaylight.mdsal.singleton.common.api.ServiceGroupIdentifier;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.inet.binary.types.rev160303.IpAddressBinary;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MessageType;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.eid.container.Eid;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.authkey.container.MappingAuthkey;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.transport.address.TransportAddress;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.mappingservice.rev150906.db.instance.AuthenticationKey;
62 import org.opendaylight.yangtools.yang.binding.Notification;
63 import org.osgi.service.component.annotations.Activate;
64 import org.osgi.service.component.annotations.Component;
65 import org.osgi.service.component.annotations.Deactivate;
66 import org.osgi.service.component.annotations.Reference;
67 import org.osgi.service.metatype.annotations.AttributeDefinition;
68 import org.osgi.service.metatype.annotations.Designate;
69 import org.osgi.service.metatype.annotations.ObjectClassDefinition;
70 import org.slf4j.Logger;
71 import org.slf4j.LoggerFactory;
74 @Component(immediate = true, property = "type=default", configurationPid = "org.opendaylight.lispflowmapping",
75 service = { IConfigLispSouthboundPlugin.class, LispSouthboundPlugin.class })
76 @Designate(ocd = LispSouthboundPlugin.Configuration.class)
77 public class LispSouthboundPlugin implements IConfigLispSouthboundPlugin, AutoCloseable, ClusterSingletonService {
78 @ObjectClassDefinition
79 public @interface Configuration {
80 @AttributeDefinition()
81 String bindingAddress() default DEFAULT_BINDING_ADDRESS;
83 @AttributeDefinition()
84 boolean mapRegisterCacheEnabled() default true;
86 @AttributeDefinition()
87 long mapRegisterCacheTimeout() default DEFAULT_MAP_REGISTER_CACHE_TIMEOUT;
90 protected static final Logger LOG = LoggerFactory.getLogger(LispSouthboundPlugin.class);
91 public static final String LISPFLOWMAPPING_ENTITY_NAME = "lispflowmapping";
92 public static final ServiceGroupIdentifier SERVICE_GROUP_IDENTIFIER =
93 ServiceGroupIdentifier.create(LISPFLOWMAPPING_ENTITY_NAME);
95 private static final String DEFAULT_BINDING_ADDRESS = "0.0.0.0";
96 private static final long DEFAULT_MAP_REGISTER_CACHE_TIMEOUT = 90000;
98 private volatile boolean isMaster = false;
99 private volatile String bindingAddress;
100 private AuthKeyDb akdb;
101 private final MapRegisterCache mapRegisterCache = new MapRegisterCache();
102 private final boolean mapRegisterCacheEnabled;
103 private final long mapRegisterCacheTimeout;
105 private static Object startLock = new Object();
107 private final DataBroker dataBroker;
108 private final NotificationPublishService notificationPublishService;
109 private final ClusterSingletonServiceProvider clusterSingletonService;
111 private LispSouthboundHandler lispSouthboundHandler;
112 private int numChannels = 1;
113 private final Channel[] channel;
114 private Channel xtrChannel;
115 private volatile int xtrPort = LispMessage.XTR_PORT_NUM;
116 private volatile boolean listenOnXtrPort = false;
117 private final ConcurrentLispSouthboundStats statistics = new ConcurrentLispSouthboundStats();
118 private final Bootstrap bootstrap = new Bootstrap();
119 private final Bootstrap xtrBootstrap = new Bootstrap();
120 private final ThreadFactory threadFactory = new DefaultThreadFactory("lisp-sb");
121 private EventLoopGroup eventLoopGroup;
122 private AuthenticationKeyDataListener authenticationKeyDataListener;
123 private DataStoreBackEnd dsbe;
126 public LispSouthboundPlugin(final DataBroker dataBroker,
127 final NotificationPublishService notificationPublishService,
128 final ClusterSingletonServiceProvider clusterSingletonService) {
129 this(dataBroker, notificationPublishService, clusterSingletonService, DEFAULT_BINDING_ADDRESS, true,
130 DEFAULT_MAP_REGISTER_CACHE_TIMEOUT);
134 public LispSouthboundPlugin(@Reference final DataBroker dataBroker,
135 @Reference final NotificationPublishService notificationPublishService,
136 @Reference final ClusterSingletonServiceProvider clusterSingletonService,
137 final Configuration configuration) {
138 this(dataBroker, notificationPublishService, clusterSingletonService, configuration.bindingAddress(),
139 configuration.mapRegisterCacheEnabled(), configuration.mapRegisterCacheTimeout());
143 public LispSouthboundPlugin(final DataBroker dataBroker,
144 final NotificationPublishService notificationPublishService,
145 final ClusterSingletonServiceProvider clusterSingletonService,
146 final String bindingAddress, final boolean mapRegisterCacheEnabled, final long mapRegisterCacheTimeout) {
147 LOG.info("LISP (RFC6830) Southbound Plugin is initializing...");
148 this.dataBroker = dataBroker;
149 this.notificationPublishService = notificationPublishService;
150 this.clusterSingletonService = clusterSingletonService;
151 this.bindingAddress = bindingAddress;
152 this.mapRegisterCacheEnabled = mapRegisterCacheEnabled;
153 this.mapRegisterCacheTimeout = mapRegisterCacheTimeout;
155 if (Epoll.isAvailable()) {
156 // When lispflowmapping is under heavy load, there are usually two threads nearing 100% CPU core
157 // utilization. In order to have some headroom, we reserve 3 cores for "other" tasks, and allow the
158 // rest to be used for southbound packet processing, which is the most CPU intensive work done in lfm
159 numChannels = Math.max(1, Runtime.getRuntime().availableProcessors() - 3);
161 channel = new Channel[numChannels];
166 synchronized (startLock) {
167 akdb = new AuthKeyDb(new HashMapDb());
168 authenticationKeyDataListener = new AuthenticationKeyDataListener(dataBroker, akdb);
169 dsbe = new DataStoreBackEnd(dataBroker);
170 restoreDaoFromDatastore();
172 final Class<? extends DatagramChannel> channelType;
173 if (Epoll.isAvailable()) {
174 eventLoopGroup = new EpollEventLoopGroup(numChannels, threadFactory);
175 channelType = EpollDatagramChannel.class;
176 bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
177 bootstrap.option(EpollChannelOption.SO_REUSEPORT, true);
178 LOG.debug("Using Netty Epoll for UDP sockets");
180 eventLoopGroup = new NioEventLoopGroup(0, threadFactory);
181 channelType = NioDatagramChannel.class;
182 LOG.debug("Using Netty I/O (non-Epoll) for UDP sockets");
185 bootstrap.group(eventLoopGroup);
186 bootstrap.channel(channelType);
187 lispSouthboundHandler = new LispSouthboundHandler(this);
188 bootstrap.handler(lispSouthboundHandler);
190 xtrBootstrap.group(eventLoopGroup);
191 xtrBootstrap.channel(channelType);
192 xtrBootstrap.handler(new LispXtrSouthboundHandler(this));
197 clusterSingletonService.registerClusterSingletonService(this);
200 LOG.info("LISP (RFC6830) Southbound Plugin is up!");
203 @SuppressWarnings("checkstyle:IllegalCatch")
204 private void start() {
206 for (int i = 0; i < numChannels; ++i) {
207 channel[i] = bootstrap.bind(bindingAddress, LispMessage.PORT_NUM).sync().channel();
209 LOG.debug("Binding LISP UDP listening socket to {}:{}", bindingAddress, LispMessage.PORT_NUM);
210 } catch (Exception e) {
211 LOG.error("Failed to open main socket ", e);
215 @SuppressWarnings("checkstyle:IllegalCatch")
216 private void startXtr() {
217 if (listenOnXtrPort) {
219 xtrChannel = xtrBootstrap.bind(bindingAddress, xtrPort).sync().channel();
220 LOG.debug("Binding LISP xTR UDP listening socket to {}:{}", bindingAddress, xtrPort);
221 } catch (Exception e) {
222 LOG.error("Failed to open xTR socket ", e);
227 @SuppressWarnings("checkstyle:IllegalCatch")
228 private void stop() {
230 for (int i = 0; i < numChannels; ++i) {
231 channel[i].close().sync();
234 } catch (Exception e) {
235 LOG.error("Failed to close main socket ", e);
239 @SuppressWarnings("checkstyle:IllegalCatch")
240 private void stopXtr() {
241 if (listenOnXtrPort) {
243 xtrChannel.close().sync();
245 } catch (Exception e) {
246 LOG.error("Failed to close xTR socket ", e);
251 private void restart() {
252 LOG.info("Reloading");
257 private void restartXtr() {
258 LOG.info("Reloading xTR");
263 private void unloadActions() {
264 lispSouthboundHandler = null;
269 LOG.info("LISP (RFC6830) Southbound Plugin is down!");
273 * Restore all keys from MDSAL datastore.
275 public void restoreDaoFromDatastore() {
276 final List<AuthenticationKey> authKeys = dsbe.getAllAuthenticationKeys();
277 LOG.info("Restoring {} keys from datastore into southbound DAO", authKeys.size());
279 for (AuthenticationKey authKey : authKeys) {
280 final Eid key = authKey.getEid();
281 final MappingAuthkey mappingAuthkey = authKey.getMappingAuthkey();
282 LOG.debug("Adding authentication key '{}' with key-ID {} for {}", mappingAuthkey.getKeyString(),
283 mappingAuthkey.getKeyType(),
284 LispAddressStringifier.getString(key));
285 akdb.addAuthenticationKey(key, mappingAuthkey);
289 public void handleSerializedLispBuffer(final TransportAddress address, final ByteBuffer outBuffer,
290 final MessageType packetType) {
291 InetAddress ip = getInetAddress(address);
292 handleSerializedLispBuffer(ip, outBuffer, packetType, address.getPort().getValue().toJava(), null);
295 public void handleSerializedLispBuffer(final InetAddress address, final ByteBuffer outBuffer,
296 final MessageType packetType, final int portNumber, Channel senderChannel) {
297 if (senderChannel == null) {
298 senderChannel = channel[0];
300 InetSocketAddress recipient = new InetSocketAddress(address, portNumber);
301 outBuffer.position(0);
302 ByteBuf data = wrappedBuffer(outBuffer);
303 DatagramPacket packet = new DatagramPacket(data, recipient);
304 LOG.debug("Sending {} on port {} to address: {}", packetType, portNumber, address);
305 if (LOG.isTraceEnabled()) {
306 LOG.trace("Buffer:\n{}", ByteBufUtil.prettyHexDump(data));
308 senderChannel.write(packet).addListener(future -> {
309 if (future.isSuccess()) {
310 LOG.trace("Success");
311 statistics.incrementTx(packetType.getIntValue());
313 LOG.warn("Failed to send packet");
314 statistics.incrementTxErrors();
317 senderChannel.flush();
320 private static InetAddress getInetAddress(final TransportAddress address) {
321 requireNonNull(address, "TransportAddress must not be null");
322 IpAddressBinary ip = address.getIpAddress();
324 if (ip.getIpv4AddressBinary() != null) {
325 return InetAddress.getByAddress(ip.getIpv4AddressBinary().getValue());
326 } else if (ip.getIpv6AddressBinary() != null) {
327 return InetAddress.getByAddress(ip.getIpv6AddressBinary().getValue());
329 } catch (UnknownHostException e) {
330 LOG.debug("Could not convert TransportAddress {} to InetAddress", address, e);
336 @SuppressWarnings("checkstyle:IllegalCatch")
337 public void setLispAddress(final String address) {
338 synchronized (startLock) {
339 if (bindingAddress.equals(address)) {
340 LOG.debug("Configured LISP binding address didn't change.");
342 LOG.debug("Setting LISP binding address to {}", address);
343 bindingAddress = address;
344 if (channel != null) {
348 } catch (Exception e) {
349 LOG.error("Failed to set LISP binding address: ", e);
357 public void shouldListenOnXtrPort(final boolean shouldListenOnXtrPort) {
358 listenOnXtrPort = shouldListenOnXtrPort;
359 if (listenOnXtrPort) {
362 LOG.info("Shutting down xTR");
368 public void setXtrPort(final int port) {
370 if (listenOnXtrPort) {
378 public void close() throws Exception {
379 eventLoopGroup.shutdownGracefully();
380 lispSouthboundHandler.close();
382 clusterSingletonService.close();
383 dsbe.closeTransactionChain();
387 public void instantiateServiceInstance() {
392 public ListenableFuture<Void> closeServiceInstance() {
394 return Futures.<Void>immediateFuture(null);
398 public ServiceGroupIdentifier getIdentifier() {
399 return SERVICE_GROUP_IDENTIFIER;
402 public synchronized void sendNotificationIfPossible(final Notification notification) throws InterruptedException {
403 if (isMaster && notificationPublishService != null) {
404 notificationPublishService.putNotification(notification);
405 LOG.trace("Publishing notification: {}", notification);
406 } else if (notificationPublishService == null) {
407 LOG.warn("Can't publish notification because no reference to publication service exists!");
411 public AuthKeyDb getAkdb() {
415 public ConcurrentLispSouthboundStats getStats() {
419 public DataBroker getDataBroker() {
423 public AuthenticationKeyDataListener getAuthenticationKeyDataListener() {
424 return authenticationKeyDataListener;
427 public MapRegisterCache getMapRegisterCache() {
428 return mapRegisterCache;
431 public boolean isMapRegisterCacheEnabled() {
432 return mapRegisterCacheEnabled;
435 public long getMapRegisterCacheTimeout() {
436 return mapRegisterCacheTimeout;