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