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