Merge "Make Map-Register cache configurable"
[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
15 import io.netty.bootstrap.Bootstrap;
16 import io.netty.buffer.ByteBuf;
17 import io.netty.buffer.ByteBufUtil;
18 import io.netty.channel.ChannelFuture;
19 import io.netty.channel.ChannelFutureListener;
20 import io.netty.channel.EventLoopGroup;
21 import io.netty.channel.nio.NioEventLoopGroup;
22 import io.netty.channel.socket.DatagramPacket;
23 import io.netty.channel.socket.nio.NioDatagramChannel;
24 import io.netty.util.concurrent.DefaultThreadFactory;
25
26 import java.net.InetAddress;
27 import java.net.InetSocketAddress;
28 import java.net.UnknownHostException;
29 import java.nio.ByteBuffer;
30 import java.util.concurrent.ThreadFactory;
31
32 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
33 import org.opendaylight.controller.md.sal.binding.api.NotificationPublishService;
34 import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.RpcRegistration;
35 import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
36 import org.opendaylight.lispflowmapping.lisp.type.LispMessage;
37 import org.opendaylight.lispflowmapping.southbound.lisp.LispSouthboundHandler;
38 import org.opendaylight.lispflowmapping.southbound.lisp.LispXtrSouthboundHandler;
39 import org.opendaylight.lispflowmapping.type.sbplugin.IConfigLispSouthboundPlugin;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.inet.binary.types.rev160303.IpAddressBinary;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MessageType;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.transport.address.TransportAddress;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.sb.rev150904.OdlLispSbService;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46
47 public class LispSouthboundPlugin implements IConfigLispSouthboundPlugin, AutoCloseable {
48     protected static final Logger LOG = LoggerFactory.getLogger(LispSouthboundPlugin.class);
49
50     private static Object startLock = new Object();
51     private LispSouthboundHandler lispSouthboundHandler;
52     private LispXtrSouthboundHandler lispXtrSouthboundHandler;
53     private NotificationPublishService notificationPublishService;
54     private RpcProviderRegistry rpcRegistry;
55     private NioDatagramChannel channel;
56     private volatile String bindingAddress = "0.0.0.0";
57     private volatile int xtrPort = LispMessage.XTR_PORT_NUM;
58     private volatile boolean listenOnXtrPort = false;
59     private boolean mapRegisterCacheEnabled = true;
60     private RpcRegistration<OdlLispSbService> sbRpcRegistration;
61     private NioDatagramChannel xtrChannel;
62     private LispSouthboundStats statistics = new LispSouthboundStats();
63     private Bootstrap bootstrap = new Bootstrap();
64     private Bootstrap xtrBootstrap = new Bootstrap();
65     private ThreadFactory threadFactory = new DefaultThreadFactory("lisp-sb");
66     private EventLoopGroup eventLoopGroup = new NioEventLoopGroup(0, threadFactory);
67     private DataBroker dataBroker;
68
69
70     public void init() {
71         LOG.info("LISP (RFC6830) Southbound Plugin is initializing...");
72         final LispSouthboundRPC sbRpcHandler = new LispSouthboundRPC(this);
73
74         sbRpcRegistration = rpcRegistry.addRpcImplementation(OdlLispSbService.class, sbRpcHandler);
75
76         synchronized (startLock) {
77             lispSouthboundHandler = new LispSouthboundHandler(this);
78             lispSouthboundHandler.setDataBroker(dataBroker);
79             lispSouthboundHandler.setNotificationProvider(this.notificationPublishService);
80             lispSouthboundHandler.setMapRegisterCacheEnabled(mapRegisterCacheEnabled);
81             lispSouthboundHandler.init();
82
83             lispXtrSouthboundHandler = new LispXtrSouthboundHandler();
84             lispXtrSouthboundHandler.setNotificationProvider(this.notificationPublishService);
85
86             bootstrap.group(eventLoopGroup);
87             bootstrap.channel(NioDatagramChannel.class);
88             bootstrap.handler(lispSouthboundHandler);
89
90             xtrBootstrap.group(eventLoopGroup);
91             xtrBootstrap.channel(NioDatagramChannel.class);
92             xtrBootstrap.handler(lispXtrSouthboundHandler);
93
94             start();
95             startXtr();
96
97             LOG.info("LISP (RFC6830) Southbound Plugin is up!");
98         }
99     }
100
101     private void start() {
102         try {
103             channel = (NioDatagramChannel) bootstrap.bind(bindingAddress, LispMessage.PORT_NUM).sync().channel();
104             LOG.debug("Binding LISP UDP listening socket to {}:{}", bindingAddress, LispMessage.PORT_NUM);
105         } catch (Exception e) {
106             LOG.error("Failed to open main socket ", e);
107         }
108     }
109
110     private void startXtr() {
111         if (listenOnXtrPort) {
112             try {
113                 xtrChannel = (NioDatagramChannel) xtrBootstrap.bind(bindingAddress, xtrPort).sync().channel();
114                 LOG.debug("Binding LISP xTR UDP listening socket to {}:{}", bindingAddress, xtrPort);
115             } catch (Exception e) {
116                 LOG.error("Failed to open xTR socket ", e);
117             }
118         }
119     }
120
121     private void stop() {
122         try {
123             channel.close().sync();
124             channel = null;
125         } catch (Exception e) {
126             LOG.error("Failed to close main socket ", e);
127         }
128     }
129
130     private void stopXtr() {
131         if (listenOnXtrPort) {
132             try {
133                 xtrChannel.close().sync();
134                 xtrChannel = null;
135             } catch (Exception e) {
136                 LOG.error("Failed to close xTR socket ", e);
137             }
138         }
139     }
140
141     private void restart() {
142         LOG.info("Reloading");
143         stop();
144         start();
145     }
146
147     private void restartXtr() {
148         LOG.info("Reloading xTR");
149         stopXtr();
150         startXtr();
151     }
152
153     public void setNotificationPublishService(NotificationPublishService notificationService) {
154         this.notificationPublishService = notificationService;
155     }
156
157     public void setRpcRegistryDependency(RpcProviderRegistry rpcRegistry) {
158         this.rpcRegistry = rpcRegistry;
159     }
160
161     private void unloadActions() {
162         lispSouthboundHandler = null;
163         lispXtrSouthboundHandler = null;
164
165         stop();
166         stopXtr();
167
168         LOG.info("LISP (RFC6830) Southbound Plugin is down!");
169     }
170
171     public void handleSerializedLispBuffer(TransportAddress address, ByteBuffer outBuffer,
172             final MessageType packetType) {
173         InetAddress ip = getInetAddress(address);
174         handleSerializedLispBuffer(ip, outBuffer, packetType, address.getPort().getValue());
175     }
176
177     public void handleSerializedLispBuffer(InetAddress address, ByteBuffer outBuffer,
178             final MessageType packetType, final int portNumber) {
179         InetSocketAddress recipient = new InetSocketAddress(address, portNumber);
180         outBuffer.position(0);
181         ByteBuf data = wrappedBuffer(outBuffer);
182         DatagramPacket packet = new DatagramPacket(data, recipient);
183         LOG.debug("Sending {} on port {} to address: {}", packetType, portNumber, address);
184         if (LOG.isTraceEnabled()) {
185             LOG.trace("Buffer:\n{}", ByteBufUtil.prettyHexDump(data));
186         }
187         channel.write(packet).addListener(new ChannelFutureListener() {
188             @Override
189             public void operationComplete(ChannelFuture future) {
190                 if (future.isSuccess()) {
191                     LOG.trace("Success");
192                     statistics.incrementTx(packetType.getIntValue());
193                 } else {
194                     LOG.warn("Failed to send packet");
195                     statistics.incrementTxErrors();
196                 }
197             }
198         });
199         channel.flush();
200     }
201
202     private InetAddress getInetAddress(TransportAddress address) {
203         Preconditions.checkNotNull(address, "TransportAddress must not be null");
204         IpAddressBinary ip = address.getIpAddress();
205         try {
206             if (ip.getIpv4AddressBinary() != null) {
207                 return InetAddress.getByAddress(ip.getIpv4AddressBinary().getValue());
208             } else if (ip.getIpv6AddressBinary() != null) {
209                 return InetAddress.getByAddress(ip.getIpv6AddressBinary().getValue());
210             }
211         } catch (UnknownHostException e) {
212             LOG.debug("Could not convert TransportAddress {} to InetAddress", address, e);
213         }
214         return null;
215     }
216
217     public LispSouthboundStats getStats() {
218         return statistics;
219     }
220
221     @Override
222     public void setLispAddress(String address) {
223         synchronized (startLock) {
224             if (bindingAddress.equals(address)) {
225                 LOG.debug("Configured LISP binding address didn't change.");
226             } else {
227                 LOG.debug("Setting LISP binding address to {}", address);
228                 bindingAddress = address;
229                 if (channel != null) {
230                     try {
231                         restart();
232                         restartXtr();
233                     } catch (Exception e) {
234                         LOG.error("Failed to set LISP binding address: ", e);
235                     }
236                 }
237             }
238         }
239     }
240
241     @Override
242     public void shouldListenOnXtrPort(boolean shouldListenOnXtrPort) {
243         listenOnXtrPort = shouldListenOnXtrPort;
244         if (listenOnXtrPort) {
245             restartXtr();
246         } else {
247             LOG.info("Shutting down xTR");
248             stopXtr();
249         }
250     }
251
252     @Override
253     public void setXtrPort(int port) {
254         this.xtrPort = port;
255         if (listenOnXtrPort) {
256             restartXtr();
257         }
258     }
259
260     public void setDataBroker(final DataBroker dataBroker) {
261         this.dataBroker = dataBroker;
262     }
263
264     public void setMapRegisterCacheEnabled(final boolean mapRegisterCacheEnabled) {
265         this.mapRegisterCacheEnabled = mapRegisterCacheEnabled;
266         if (mapRegisterCacheEnabled) {
267             LOG.info("Enabling Map-Register cache");
268         } else {
269             LOG.info("Disabling Map-Register cache");
270         }
271     }
272
273     @Override
274     public void close() throws Exception {
275         unloadActions();
276         eventLoopGroup.shutdownGracefully();
277         sbRpcRegistration.close();
278         lispSouthboundHandler.close();
279     }
280 }