Configuration of southbound plugin via property placeholder
[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.md.sal.common.api.clustering.EntityOwnershipService;
35 import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.RpcRegistration;
36 import org.opendaylight.lispflowmapping.clustering.ClusterNodeModulSwitcherImpl;
37 import org.opendaylight.lispflowmapping.clustering.api.ClusterNodeModuleSwitcher;
38 import org.opendaylight.lispflowmapping.lisp.type.LispMessage;
39 import org.opendaylight.lispflowmapping.southbound.lisp.LispSouthboundHandler;
40 import org.opendaylight.lispflowmapping.southbound.lisp.LispXtrSouthboundHandler;
41 import org.opendaylight.lispflowmapping.type.sbplugin.IConfigLispSouthboundPlugin;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.inet.binary.types.rev160303.IpAddressBinary;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MessageType;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.transport.address.TransportAddress;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.sb.rev150904.OdlLispSbService;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48
49 public class LispSouthboundPlugin implements IConfigLispSouthboundPlugin, AutoCloseable, ClusterNodeModuleSwitcher {
50     protected static final Logger LOG = LoggerFactory.getLogger(LispSouthboundPlugin.class);
51
52     private volatile String bindingAddress;
53     private boolean mapRegisterCacheEnabled;
54     private static Object startLock = new Object();
55     private final ClusterNodeModulSwitcherImpl clusterNodeModulSwitcher;
56     private LispSouthboundHandler lispSouthboundHandler;
57     private LispXtrSouthboundHandler lispXtrSouthboundHandler;
58     private NotificationPublishService notificationPublishService;
59     private NioDatagramChannel channel;
60     private volatile int xtrPort = LispMessage.XTR_PORT_NUM;
61     private volatile boolean listenOnXtrPort = false;
62     private RpcRegistration<OdlLispSbService> sbRpcRegistration;
63     private NioDatagramChannel xtrChannel;
64     private LispSouthboundStats statistics = new LispSouthboundStats();
65     private Bootstrap bootstrap = new Bootstrap();
66     private Bootstrap xtrBootstrap = new Bootstrap();
67     private ThreadFactory threadFactory = new DefaultThreadFactory("lisp-sb");
68     private EventLoopGroup eventLoopGroup = new NioEventLoopGroup(0, threadFactory);
69     private DataBroker dataBroker;
70
71     public LispSouthboundPlugin(final DataBroker dataBroker,
72             final NotificationPublishService notificationPublishService,
73             final EntityOwnershipService entityOwnershipService) {
74         this.dataBroker = dataBroker;
75         this.notificationPublishService = notificationPublishService;
76         clusterNodeModulSwitcher = new ClusterNodeModulSwitcherImpl(entityOwnershipService);
77         clusterNodeModulSwitcher.setModule(this);
78     }
79
80     public void init() {
81         LOG.info("LISP (RFC6830) Southbound Plugin is initializing...");
82         synchronized (startLock) {
83             lispSouthboundHandler = new LispSouthboundHandler(this);
84             lispSouthboundHandler.setDataBroker(dataBroker);
85             lispSouthboundHandler.setNotificationProvider(this.notificationPublishService);
86             lispSouthboundHandler.setMapRegisterCacheEnabled(mapRegisterCacheEnabled);
87             lispSouthboundHandler.init();
88             lispSouthboundHandler.restoreDaoFromDatastore();
89
90             lispXtrSouthboundHandler = new LispXtrSouthboundHandler();
91             lispXtrSouthboundHandler.setNotificationProvider(this.notificationPublishService);
92
93             bootstrap.group(eventLoopGroup);
94             bootstrap.channel(NioDatagramChannel.class);
95             bootstrap.handler(lispSouthboundHandler);
96
97             xtrBootstrap.group(eventLoopGroup);
98             xtrBootstrap.channel(NioDatagramChannel.class);
99             xtrBootstrap.handler(lispXtrSouthboundHandler);
100
101             start();
102             startXtr();
103
104             LOG.info("LISP (RFC6830) Southbound Plugin is up!");
105         }
106         clusterNodeModulSwitcher.switchModuleByEntityOwnership();
107     }
108
109     private void start() {
110         try {
111             channel = (NioDatagramChannel) bootstrap.bind(bindingAddress, LispMessage.PORT_NUM).sync().channel();
112             LOG.debug("Binding LISP UDP listening socket to {}:{}", bindingAddress, LispMessage.PORT_NUM);
113         } catch (Exception e) {
114             LOG.error("Failed to open main socket ", e);
115         }
116     }
117
118     private void startXtr() {
119         if (listenOnXtrPort) {
120             try {
121                 xtrChannel = (NioDatagramChannel) xtrBootstrap.bind(bindingAddress, xtrPort).sync().channel();
122                 LOG.debug("Binding LISP xTR UDP listening socket to {}:{}", bindingAddress, xtrPort);
123             } catch (Exception e) {
124                 LOG.error("Failed to open xTR socket ", e);
125             }
126         }
127     }
128
129     private void stop() {
130         try {
131             channel.close().sync();
132             channel = null;
133         } catch (Exception e) {
134             LOG.error("Failed to close main socket ", e);
135         }
136     }
137
138     private void stopXtr() {
139         if (listenOnXtrPort) {
140             try {
141                 xtrChannel.close().sync();
142                 xtrChannel = null;
143             } catch (Exception e) {
144                 LOG.error("Failed to close xTR socket ", e);
145             }
146         }
147     }
148
149     private void restart() {
150         LOG.info("Reloading");
151         stop();
152         start();
153     }
154
155     private void restartXtr() {
156         LOG.info("Reloading xTR");
157         stopXtr();
158         startXtr();
159     }
160
161     private void unloadActions() {
162         lispSouthboundHandler = null;
163         lispXtrSouthboundHandler = null;
164
165         stop();
166         stopXtr();
167
168         LOG.info("LISP (RFC6830) Southbound Plugin is down!");
169     }
170
171     public void handleSerializedLispBuffer(TransportAddress address, ByteBuffer outBuffer,
172             final MessageType packetType) {
173         InetAddress ip = getInetAddress(address);
174         handleSerializedLispBuffer(ip, outBuffer, packetType, address.getPort().getValue());
175     }
176
177     public void handleSerializedLispBuffer(InetAddress address, ByteBuffer outBuffer,
178             final MessageType packetType, final int portNumber) {
179         InetSocketAddress recipient = new InetSocketAddress(address, portNumber);
180         outBuffer.position(0);
181         ByteBuf data = wrappedBuffer(outBuffer);
182         DatagramPacket packet = new DatagramPacket(data, recipient);
183         LOG.debug("Sending {} on port {} to address: {}", packetType, portNumber, address);
184         if (LOG.isTraceEnabled()) {
185             LOG.trace("Buffer:\n{}", ByteBufUtil.prettyHexDump(data));
186         }
187         channel.write(packet).addListener(new ChannelFutureListener() {
188             @Override
189             public void operationComplete(ChannelFuture future) {
190                 if (future.isSuccess()) {
191                     LOG.trace("Success");
192                     statistics.incrementTx(packetType.getIntValue());
193                 } else {
194                     LOG.warn("Failed to send packet");
195                     statistics.incrementTxErrors();
196                 }
197             }
198         });
199         channel.flush();
200     }
201
202     private InetAddress getInetAddress(TransportAddress address) {
203         Preconditions.checkNotNull(address, "TransportAddress must not be null");
204         IpAddressBinary ip = address.getIpAddress();
205         try {
206             if (ip.getIpv4AddressBinary() != null) {
207                 return InetAddress.getByAddress(ip.getIpv4AddressBinary().getValue());
208             } else if (ip.getIpv6AddressBinary() != null) {
209                 return InetAddress.getByAddress(ip.getIpv6AddressBinary().getValue());
210             }
211         } catch (UnknownHostException e) {
212             LOG.debug("Could not convert TransportAddress {} to InetAddress", address, e);
213         }
214         return null;
215     }
216
217     public LispSouthboundStats getStats() {
218         return statistics;
219     }
220
221     @Override
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 setBindingAddress(String bindingAddress) {
270         this.bindingAddress = bindingAddress;
271     }
272
273     @Override
274     public void close() throws Exception {
275         eventLoopGroup.shutdownGracefully();
276         sbRpcRegistration.close();
277         lispSouthboundHandler.close();
278         unloadActions();
279     }
280
281     @Override
282     public void stopModule() {
283         if (lispSouthboundHandler != null) {
284             lispSouthboundHandler.setNotificationProvider(null);
285             lispSouthboundHandler.setIsReadFromChannelEnabled(false);
286         }
287         if (lispXtrSouthboundHandler != null) {
288             lispXtrSouthboundHandler.setNotificationProvider(null);
289         }
290     }
291
292     @Override
293     public void startModule() {
294         if (lispSouthboundHandler != null) {
295             lispSouthboundHandler.setNotificationProvider(notificationPublishService);
296             lispSouthboundHandler.restoreDaoFromDatastore();
297             lispSouthboundHandler.setIsReadFromChannelEnabled(true);
298         }
299         if (lispXtrSouthboundHandler != null) {
300             lispXtrSouthboundHandler.setNotificationProvider(notificationPublishService);
301         }
302     }
303 }