Bug 6361: Make LispSouthboundHandler stateless
[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
9 package org.opendaylight.lispflowmapping.southbound;
10
11 import static io.netty.buffer.Unpooled.wrappedBuffer;
12
13 import com.google.common.base.Preconditions;
14 import com.google.common.util.concurrent.Futures;
15 import com.google.common.util.concurrent.ListenableFuture;
16 import io.netty.bootstrap.Bootstrap;
17 import io.netty.buffer.ByteBuf;
18 import io.netty.buffer.ByteBufUtil;
19 import io.netty.channel.Channel;
20 import io.netty.channel.ChannelFuture;
21 import io.netty.channel.ChannelFutureListener;
22 import io.netty.channel.EventLoopGroup;
23 import io.netty.channel.epoll.Epoll;
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.DatagramPacket;
28 import io.netty.channel.socket.nio.NioDatagramChannel;
29 import io.netty.util.concurrent.DefaultThreadFactory;
30 import java.net.InetAddress;
31 import java.net.InetSocketAddress;
32 import java.net.UnknownHostException;
33 import java.nio.ByteBuffer;
34 import java.util.concurrent.ThreadFactory;
35 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
36 import org.opendaylight.controller.md.sal.binding.api.NotificationPublishService;
37 import org.opendaylight.lispflowmapping.dsbackend.DataStoreBackEnd;
38 import org.opendaylight.lispflowmapping.inmemorydb.HashMapDb;
39 import org.opendaylight.lispflowmapping.lisp.type.LispMessage;
40 import org.opendaylight.lispflowmapping.mapcache.SimpleMapCache;
41 import org.opendaylight.lispflowmapping.southbound.lisp.AuthenticationKeyDataListener;
42 import org.opendaylight.lispflowmapping.southbound.lisp.LispSouthboundHandler;
43 import org.opendaylight.lispflowmapping.southbound.lisp.LispXtrSouthboundHandler;
44 import org.opendaylight.lispflowmapping.southbound.lisp.cache.MapRegisterCache;
45 import org.opendaylight.lispflowmapping.type.sbplugin.IConfigLispSouthboundPlugin;
46 import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonService;
47 import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceProvider;
48 import org.opendaylight.mdsal.singleton.common.api.ServiceGroupIdentifier;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.inet.binary.types.rev160303.IpAddressBinary;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MessageType;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.transport.address.TransportAddress;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
54
55 public class LispSouthboundPlugin implements IConfigLispSouthboundPlugin, AutoCloseable, ClusterSingletonService {
56     protected static final Logger LOG = LoggerFactory.getLogger(LispSouthboundPlugin.class);
57     public static final String LISPFLOWMAPPING_ENTITY_NAME = "lispflowmapping";
58     public static final ServiceGroupIdentifier SERVICE_GROUP_IDENTIFIER = ServiceGroupIdentifier.create(
59             LISPFLOWMAPPING_ENTITY_NAME);
60
61     private volatile String bindingAddress;
62     private SimpleMapCache smc;
63     private MapRegisterCache mapRegisterCache = new MapRegisterCache();
64     private boolean mapRegisterCacheEnabled;
65     private long mapRegisterCacheTimeout;
66
67     private static Object startLock = new Object();
68     private final ClusterSingletonServiceProvider clusterSingletonService;
69     private LispSouthboundHandler lispSouthboundHandler;
70     private LispXtrSouthboundHandler lispXtrSouthboundHandler;
71     private NotificationPublishService notificationPublishService;
72     private Channel channel;
73     private Channel xtrChannel;
74     private Class channelType;
75     private volatile int xtrPort = LispMessage.XTR_PORT_NUM;
76     private volatile boolean listenOnXtrPort = false;
77     private LispSouthboundStats statistics = new LispSouthboundStats();
78     private Bootstrap bootstrap = new Bootstrap();
79     private Bootstrap xtrBootstrap = new Bootstrap();
80     private ThreadFactory threadFactory = new DefaultThreadFactory("lisp-sb");
81     private EventLoopGroup eventLoopGroup;
82     private DataBroker dataBroker;
83     private AuthenticationKeyDataListener authenticationKeyDataListener;
84     private DataStoreBackEnd dsbe;
85
86     public LispSouthboundPlugin(final DataBroker dataBroker,
87             final NotificationPublishService notificationPublishService,
88             final ClusterSingletonServiceProvider clusterSingletonService) {
89         this.dataBroker = dataBroker;
90         this.notificationPublishService = notificationPublishService;
91         this.clusterSingletonService = clusterSingletonService;
92         this.clusterSingletonService.registerClusterSingletonService(this);
93     }
94
95     public void init() {
96         LOG.info("LISP (RFC6830) Southbound Plugin is initializing...");
97         synchronized (startLock) {
98             this.smc = new SimpleMapCache(new HashMapDb());
99             this.authenticationKeyDataListener = new AuthenticationKeyDataListener(dataBroker, smc);
100             this.dsbe = new DataStoreBackEnd(dataBroker);
101
102             lispSouthboundHandler = new LispSouthboundHandler(this);
103             lispSouthboundHandler.setDataBroker(dataBroker);
104             lispSouthboundHandler.setNotificationProvider(notificationPublishService);
105             lispSouthboundHandler.setSimpleMapCache(smc);
106             lispSouthboundHandler.setMapRegisterCache(mapRegisterCache);
107             lispSouthboundHandler.setMapRegisterCacheTimeout(mapRegisterCacheTimeout);
108             lispSouthboundHandler.setAuthenticationKeyDataListener(authenticationKeyDataListener);
109             lispSouthboundHandler.setDataStoreBackEnd(dsbe);
110             lispSouthboundHandler.setStats(statistics);
111             lispSouthboundHandler.restoreDaoFromDatastore();
112
113             lispXtrSouthboundHandler = new LispXtrSouthboundHandler();
114             lispXtrSouthboundHandler.setNotificationProvider(notificationPublishService);
115
116             if (Epoll.isAvailable()) {
117                 eventLoopGroup = new EpollEventLoopGroup(0, threadFactory);
118                 channelType = EpollDatagramChannel.class;
119                 LOG.debug("Using Netty Epoll for UDP sockets");
120             } else {
121                 eventLoopGroup = new NioEventLoopGroup(0, threadFactory);
122                 channelType = NioDatagramChannel.class;
123                 LOG.debug("Using Netty I/O (non-Epoll) for UDP sockets");
124             }
125
126             bootstrap.group(eventLoopGroup);
127             bootstrap.channel(channelType);
128             bootstrap.handler(lispSouthboundHandler);
129
130             xtrBootstrap.group(eventLoopGroup);
131             xtrBootstrap.channel(channelType);
132             xtrBootstrap.handler(lispXtrSouthboundHandler);
133
134             start();
135             startXtr();
136
137             LOG.info("LISP (RFC6830) Southbound Plugin is up!");
138         }
139     }
140
141     @SuppressWarnings("checkstyle:IllegalCatch")
142     private void start() {
143         try {
144             channel = bootstrap.bind(bindingAddress, LispMessage.PORT_NUM).sync().channel();
145             LOG.debug("Binding LISP UDP listening socket to {}:{}", bindingAddress, LispMessage.PORT_NUM);
146         } catch (Exception e) {
147             LOG.error("Failed to open main socket ", e);
148         }
149     }
150
151     @SuppressWarnings("checkstyle:IllegalCatch")
152     private void startXtr() {
153         if (listenOnXtrPort) {
154             try {
155                 xtrChannel = xtrBootstrap.bind(bindingAddress, xtrPort).sync().channel();
156                 LOG.debug("Binding LISP xTR UDP listening socket to {}:{}", bindingAddress, xtrPort);
157             } catch (Exception e) {
158                 LOG.error("Failed to open xTR socket ", e);
159             }
160         }
161     }
162
163     @SuppressWarnings("checkstyle:IllegalCatch")
164     private void stop() {
165         try {
166             channel.close().sync();
167             channel = null;
168         } catch (Exception e) {
169             LOG.error("Failed to close main socket ", e);
170         }
171     }
172
173     @SuppressWarnings("checkstyle:IllegalCatch")
174     private void stopXtr() {
175         if (listenOnXtrPort) {
176             try {
177                 xtrChannel.close().sync();
178                 xtrChannel = null;
179             } catch (Exception e) {
180                 LOG.error("Failed to close xTR socket ", e);
181             }
182         }
183     }
184
185     private void restart() {
186         LOG.info("Reloading");
187         stop();
188         start();
189     }
190
191     private void restartXtr() {
192         LOG.info("Reloading xTR");
193         stopXtr();
194         startXtr();
195     }
196
197     private void unloadActions() {
198         lispSouthboundHandler = null;
199         lispXtrSouthboundHandler = null;
200
201         stop();
202         stopXtr();
203
204         LOG.info("LISP (RFC6830) Southbound Plugin is down!");
205     }
206
207     public void handleSerializedLispBuffer(TransportAddress address, ByteBuffer outBuffer,
208                                            final MessageType packetType) {
209         InetAddress ip = getInetAddress(address);
210         handleSerializedLispBuffer(ip, outBuffer, packetType, address.getPort().getValue());
211     }
212
213     public void handleSerializedLispBuffer(InetAddress address, ByteBuffer outBuffer,
214             final MessageType packetType, final int portNumber) {
215         InetSocketAddress recipient = new InetSocketAddress(address, portNumber);
216         outBuffer.position(0);
217         ByteBuf data = wrappedBuffer(outBuffer);
218         DatagramPacket packet = new DatagramPacket(data, recipient);
219         LOG.debug("Sending {} on port {} to address: {}", packetType, portNumber, address);
220         if (LOG.isTraceEnabled()) {
221             LOG.trace("Buffer:\n{}", ByteBufUtil.prettyHexDump(data));
222         }
223         channel.write(packet).addListener(new ChannelFutureListener() {
224             @Override
225             public void operationComplete(ChannelFuture future) {
226                 if (future.isSuccess()) {
227                     LOG.trace("Success");
228                     statistics.incrementTx(packetType.getIntValue());
229                 } else {
230                     LOG.warn("Failed to send packet");
231                     statistics.incrementTxErrors();
232                 }
233             }
234         });
235         channel.flush();
236     }
237
238     private InetAddress getInetAddress(TransportAddress address) {
239         Preconditions.checkNotNull(address, "TransportAddress must not be null");
240         IpAddressBinary ip = address.getIpAddress();
241         try {
242             if (ip.getIpv4AddressBinary() != null) {
243                 return InetAddress.getByAddress(ip.getIpv4AddressBinary().getValue());
244             } else if (ip.getIpv6AddressBinary() != null) {
245                 return InetAddress.getByAddress(ip.getIpv6AddressBinary().getValue());
246             }
247         } catch (UnknownHostException e) {
248             LOG.debug("Could not convert TransportAddress {} to InetAddress", address, e);
249         }
250         return null;
251     }
252
253     public LispSouthboundStats getStats() {
254         return statistics;
255     }
256
257     @Override
258     @SuppressWarnings("checkstyle:IllegalCatch")
259     public void setLispAddress(String address) {
260         synchronized (startLock) {
261             if (bindingAddress.equals(address)) {
262                 LOG.debug("Configured LISP binding address didn't change.");
263             } else {
264                 LOG.debug("Setting LISP binding address to {}", address);
265                 bindingAddress = address;
266                 if (channel != null) {
267                     try {
268                         restart();
269                         restartXtr();
270                     } catch (Exception e) {
271                         LOG.error("Failed to set LISP binding address: ", e);
272                     }
273                 }
274             }
275         }
276     }
277
278     @Override
279     public void shouldListenOnXtrPort(boolean shouldListenOnXtrPort) {
280         listenOnXtrPort = shouldListenOnXtrPort;
281         if (listenOnXtrPort) {
282             restartXtr();
283         } else {
284             LOG.info("Shutting down xTR");
285             stopXtr();
286         }
287     }
288
289     @Override
290     public void setXtrPort(int port) {
291         this.xtrPort = port;
292         if (listenOnXtrPort) {
293             restartXtr();
294         }
295     }
296
297     public void setMapRegisterCacheEnabled(final boolean mapRegisterCacheEnabled) {
298         this.mapRegisterCacheEnabled = mapRegisterCacheEnabled;
299         if (mapRegisterCacheEnabled) {
300             LOG.info("Enabling Map-Register cache");
301         } else {
302             LOG.info("Disabling Map-Register cache");
303         }
304     }
305
306     public void setMapRegisterCacheTimeout(long mapRegisterCacheTimeout) {
307         this.mapRegisterCacheTimeout = mapRegisterCacheTimeout;
308     }
309
310     public void setBindingAddress(String bindingAddress) {
311         this.bindingAddress = bindingAddress;
312     }
313
314     @Override
315     public void close() throws Exception {
316         eventLoopGroup.shutdownGracefully();
317         lispSouthboundHandler.close();
318         unloadActions();
319         clusterSingletonService.close();
320     }
321
322     @Override
323     public void instantiateServiceInstance() {
324         if (lispSouthboundHandler != null) {
325             lispSouthboundHandler.setNotificationProvider(notificationPublishService);
326             lispSouthboundHandler.restoreDaoFromDatastore();
327             lispSouthboundHandler.setIsMaster(true);
328         }
329         if (lispXtrSouthboundHandler != null) {
330             lispXtrSouthboundHandler.setNotificationProvider(notificationPublishService);
331         }
332     }
333
334     @Override
335     public ListenableFuture<Void> closeServiceInstance() {
336         if (lispSouthboundHandler != null) {
337             lispSouthboundHandler.setNotificationProvider(null);
338             lispSouthboundHandler.setIsMaster(false);
339         }
340         if (lispXtrSouthboundHandler != null) {
341             lispXtrSouthboundHandler.setNotificationProvider(null);
342         }
343         return Futures.<Void>immediateFuture(null);
344     }
345
346     @Override
347     public ServiceGroupIdentifier getIdentifier() {
348         return SERVICE_GROUP_IDENTIFIER;
349     }
350
351     public MapRegisterCache getMapRegisterCache() {
352         return mapRegisterCache;
353     }
354
355     public boolean isMapRegisterCacheEnabled() {
356         return mapRegisterCacheEnabled;
357     }
358
359     public long getMapRegisterCacheTimeout() {
360         return mapRegisterCacheTimeout;
361     }
362 }