Merge "Fix JMock execution"
[lispflowmapping.git] / mappingservice / southbound / src / main / java / org / opendaylight / lispflowmapping / southbound / LispSouthboundPlugin.java
1 /*
2  * Copyright (c) 2014 Contextream, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.lispflowmapping.southbound;
9
10 import static io.netty.buffer.Unpooled.wrappedBuffer;
11 import static java.util.Objects.requireNonNull;
12
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;
72
73 @Singleton
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;
82
83         @AttributeDefinition()
84         boolean mapRegisterCacheEnabled() default true;
85
86         @AttributeDefinition()
87         long mapRegisterCacheTimeout() default DEFAULT_MAP_REGISTER_CACHE_TIMEOUT;
88     }
89
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);
94
95     private static final String DEFAULT_BINDING_ADDRESS = "0.0.0.0";
96     private static final long DEFAULT_MAP_REGISTER_CACHE_TIMEOUT = 90000;
97
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;
104
105     private static Object startLock = new Object();
106
107     private final DataBroker dataBroker;
108     private final NotificationPublishService notificationPublishService;
109     private final ClusterSingletonServiceProvider clusterSingletonService;
110
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;
124
125     @Inject
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);
131     }
132
133     @Activate
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());
140         init();
141     }
142
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;
154
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);
160         }
161         channel = new Channel[numChannels];
162     }
163
164     @PostConstruct
165     public void init() {
166         synchronized (startLock) {
167             akdb = new AuthKeyDb(new HashMapDb());
168             authenticationKeyDataListener = new AuthenticationKeyDataListener(dataBroker, akdb);
169             dsbe = new DataStoreBackEnd(dataBroker);
170             restoreDaoFromDatastore();
171
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");
179             } else {
180                 eventLoopGroup = new NioEventLoopGroup(0, threadFactory);
181                 channelType = NioDatagramChannel.class;
182                 LOG.debug("Using Netty I/O (non-Epoll) for UDP sockets");
183             }
184
185             bootstrap.group(eventLoopGroup);
186             bootstrap.channel(channelType);
187             lispSouthboundHandler = new LispSouthboundHandler(this);
188             bootstrap.handler(lispSouthboundHandler);
189
190             xtrBootstrap.group(eventLoopGroup);
191             xtrBootstrap.channel(channelType);
192             xtrBootstrap.handler(new LispXtrSouthboundHandler(this));
193
194             start();
195             startXtr();
196
197             clusterSingletonService.registerClusterSingletonService(this);
198         }
199
200         LOG.info("LISP (RFC6830) Southbound Plugin is up!");
201     }
202
203     @SuppressWarnings("checkstyle:IllegalCatch")
204     private void start() {
205         try {
206             for (int i = 0; i < numChannels; ++i) {
207                 channel[i] = bootstrap.bind(bindingAddress, LispMessage.PORT_NUM).sync().channel();
208             }
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);
212         }
213     }
214
215     @SuppressWarnings("checkstyle:IllegalCatch")
216     private void startXtr() {
217         if (listenOnXtrPort) {
218             try {
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);
223             }
224         }
225     }
226
227     @SuppressWarnings("checkstyle:IllegalCatch")
228     private void stop() {
229         try {
230             for (int i = 0; i < numChannels; ++i) {
231                 channel[i].close().sync();
232                 channel[i] = null;
233             }
234         } catch (Exception e) {
235             LOG.error("Failed to close main socket ", e);
236         }
237     }
238
239     @SuppressWarnings("checkstyle:IllegalCatch")
240     private void stopXtr() {
241         if (listenOnXtrPort) {
242             try {
243                 xtrChannel.close().sync();
244                 xtrChannel = null;
245             } catch (Exception e) {
246                 LOG.error("Failed to close xTR socket ", e);
247             }
248         }
249     }
250
251     private void restart() {
252         LOG.info("Reloading");
253         stop();
254         start();
255     }
256
257     private void restartXtr() {
258         LOG.info("Reloading xTR");
259         stopXtr();
260         startXtr();
261     }
262
263     private void unloadActions() {
264         lispSouthboundHandler = null;
265
266         stop();
267         stopXtr();
268
269         LOG.info("LISP (RFC6830) Southbound Plugin is down!");
270     }
271
272     /**
273      * Restore all keys from MDSAL datastore.
274      */
275     public void restoreDaoFromDatastore() {
276         final List<AuthenticationKey> authKeys = dsbe.getAllAuthenticationKeys();
277         LOG.info("Restoring {} keys from datastore into southbound DAO", authKeys.size());
278
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);
286         }
287     }
288
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);
293     }
294
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];
299         }
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));
307         }
308         senderChannel.write(packet).addListener(future -> {
309             if (future.isSuccess()) {
310                 LOG.trace("Success");
311                 statistics.incrementTx(packetType.getIntValue());
312             } else {
313                 LOG.warn("Failed to send packet");
314                 statistics.incrementTxErrors();
315             }
316         });
317         senderChannel.flush();
318     }
319
320     private static InetAddress getInetAddress(final TransportAddress address) {
321         requireNonNull(address, "TransportAddress must not be null");
322         IpAddressBinary ip = address.getIpAddress();
323         try {
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());
328             }
329         } catch (UnknownHostException e) {
330             LOG.debug("Could not convert TransportAddress {} to InetAddress", address, e);
331         }
332         return null;
333     }
334
335     @Override
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.");
341             } else {
342                 LOG.debug("Setting LISP binding address to {}", address);
343                 bindingAddress = address;
344                 if (channel != null) {
345                     try {
346                         restart();
347                         restartXtr();
348                     } catch (Exception e) {
349                         LOG.error("Failed to set LISP binding address: ", e);
350                     }
351                 }
352             }
353         }
354     }
355
356     @Override
357     public void shouldListenOnXtrPort(final boolean shouldListenOnXtrPort) {
358         listenOnXtrPort = shouldListenOnXtrPort;
359         if (listenOnXtrPort) {
360             restartXtr();
361         } else {
362             LOG.info("Shutting down xTR");
363             stopXtr();
364         }
365     }
366
367     @Override
368     public void setXtrPort(final int port) {
369         xtrPort = port;
370         if (listenOnXtrPort) {
371             restartXtr();
372         }
373     }
374
375     @Deactivate
376     @PreDestroy
377     @Override
378     public void close() throws Exception {
379         eventLoopGroup.shutdownGracefully();
380         lispSouthboundHandler.close();
381         unloadActions();
382         clusterSingletonService.close();
383         dsbe.closeTransactionChain();
384     }
385
386     @Override
387     public void instantiateServiceInstance() {
388         isMaster = true;
389     }
390
391     @Override
392     public ListenableFuture<Void> closeServiceInstance() {
393         isMaster = false;
394         return Futures.<Void>immediateFuture(null);
395     }
396
397     @Override
398     public ServiceGroupIdentifier getIdentifier() {
399         return SERVICE_GROUP_IDENTIFIER;
400     }
401
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!");
408         }
409     }
410
411     public AuthKeyDb getAkdb() {
412         return akdb;
413     }
414
415     public ConcurrentLispSouthboundStats getStats() {
416         return statistics;
417     }
418
419     public DataBroker getDataBroker() {
420         return dataBroker;
421     }
422
423     public AuthenticationKeyDataListener getAuthenticationKeyDataListener() {
424         return authenticationKeyDataListener;
425     }
426
427     public MapRegisterCache getMapRegisterCache() {
428         return mapRegisterCache;
429     }
430
431     public boolean isMapRegisterCacheEnabled() {
432         return mapRegisterCacheEnabled;
433     }
434
435     public long getMapRegisterCacheTimeout() {
436         return mapRegisterCacheTimeout;
437     }
438 }