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