Merge "MultiTableMapCacheTest test update"
[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         InetSocketAddress recipient = new InetSocketAddress(ip, address.getPort().getValue());
164         // the wrappedBuffer() method doesn't copy data, so this conversion shouldn't hurt performance
165         ByteBuf data = wrappedBuffer(outBuffer.array());
166         DatagramPacket packet = new DatagramPacket(data, recipient);
167         LOG.debug("Sending {} on port {} to address: {}", packetType, address.getPort().getValue(), ip);
168         if (LOG.isTraceEnabled()) {
169             LOG.trace("Buffer:\n{}", ByteBufUtil.prettyHexDump(data));
170         }
171         channel.write(packet).addListener(new ChannelFutureListener() {
172             @Override
173             public void operationComplete(ChannelFuture future) {
174                 if (future.isSuccess()) {
175                     LOG.trace("Success");
176                     statistics.incrementTx(packetType.getIntValue());
177                 } else {
178                     LOG.warn("Failed to send packet");
179                     statistics.incrementTxErrors();
180                 }
181             }
182         });
183         channel.flush();
184     }
185
186     private InetAddress getInetAddress(TransportAddress address) {
187         Preconditions.checkNotNull(address, "TransportAddress must not be null");
188         IpAddressBinary ip = address.getIpAddress();
189         try {
190             if (ip.getIpv4AddressBinary() != null) {
191                 return InetAddress.getByAddress(ip.getIpv4AddressBinary().getValue());
192             } else if (ip.getIpv6AddressBinary() != null) {
193                 return InetAddress.getByAddress(ip.getIpv6AddressBinary().getValue());
194             }
195         } catch (UnknownHostException e) {
196             LOG.debug("Could not convert TransportAddress {} to InetAddress", address, e);
197         }
198         return null;
199     }
200
201     public LispSouthboundStats getStats() {
202         return statistics;
203     }
204
205     @Override
206     public void setLispAddress(String address) {
207         synchronized (startLock) {
208             if (bindingAddress.equals(address)) {
209                 LOG.debug("Configured LISP binding address didn't change.");
210             } else {
211                 LOG.debug("Setting LISP binding address to {}", address);
212                 bindingAddress = address;
213                 try {
214                     restart();
215                     restartXtr();
216                 } catch (Exception e) {
217                     LOG.error("Failed to set LISP binding address: ", e);
218                 }
219             }
220         }
221     }
222
223     @Override
224     public void shouldListenOnXtrPort(boolean shouldListenOnXtrPort) {
225         listenOnXtrPort = shouldListenOnXtrPort;
226         if (listenOnXtrPort) {
227             restartXtr();
228         } else {
229             LOG.info("Shutting down xTR");
230             stopXtr();
231         }
232     }
233
234     @Override
235     public void setXtrPort(int port) {
236         this.xtrPort = port;
237         if (listenOnXtrPort) {
238             restartXtr();
239         }
240     }
241
242     @Override
243     public void close() throws Exception {
244         unloadActions();
245         eventLoopGroup.shutdownGracefully();
246         sbRpcRegistration.close();
247     }
248 }