Make Channel an argument to handleSerializedLispBuffer()
[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 ConcurrentLispSouthboundStats statistics = new ConcurrentLispSouthboundStats();
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(), null);
211     }
212
213     public void handleSerializedLispBuffer(InetAddress address, ByteBuffer outBuffer,
214             final MessageType packetType, final int portNumber, Channel senderChannel) {
215         if (senderChannel == null) {
216             senderChannel = this.channel;
217         }
218         InetSocketAddress recipient = new InetSocketAddress(address, portNumber);
219         outBuffer.position(0);
220         ByteBuf data = wrappedBuffer(outBuffer);
221         DatagramPacket packet = new DatagramPacket(data, recipient);
222         LOG.debug("Sending {} on port {} to address: {}", packetType, portNumber, address);
223         if (LOG.isTraceEnabled()) {
224             LOG.trace("Buffer:\n{}", ByteBufUtil.prettyHexDump(data));
225         }
226         senderChannel.write(packet).addListener(new ChannelFutureListener() {
227             @Override
228             public void operationComplete(ChannelFuture future) {
229                 if (future.isSuccess()) {
230                     LOG.trace("Success");
231                     statistics.incrementTx(packetType.getIntValue());
232                 } else {
233                     LOG.warn("Failed to send packet");
234                     statistics.incrementTxErrors();
235                 }
236             }
237         });
238         senderChannel.flush();
239     }
240
241     private InetAddress getInetAddress(TransportAddress address) {
242         Preconditions.checkNotNull(address, "TransportAddress must not be null");
243         IpAddressBinary ip = address.getIpAddress();
244         try {
245             if (ip.getIpv4AddressBinary() != null) {
246                 return InetAddress.getByAddress(ip.getIpv4AddressBinary().getValue());
247             } else if (ip.getIpv6AddressBinary() != null) {
248                 return InetAddress.getByAddress(ip.getIpv6AddressBinary().getValue());
249             }
250         } catch (UnknownHostException e) {
251             LOG.debug("Could not convert TransportAddress {} to InetAddress", address, e);
252         }
253         return null;
254     }
255
256     public ConcurrentLispSouthboundStats getStats() {
257         return statistics;
258     }
259
260     @Override
261     @SuppressWarnings("checkstyle:IllegalCatch")
262     public void setLispAddress(String address) {
263         synchronized (startLock) {
264             if (bindingAddress.equals(address)) {
265                 LOG.debug("Configured LISP binding address didn't change.");
266             } else {
267                 LOG.debug("Setting LISP binding address to {}", address);
268                 bindingAddress = address;
269                 if (channel != null) {
270                     try {
271                         restart();
272                         restartXtr();
273                     } catch (Exception e) {
274                         LOG.error("Failed to set LISP binding address: ", e);
275                     }
276                 }
277             }
278         }
279     }
280
281     @Override
282     public void shouldListenOnXtrPort(boolean shouldListenOnXtrPort) {
283         listenOnXtrPort = shouldListenOnXtrPort;
284         if (listenOnXtrPort) {
285             restartXtr();
286         } else {
287             LOG.info("Shutting down xTR");
288             stopXtr();
289         }
290     }
291
292     @Override
293     public void setXtrPort(int port) {
294         this.xtrPort = port;
295         if (listenOnXtrPort) {
296             restartXtr();
297         }
298     }
299
300     public void setMapRegisterCacheEnabled(final boolean mapRegisterCacheEnabled) {
301         this.mapRegisterCacheEnabled = mapRegisterCacheEnabled;
302         if (mapRegisterCacheEnabled) {
303             LOG.info("Enabling Map-Register cache");
304         } else {
305             LOG.info("Disabling Map-Register cache");
306         }
307     }
308
309     public void setMapRegisterCacheTimeout(long mapRegisterCacheTimeout) {
310         this.mapRegisterCacheTimeout = mapRegisterCacheTimeout;
311     }
312
313     public void setBindingAddress(String bindingAddress) {
314         this.bindingAddress = bindingAddress;
315     }
316
317     @Override
318     public void close() throws Exception {
319         eventLoopGroup.shutdownGracefully();
320         lispSouthboundHandler.close();
321         unloadActions();
322         clusterSingletonService.close();
323     }
324
325     @Override
326     public void instantiateServiceInstance() {
327         if (lispSouthboundHandler != null) {
328             lispSouthboundHandler.setNotificationProvider(notificationPublishService);
329             lispSouthboundHandler.restoreDaoFromDatastore();
330             lispSouthboundHandler.setIsMaster(true);
331         }
332         if (lispXtrSouthboundHandler != null) {
333             lispXtrSouthboundHandler.setNotificationProvider(notificationPublishService);
334         }
335     }
336
337     @Override
338     public ListenableFuture<Void> closeServiceInstance() {
339         if (lispSouthboundHandler != null) {
340             lispSouthboundHandler.setNotificationProvider(null);
341             lispSouthboundHandler.setIsMaster(false);
342         }
343         if (lispXtrSouthboundHandler != null) {
344             lispXtrSouthboundHandler.setNotificationProvider(null);
345         }
346         return Futures.<Void>immediateFuture(null);
347     }
348
349     @Override
350     public ServiceGroupIdentifier getIdentifier() {
351         return SERVICE_GROUP_IDENTIFIER;
352     }
353
354     public MapRegisterCache getMapRegisterCache() {
355         return mapRegisterCache;
356     }
357
358     public boolean isMapRegisterCacheEnabled() {
359         return mapRegisterCacheEnabled;
360     }
361
362     public long getMapRegisterCacheTimeout() {
363         return mapRegisterCacheTimeout;
364     }
365 }