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