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