Bug 6351 - Clustering rework.
[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 com.google.common.util.concurrent.Futures;
16 import com.google.common.util.concurrent.ListenableFuture;
17 import io.netty.bootstrap.Bootstrap;
18 import io.netty.buffer.ByteBuf;
19 import io.netty.buffer.ByteBufUtil;
20 import io.netty.channel.ChannelFuture;
21 import io.netty.channel.ChannelFutureListener;
22 import io.netty.channel.EventLoopGroup;
23 import io.netty.channel.nio.NioEventLoopGroup;
24 import io.netty.channel.socket.DatagramPacket;
25 import io.netty.channel.socket.nio.NioDatagramChannel;
26 import io.netty.util.concurrent.DefaultThreadFactory;
27
28 import java.net.InetAddress;
29 import java.net.InetSocketAddress;
30 import java.net.UnknownHostException;
31 import java.nio.ByteBuffer;
32 import java.util.concurrent.ThreadFactory;
33
34 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
35 import org.opendaylight.controller.md.sal.binding.api.NotificationPublishService;
36 import org.opendaylight.lispflowmapping.lisp.type.LispMessage;
37 import org.opendaylight.lispflowmapping.southbound.lisp.LispSouthboundHandler;
38 import org.opendaylight.lispflowmapping.southbound.lisp.LispXtrSouthboundHandler;
39 import org.opendaylight.lispflowmapping.type.sbplugin.IConfigLispSouthboundPlugin;
40 import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonService;
41 import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceProvider;
42 import org.opendaylight.mdsal.singleton.common.api.ServiceGroupIdentifier;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.inet.binary.types.rev160303.IpAddressBinary;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MessageType;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.transport.address.TransportAddress;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48
49 public class LispSouthboundPlugin implements IConfigLispSouthboundPlugin, AutoCloseable, ClusterSingletonService {
50     protected static final Logger LOG = LoggerFactory.getLogger(LispSouthboundPlugin.class);
51     public static final String LISPFLOWMAPPING_ENTITY_NAME = "lispflowmapping";
52     public static final ServiceGroupIdentifier SERVICE_GROUP_IDENTIFIER = ServiceGroupIdentifier.create(
53             LISPFLOWMAPPING_ENTITY_NAME);
54
55     private volatile String bindingAddress;
56     private boolean mapRegisterCacheEnabled;
57     private long mapRegisterCacheTimeout;
58
59     private static Object startLock = new Object();
60     private final ClusterSingletonServiceProvider clusterSingletonService;
61     private LispSouthboundHandler lispSouthboundHandler;
62     private LispXtrSouthboundHandler lispXtrSouthboundHandler;
63     private NotificationPublishService notificationPublishService;
64     private NioDatagramChannel channel;
65     private volatile int xtrPort = LispMessage.XTR_PORT_NUM;
66     private volatile boolean listenOnXtrPort = false;
67     private NioDatagramChannel xtrChannel;
68     private LispSouthboundStats statistics = new LispSouthboundStats();
69     private Bootstrap bootstrap = new Bootstrap();
70     private Bootstrap xtrBootstrap = new Bootstrap();
71     private ThreadFactory threadFactory = new DefaultThreadFactory("lisp-sb");
72     private EventLoopGroup eventLoopGroup = new NioEventLoopGroup(0, threadFactory);
73     private DataBroker dataBroker;
74
75     public LispSouthboundPlugin(final DataBroker dataBroker,
76             final NotificationPublishService notificationPublishService,
77             final ClusterSingletonServiceProvider clusterSingletonService) {
78         this.dataBroker = dataBroker;
79         this.notificationPublishService = notificationPublishService;
80         this.clusterSingletonService = clusterSingletonService;
81         this.clusterSingletonService.registerClusterSingletonService(this);
82     }
83
84     public void init() {
85         LOG.info("LISP (RFC6830) Southbound Plugin is initializing...");
86         synchronized (startLock) {
87             lispSouthboundHandler = new LispSouthboundHandler(this);
88             lispSouthboundHandler.setDataBroker(dataBroker);
89             lispSouthboundHandler.setNotificationProvider(this.notificationPublishService);
90             lispSouthboundHandler.setMapRegisterCacheEnabled(mapRegisterCacheEnabled);
91             lispSouthboundHandler.setMapRegisterCacheTimeout(mapRegisterCacheTimeout);
92             lispSouthboundHandler.init();
93             lispSouthboundHandler.restoreDaoFromDatastore();
94
95             lispXtrSouthboundHandler = new LispXtrSouthboundHandler();
96             lispXtrSouthboundHandler.setNotificationProvider(this.notificationPublishService);
97
98             bootstrap.group(eventLoopGroup);
99             bootstrap.channel(NioDatagramChannel.class);
100             bootstrap.handler(lispSouthboundHandler);
101
102             xtrBootstrap.group(eventLoopGroup);
103             xtrBootstrap.channel(NioDatagramChannel.class);
104             xtrBootstrap.handler(lispXtrSouthboundHandler);
105
106             start();
107             startXtr();
108
109             LOG.info("LISP (RFC6830) Southbound Plugin is up!");
110         }
111     }
112
113     @SuppressWarnings("checkstyle:IllegalCatch")
114     private void start() {
115         try {
116             channel = (NioDatagramChannel) bootstrap.bind(bindingAddress, LispMessage.PORT_NUM).sync().channel();
117             LOG.debug("Binding LISP UDP listening socket to {}:{}", bindingAddress, LispMessage.PORT_NUM);
118         } catch (Exception e) {
119             LOG.error("Failed to open main socket ", e);
120         }
121     }
122
123     @SuppressWarnings("checkstyle:IllegalCatch")
124     private void startXtr() {
125         if (listenOnXtrPort) {
126             try {
127                 xtrChannel = (NioDatagramChannel) xtrBootstrap.bind(bindingAddress, xtrPort).sync().channel();
128                 LOG.debug("Binding LISP xTR UDP listening socket to {}:{}", bindingAddress, xtrPort);
129             } catch (Exception e) {
130                 LOG.error("Failed to open xTR socket ", e);
131             }
132         }
133     }
134
135     @SuppressWarnings("checkstyle:IllegalCatch")
136     private void stop() {
137         try {
138             channel.close().sync();
139             channel = null;
140         } catch (Exception e) {
141             LOG.error("Failed to close main socket ", e);
142         }
143     }
144
145     @SuppressWarnings("checkstyle:IllegalCatch")
146     private void stopXtr() {
147         if (listenOnXtrPort) {
148             try {
149                 xtrChannel.close().sync();
150                 xtrChannel = null;
151             } catch (Exception e) {
152                 LOG.error("Failed to close xTR socket ", e);
153             }
154         }
155     }
156
157     private void restart() {
158         LOG.info("Reloading");
159         stop();
160         start();
161     }
162
163     private void restartXtr() {
164         LOG.info("Reloading xTR");
165         stopXtr();
166         startXtr();
167     }
168
169     private void unloadActions() {
170         lispSouthboundHandler = null;
171         lispXtrSouthboundHandler = null;
172
173         stop();
174         stopXtr();
175
176         LOG.info("LISP (RFC6830) Southbound Plugin is down!");
177     }
178
179     public void handleSerializedLispBuffer(TransportAddress address, ByteBuffer outBuffer,
180                                            final MessageType packetType) {
181         InetAddress ip = getInetAddress(address);
182         handleSerializedLispBuffer(ip, outBuffer, packetType, address.getPort().getValue());
183     }
184
185     public void handleSerializedLispBuffer(InetAddress address, ByteBuffer outBuffer,
186             final MessageType packetType, final int portNumber) {
187         InetSocketAddress recipient = new InetSocketAddress(address, portNumber);
188         outBuffer.position(0);
189         ByteBuf data = wrappedBuffer(outBuffer);
190         DatagramPacket packet = new DatagramPacket(data, recipient);
191         LOG.debug("Sending {} on port {} to address: {}", packetType, portNumber, address);
192         if (LOG.isTraceEnabled()) {
193             LOG.trace("Buffer:\n{}", ByteBufUtil.prettyHexDump(data));
194         }
195         channel.write(packet).addListener(new ChannelFutureListener() {
196             @Override
197             public void operationComplete(ChannelFuture future) {
198                 if (future.isSuccess()) {
199                     LOG.trace("Success");
200                     statistics.incrementTx(packetType.getIntValue());
201                 } else {
202                     LOG.warn("Failed to send packet");
203                     statistics.incrementTxErrors();
204                 }
205             }
206         });
207         channel.flush();
208     }
209
210     private InetAddress getInetAddress(TransportAddress address) {
211         Preconditions.checkNotNull(address, "TransportAddress must not be null");
212         IpAddressBinary ip = address.getIpAddress();
213         try {
214             if (ip.getIpv4AddressBinary() != null) {
215                 return InetAddress.getByAddress(ip.getIpv4AddressBinary().getValue());
216             } else if (ip.getIpv6AddressBinary() != null) {
217                 return InetAddress.getByAddress(ip.getIpv6AddressBinary().getValue());
218             }
219         } catch (UnknownHostException e) {
220             LOG.debug("Could not convert TransportAddress {} to InetAddress", address, e);
221         }
222         return null;
223     }
224
225     public LispSouthboundStats getStats() {
226         return statistics;
227     }
228
229     @Override
230     @SuppressWarnings("checkstyle:IllegalCatch")
231     public void setLispAddress(String address) {
232         synchronized (startLock) {
233             if (bindingAddress.equals(address)) {
234                 LOG.debug("Configured LISP binding address didn't change.");
235             } else {
236                 LOG.debug("Setting LISP binding address to {}", address);
237                 bindingAddress = address;
238                 if (channel != null) {
239                     try {
240                         restart();
241                         restartXtr();
242                     } catch (Exception e) {
243                         LOG.error("Failed to set LISP binding address: ", e);
244                     }
245                 }
246             }
247         }
248     }
249
250     @Override
251     public void shouldListenOnXtrPort(boolean shouldListenOnXtrPort) {
252         listenOnXtrPort = shouldListenOnXtrPort;
253         if (listenOnXtrPort) {
254             restartXtr();
255         } else {
256             LOG.info("Shutting down xTR");
257             stopXtr();
258         }
259     }
260
261     @Override
262     public void setXtrPort(int port) {
263         this.xtrPort = port;
264         if (listenOnXtrPort) {
265             restartXtr();
266         }
267     }
268
269     public void setMapRegisterCacheEnabled(final boolean mapRegisterCacheEnabled) {
270         this.mapRegisterCacheEnabled = mapRegisterCacheEnabled;
271         if (mapRegisterCacheEnabled) {
272             LOG.info("Enabling Map-Register cache");
273         } else {
274             LOG.info("Disabling Map-Register cache");
275         }
276     }
277
278     public void setMapRegisterCacheTimeout(long mapRegisterCacheTimeout) {
279         this.mapRegisterCacheTimeout = mapRegisterCacheTimeout;
280     }
281
282     public void setBindingAddress(String bindingAddress) {
283         this.bindingAddress = bindingAddress;
284     }
285
286     @Override
287     public void close() throws Exception {
288         eventLoopGroup.shutdownGracefully();
289         lispSouthboundHandler.close();
290         unloadActions();
291         clusterSingletonService.close();
292     }
293
294     @Override
295     public void instantiateServiceInstance() {
296         if (lispSouthboundHandler != null) {
297             lispSouthboundHandler.setNotificationProvider(notificationPublishService);
298             lispSouthboundHandler.restoreDaoFromDatastore();
299             lispSouthboundHandler.setIsMaster(true);
300         }
301         if (lispXtrSouthboundHandler != null) {
302             lispXtrSouthboundHandler.setNotificationProvider(notificationPublishService);
303         }
304     }
305
306     @Override
307     public ListenableFuture<Void> closeServiceInstance() {
308         if (lispSouthboundHandler != null) {
309             lispSouthboundHandler.setNotificationProvider(null);
310             lispSouthboundHandler.setIsMaster(false);
311         }
312         if (lispXtrSouthboundHandler != null) {
313             lispXtrSouthboundHandler.setNotificationProvider(null);
314         }
315         return Futures.<Void>immediateFuture(null);
316     }
317
318     @Override
319     public ServiceGroupIdentifier getIdentifier() {
320         return SERVICE_GROUP_IDENTIFIER;
321     }
322
323 }