Merge "Restoring authentication key from MDSAL."
[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             lispSouthboundHandler.restoreDaoFromDatastore();
83
84             lispXtrSouthboundHandler = new LispXtrSouthboundHandler();
85             lispXtrSouthboundHandler.setNotificationProvider(this.notificationPublishService);
86
87             bootstrap.group(eventLoopGroup);
88             bootstrap.channel(NioDatagramChannel.class);
89             bootstrap.handler(lispSouthboundHandler);
90
91             xtrBootstrap.group(eventLoopGroup);
92             xtrBootstrap.channel(NioDatagramChannel.class);
93             xtrBootstrap.handler(lispXtrSouthboundHandler);
94
95             start();
96             startXtr();
97
98             LOG.info("LISP (RFC6830) Southbound Plugin is up!");
99         }
100     }
101
102     private void start() {
103         try {
104             channel = (NioDatagramChannel) bootstrap.bind(bindingAddress, LispMessage.PORT_NUM).sync().channel();
105             LOG.debug("Binding LISP UDP listening socket to {}:{}", bindingAddress, LispMessage.PORT_NUM);
106         } catch (Exception e) {
107             LOG.error("Failed to open main socket ", e);
108         }
109     }
110
111     private void startXtr() {
112         if (listenOnXtrPort) {
113             try {
114                 xtrChannel = (NioDatagramChannel) xtrBootstrap.bind(bindingAddress, xtrPort).sync().channel();
115                 LOG.debug("Binding LISP xTR UDP listening socket to {}:{}", bindingAddress, xtrPort);
116             } catch (Exception e) {
117                 LOG.error("Failed to open xTR socket ", e);
118             }
119         }
120     }
121
122     private void stop() {
123         try {
124             channel.close().sync();
125             channel = null;
126         } catch (Exception e) {
127             LOG.error("Failed to close main socket ", e);
128         }
129     }
130
131     private void stopXtr() {
132         if (listenOnXtrPort) {
133             try {
134                 xtrChannel.close().sync();
135                 xtrChannel = null;
136             } catch (Exception e) {
137                 LOG.error("Failed to close xTR socket ", e);
138             }
139         }
140     }
141
142     private void restart() {
143         LOG.info("Reloading");
144         stop();
145         start();
146     }
147
148     private void restartXtr() {
149         LOG.info("Reloading xTR");
150         stopXtr();
151         startXtr();
152     }
153
154     public void setNotificationPublishService(NotificationPublishService notificationService) {
155         this.notificationPublishService = notificationService;
156     }
157
158     public void setRpcRegistryDependency(RpcProviderRegistry rpcRegistry) {
159         this.rpcRegistry = rpcRegistry;
160     }
161
162     private void unloadActions() {
163         lispSouthboundHandler = null;
164         lispXtrSouthboundHandler = null;
165
166         stop();
167         stopXtr();
168
169         LOG.info("LISP (RFC6830) Southbound Plugin is down!");
170     }
171
172     public void handleSerializedLispBuffer(TransportAddress address, ByteBuffer outBuffer,
173             final MessageType packetType) {
174         InetAddress ip = getInetAddress(address);
175         handleSerializedLispBuffer(ip, outBuffer, packetType, address.getPort().getValue());
176     }
177
178     public void handleSerializedLispBuffer(InetAddress address, ByteBuffer outBuffer,
179             final MessageType packetType, final int portNumber) {
180         InetSocketAddress recipient = new InetSocketAddress(address, portNumber);
181         outBuffer.position(0);
182         ByteBuf data = wrappedBuffer(outBuffer);
183         DatagramPacket packet = new DatagramPacket(data, recipient);
184         LOG.debug("Sending {} on port {} to address: {}", packetType, portNumber, address);
185         if (LOG.isTraceEnabled()) {
186             LOG.trace("Buffer:\n{}", ByteBufUtil.prettyHexDump(data));
187         }
188         channel.write(packet).addListener(new ChannelFutureListener() {
189             @Override
190             public void operationComplete(ChannelFuture future) {
191                 if (future.isSuccess()) {
192                     LOG.trace("Success");
193                     statistics.incrementTx(packetType.getIntValue());
194                 } else {
195                     LOG.warn("Failed to send packet");
196                     statistics.incrementTxErrors();
197                 }
198             }
199         });
200         channel.flush();
201     }
202
203     private InetAddress getInetAddress(TransportAddress address) {
204         Preconditions.checkNotNull(address, "TransportAddress must not be null");
205         IpAddressBinary ip = address.getIpAddress();
206         try {
207             if (ip.getIpv4AddressBinary() != null) {
208                 return InetAddress.getByAddress(ip.getIpv4AddressBinary().getValue());
209             } else if (ip.getIpv6AddressBinary() != null) {
210                 return InetAddress.getByAddress(ip.getIpv6AddressBinary().getValue());
211             }
212         } catch (UnknownHostException e) {
213             LOG.debug("Could not convert TransportAddress {} to InetAddress", address, e);
214         }
215         return null;
216     }
217
218     public LispSouthboundStats getStats() {
219         return statistics;
220     }
221
222     @Override
223     public void setLispAddress(String address) {
224         synchronized (startLock) {
225             if (bindingAddress.equals(address)) {
226                 LOG.debug("Configured LISP binding address didn't change.");
227             } else {
228                 LOG.debug("Setting LISP binding address to {}", address);
229                 bindingAddress = address;
230                 if (channel != null) {
231                     try {
232                         restart();
233                         restartXtr();
234                     } catch (Exception e) {
235                         LOG.error("Failed to set LISP binding address: ", e);
236                     }
237                 }
238             }
239         }
240     }
241
242     @Override
243     public void shouldListenOnXtrPort(boolean shouldListenOnXtrPort) {
244         listenOnXtrPort = shouldListenOnXtrPort;
245         if (listenOnXtrPort) {
246             restartXtr();
247         } else {
248             LOG.info("Shutting down xTR");
249             stopXtr();
250         }
251     }
252
253     @Override
254     public void setXtrPort(int port) {
255         this.xtrPort = port;
256         if (listenOnXtrPort) {
257             restartXtr();
258         }
259     }
260
261     public void setDataBroker(final DataBroker dataBroker) {
262         this.dataBroker = dataBroker;
263     }
264
265     public void setMapRegisterCacheEnabled(final boolean mapRegisterCacheEnabled) {
266         this.mapRegisterCacheEnabled = mapRegisterCacheEnabled;
267         if (mapRegisterCacheEnabled) {
268             LOG.info("Enabling Map-Register cache");
269         } else {
270             LOG.info("Disabling Map-Register cache");
271         }
272     }
273
274     @Override
275     public void close() throws Exception {
276         eventLoopGroup.shutdownGracefully();
277         sbRpcRegistration.close();
278         lispSouthboundHandler.close();
279         unloadActions();
280     }
281 }