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