Clustering - adding to LispSouthboundPlugin.
[lispflowmapping.git] / mappingservice / southbound / src / main / java / org / opendaylight / lispflowmapping / southbound / LispSouthboundPlugin.java
index 0cbee80ba1e33adf46a3f5942e13d40abbd8ff76..4557bb387cc097e9fa0d289b52ce342bff57ce23 100644 (file)
 
 package org.opendaylight.lispflowmapping.southbound;
 
-import java.io.IOException;
-import java.net.DatagramPacket;
-import java.net.DatagramSocket;
+import static io.netty.buffer.Unpooled.wrappedBuffer;
+
+import com.google.common.base.Preconditions;
+
+import io.netty.bootstrap.Bootstrap;
+import io.netty.buffer.ByteBuf;
+import io.netty.buffer.ByteBufUtil;
+import io.netty.channel.ChannelFuture;
+import io.netty.channel.ChannelFutureListener;
+import io.netty.channel.EventLoopGroup;
+import io.netty.channel.nio.NioEventLoopGroup;
+import io.netty.channel.socket.DatagramPacket;
+import io.netty.channel.socket.nio.NioDatagramChannel;
+import io.netty.util.concurrent.DefaultThreadFactory;
+
 import java.net.InetAddress;
 import java.net.InetSocketAddress;
-import java.net.SocketException;
-import java.net.SocketTimeoutException;
+import java.net.UnknownHostException;
 import java.nio.ByteBuffer;
-
-import org.apache.commons.lang3.exception.ExceptionUtils;
-import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
-import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.ProviderContext;
-import org.opendaylight.controller.sal.binding.api.BindingAwareProvider;
-import org.opendaylight.controller.sal.binding.api.NotificationProviderService;
-import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
-import org.opendaylight.lispflowmapping.implementation.serializer.LispMessage;
-import org.opendaylight.lispflowmapping.southbound.lisp.ILispSouthboundService;
-import org.opendaylight.lispflowmapping.southbound.lisp.LispSouthboundService;
-import org.opendaylight.lispflowmapping.southbound.lisp.LispXtrSouthboundService;
+import java.util.concurrent.ThreadFactory;
+
+import org.opendaylight.controller.md.sal.binding.api.DataBroker;
+import org.opendaylight.controller.md.sal.binding.api.NotificationPublishService;
+import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipService;
+import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.RpcRegistration;
+import org.opendaylight.lispflowmapping.clustering.ClusterNodeModulSwitcherImpl;
+import org.opendaylight.lispflowmapping.clustering.api.ClusterNodeModuleSwitcher;
+import org.opendaylight.lispflowmapping.lisp.type.LispMessage;
+import org.opendaylight.lispflowmapping.southbound.lisp.LispSouthboundHandler;
+import org.opendaylight.lispflowmapping.southbound.lisp.LispXtrSouthboundHandler;
 import org.opendaylight.lispflowmapping.type.sbplugin.IConfigLispSouthboundPlugin;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.LfmControlPlaneService;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.transportaddress.TransportAddress;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.inet.binary.types.rev160303.IpAddressBinary;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MessageType;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.transport.address.TransportAddress;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.sb.rev150904.OdlLispSbService;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.lisp.sb.config.rev150517.LispSbConfig;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import com.google.common.net.InetAddresses;
-
-public class LispSouthboundPlugin implements IConfigLispSouthboundPlugin, AutoCloseable, BindingAwareProvider {
+public class LispSouthboundPlugin implements IConfigLispSouthboundPlugin, AutoCloseable, ClusterNodeModuleSwitcher {
     protected static final Logger LOG = LoggerFactory.getLogger(LispSouthboundPlugin.class);
 
     private static Object startLock = new Object();
-    private LispIoThread lispThread;
-    private LispIoThread xtrThread;
-    private LispSouthboundService lispSouthboundService;
-    private LispXtrSouthboundService lispXtrSouthboundService;
-    private NotificationProviderService notificationService;
-    private RpcProviderRegistry rpcRegistry;
-    private BindingAwareBroker broker;
-    private volatile DatagramSocket socket = null;
-    private volatile String bindingAddress = null;
+    private final ClusterNodeModulSwitcherImpl clusterNodeModulSwitcher;
+    private LispSouthboundHandler lispSouthboundHandler;
+    private LispXtrSouthboundHandler lispXtrSouthboundHandler;
+    private NotificationPublishService notificationPublishService;
+    private NioDatagramChannel channel;
+    private volatile String bindingAddress = "0.0.0.0";
     private volatile int xtrPort = LispMessage.XTR_PORT_NUM;
     private volatile boolean listenOnXtrPort = false;
-    private BindingAwareBroker.RpcRegistration<LfmControlPlaneService> controlPlaneRpc;
-    private DatagramSocket xtrSocket;
+    private boolean mapRegisterCacheEnabled = true;
+    private RpcRegistration<OdlLispSbService> sbRpcRegistration;
+    private NioDatagramChannel xtrChannel;
+    private LispSouthboundStats statistics = new LispSouthboundStats();
+    private Bootstrap bootstrap = new Bootstrap();
+    private Bootstrap xtrBootstrap = new Bootstrap();
+    private ThreadFactory threadFactory = new DefaultThreadFactory("lisp-sb");
+    private EventLoopGroup eventLoopGroup = new NioEventLoopGroup(0, threadFactory);
+    private DataBroker dataBroker;
+
+    public LispSouthboundPlugin(final DataBroker dataBroker,
+            final NotificationPublishService notificationPublishService,
+            final LispSbConfig lispSbConfig, final EntityOwnershipService entityOwnershipService) {
+        this.dataBroker = dataBroker;
+        this.notificationPublishService = notificationPublishService;
+        this.bindingAddress = lispSbConfig.getBindAddress();
+        this.mapRegisterCacheEnabled = lispSbConfig.isMapRegisterCache();
+        clusterNodeModulSwitcher = new ClusterNodeModulSwitcherImpl(entityOwnershipService);
+        clusterNodeModulSwitcher.setModule(this);
+    }
 
     public void init() {
-        LOG.info("LISP (RFC6830) Mapping Service is up!");
-        final LfmControlPlaneRpc lfmCpRpc = new LfmControlPlaneRpc(this);
+        LOG.info("LISP (RFC6830) Southbound Plugin is initializing...");
+        synchronized (startLock) {
+            lispSouthboundHandler = new LispSouthboundHandler(this);
+            lispSouthboundHandler.setDataBroker(dataBroker);
+            lispSouthboundHandler.setNotificationProvider(this.notificationPublishService);
+            lispSouthboundHandler.setMapRegisterCacheEnabled(mapRegisterCacheEnabled);
+            lispSouthboundHandler.init();
+            lispSouthboundHandler.restoreDaoFromDatastore();
 
-        controlPlaneRpc = rpcRegistry.addRpcImplementation(LfmControlPlaneService.class, lfmCpRpc);
-        broker.registerProvider(this);
+            lispXtrSouthboundHandler = new LispXtrSouthboundHandler();
+            lispXtrSouthboundHandler.setNotificationProvider(this.notificationPublishService);
 
-        synchronized (startLock) {
-            lispSouthboundService = new LispSouthboundService();
-            lispXtrSouthboundService = new LispXtrSouthboundService();
-            lispSouthboundService.setNotificationProvider(this.notificationService);
-            lispXtrSouthboundService.setNotificationProvider(this.notificationService);
-            LOG.trace("Provider Session initialized");
-            if (bindingAddress == null) {
-                setLispAddress("0.0.0.0");
-            }
-            LOG.info("LISP (RFC6830) Mapping Service is up!");
-        }
-    }
+            bootstrap.group(eventLoopGroup);
+            bootstrap.channel(NioDatagramChannel.class);
+            bootstrap.handler(lispSouthboundHandler);
 
-    public void setNotificationProviderService(NotificationProviderService notificationService) {
-        this.notificationService = notificationService;
-    }
+            xtrBootstrap.group(eventLoopGroup);
+            xtrBootstrap.channel(NioDatagramChannel.class);
+            xtrBootstrap.handler(lispXtrSouthboundHandler);
 
-    public void setRpcRegistryDependency(RpcProviderRegistry rpcRegistry) {
-        this.rpcRegistry = rpcRegistry;
-    }
+            start();
+            startXtr();
 
-    public void setBindingAwareBroker(BindingAwareBroker broker) {
-        this.broker = broker;
+            LOG.info("LISP (RFC6830) Southbound Plugin is up!");
+        }
+        clusterNodeModulSwitcher.switchModuleByEntityOwnership();
     }
 
-    private void unloadActions() {
-        if (lispThread != null) {
-            lispThread.stopRunning();
-        }
-        lispSouthboundService = null;
-        lispXtrSouthboundService = null;
-        lispThread = null;
-        xtrThread = null;
-        bindingAddress = null;
-        LOG.info("LISP (RFC6830) Mapping Service is down!");
+    private void start() {
         try {
-            Thread.sleep(1100);
-        } catch (InterruptedException e) {
+            channel = (NioDatagramChannel) bootstrap.bind(bindingAddress, LispMessage.PORT_NUM).sync().channel();
+            LOG.debug("Binding LISP UDP listening socket to {}:{}", bindingAddress, LispMessage.PORT_NUM);
+        } catch (Exception e) {
+            LOG.error("Failed to open main socket ", e);
         }
     }
 
-    private class LispIoThread extends Thread {
-        private volatile boolean shouldRun;
-        private volatile DatagramSocket threadSocket = null;
-        private volatile ILispSouthboundService service;
-        private volatile boolean running;
-
-        public LispIoThread(DatagramSocket socket, ILispSouthboundService service) {
-            super("Lisp Thread");
-            this.threadSocket = socket;
-            this.service = service;
-            shouldRun = true;
-        }
-
-        @Override
-        public void run() {
-            running = true;
-
-            int lispReceiveTimeout = 1000;
-
-            LOG.info("LISP (RFC6830) Mapping Service is running and listening on address: " + bindingAddress
-                    + " port: " + threadSocket.getLocalPort());
+    private void startXtr() {
+        if (listenOnXtrPort) {
             try {
-
-                threadSocket.setSoTimeout(lispReceiveTimeout);
-            } catch (SocketException e) {
-                LOG.error("Cannot open socket on UDP port " + threadSocket.getLocalPort(), e);
-                return;
+                xtrChannel = (NioDatagramChannel) xtrBootstrap.bind(bindingAddress, xtrPort).sync().channel();
+                LOG.debug("Binding LISP xTR UDP listening socket to {}:{}", bindingAddress, xtrPort);
+            } catch (Exception e) {
+                LOG.error("Failed to open xTR socket ", e);
             }
+        }
+    }
 
-            while (shouldRun) {
-                byte[] buffer = new byte[4096];
-                DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
-                try {
-                    threadSocket.receive(packet);
-                    LOG.trace("Received a packet!");
-                } catch (SocketTimeoutException ste) {
-                    continue;
-                } catch (IOException e) {
-                    LOG.warn("IO Exception while trying to recieve packet", e);
-                }
-                LOG.trace(String.format("Handling packet from {%s}:{%d} (len={%d})", packet.getAddress()
-                        .getHostAddress(), packet.getPort(), packet.getLength()));
+    private void stop() {
+        try {
+            channel.close().sync();
+            channel = null;
+        } catch (Exception e) {
+            LOG.error("Failed to close main socket ", e);
+        }
+    }
 
-                try {
-                    this.service.handlePacket(packet);
-                } catch (Exception e) {
-                    LOG.warn("Error while handling packet", e);
-                }
+    private void stopXtr() {
+        if (listenOnXtrPort) {
+            try {
+                xtrChannel.close().sync();
+                xtrChannel = null;
+            } catch (Exception e) {
+                LOG.error("Failed to close xTR socket ", e);
             }
-
-            threadSocket.close();
-            LOG.trace("Socket closed");
-            running = false;
         }
+    }
 
-        public void stopRunning() {
-            shouldRun = false;
-        }
+    private void restart() {
+        LOG.info("Reloading");
+        stop();
+        start();
+    }
 
-        public boolean isRunning() {
-            return running;
-        }
+    private void restartXtr() {
+        LOG.info("Reloading xTR");
+        stopXtr();
+        startXtr();
     }
 
-    public static String intToIpv4(int address) {
-        return ((address >> 24) & 0xff) + "." + //
-                ((address >> 16) & 0xff) + "." + //
-                ((address >> 8) & 0xff) + "." + //
-                ((address >> 0) & 0xff);
+    private void unloadActions() {
+        lispSouthboundHandler = null;
+        lispXtrSouthboundHandler = null;
+
+        stop();
+        stopXtr();
+
+        LOG.info("LISP (RFC6830) Southbound Plugin is down!");
     }
 
-    public String getHelp() {
-        StringBuffer help = new StringBuffer();
-        help.append("---LISP Southbound Plugin---\n");
-        return help.toString();
+    public void handleSerializedLispBuffer(TransportAddress address, ByteBuffer outBuffer,
+            final MessageType packetType) {
+        InetAddress ip = getInetAddress(address);
+        handleSerializedLispBuffer(ip, outBuffer, packetType, address.getPort().getValue());
     }
 
-    private void startIOThread() {
-        if (socket != null) {
-            while (!socket.isClosed()) {
-                try {
-                    Thread.sleep(500);
-                } catch (InterruptedException e) {
-                }
-            }
+    public void handleSerializedLispBuffer(InetAddress address, ByteBuffer outBuffer,
+            final MessageType packetType, final int portNumber) {
+        InetSocketAddress recipient = new InetSocketAddress(address, portNumber);
+        outBuffer.position(0);
+        ByteBuf data = wrappedBuffer(outBuffer);
+        DatagramPacket packet = new DatagramPacket(data, recipient);
+        LOG.debug("Sending {} on port {} to address: {}", packetType, portNumber, address);
+        if (LOG.isTraceEnabled()) {
+            LOG.trace("Buffer:\n{}", ByteBufUtil.prettyHexDump(data));
         }
-        try {
-            socket = new DatagramSocket(new InetSocketAddress(bindingAddress, LispMessage.PORT_NUM));
-            lispThread = new LispIoThread(socket, lispSouthboundService);
-            lispThread.start();
-            LOG.info("LISP (RFC6830) Mapping Service Southbound Plugin is up!");
-            if (listenOnXtrPort) {
-                restartXtrThread();
+        channel.write(packet).addListener(new ChannelFutureListener() {
+            @Override
+            public void operationComplete(ChannelFuture future) {
+                if (future.isSuccess()) {
+                    LOG.trace("Success");
+                    statistics.incrementTx(packetType.getIntValue());
+                } else {
+                    LOG.warn("Failed to send packet");
+                    statistics.incrementTxErrors();
+                }
             }
-        } catch (SocketException e) {
-            LOG.error("couldn't start socket: {}", ExceptionUtils.getStackTrace(e));
-        }
+        });
+        channel.flush();
     }
 
-    private void restartXtrThread() {
+    private InetAddress getInetAddress(TransportAddress address) {
+        Preconditions.checkNotNull(address, "TransportAddress must not be null");
+        IpAddressBinary ip = address.getIpAddress();
         try {
-            stopXtrThread();
-            xtrSocket = new DatagramSocket(new InetSocketAddress(bindingAddress, xtrPort));
-            xtrThread = new LispIoThread(xtrSocket, lispXtrSouthboundService);
-            xtrThread.start();
-            LOG.info("xTR Southbound Plugin is up!");
-        } catch (SocketException e) {
-            LOG.warn("failed to start xtr thread: {}", ExceptionUtils.getStackTrace(e));
+            if (ip.getIpv4AddressBinary() != null) {
+                return InetAddress.getByAddress(ip.getIpv4AddressBinary().getValue());
+            } else if (ip.getIpv6AddressBinary() != null) {
+                return InetAddress.getByAddress(ip.getIpv6AddressBinary().getValue());
+            }
+        } catch (UnknownHostException e) {
+            LOG.debug("Could not convert TransportAddress {} to InetAddress", address, e);
         }
+        return null;
     }
 
-    public void handleSerializedLispBuffer(TransportAddress address, ByteBuffer outBuffer, String packetType) {
-        DatagramPacket packet = new DatagramPacket(outBuffer.array(), outBuffer.limit());
-        packet.setPort(address.getPort().getValue());
-        InetAddress ip = InetAddresses.forString(new String(address.getIpAddress().getValue()));
-        packet.setAddress(ip);
-        try {
-            if (LOG.isDebugEnabled()) {
-                LOG.trace("Sending " + packetType + " on port " + address.getPort().getValue() + " to address: " + ip);
-            }
-            socket.send(packet);
-        } catch (IOException e) {
-            LOG.warn("Failed to send " + packetType, e);
-        }
+    public LispSouthboundStats getStats() {
+        return statistics;
     }
 
+    @Override
     public void setLispAddress(String address) {
         synchronized (startLock) {
-            if (bindingAddress != null && bindingAddress.equals(address)) {
-                LOG.trace("configured lisp binding address didn't change.");
+            if (bindingAddress.equals(address)) {
+                LOG.debug("Configured LISP binding address didn't change.");
             } else {
-                String action = (bindingAddress == null ? "Setting" : "Resetting");
-                LOG.trace(action + " lisp binding address to: " + address);
+                LOG.debug("Setting LISP binding address to {}", address);
                 bindingAddress = address;
-                if (lispThread != null) {
-                    lispThread.stopRunning();
-                    while (lispThread.isRunning()) {
-                        try {
-                            Thread.sleep(500);
-                        } catch (InterruptedException e) {
-                        }
+                if (channel != null) {
+                    try {
+                        restart();
+                        restartXtr();
+                    } catch (Exception e) {
+                        LOG.error("Failed to set LISP binding address: ", e);
                     }
                 }
-                stopXtrThread();
-                startIOThread();
-            }
-        }
-    }
-
-    private void stopXtrThread() {
-        if (xtrThread != null) {
-            xtrThread.stopRunning();
-            while (xtrThread.isRunning()) {
-                try {
-                    Thread.sleep(500);
-                } catch (InterruptedException e) {
-                }
             }
         }
     }
@@ -266,11 +245,10 @@ public class LispSouthboundPlugin implements IConfigLispSouthboundPlugin, AutoCl
     public void shouldListenOnXtrPort(boolean shouldListenOnXtrPort) {
         listenOnXtrPort = shouldListenOnXtrPort;
         if (listenOnXtrPort) {
-            LOG.debug("restarting xtr thread");
-            restartXtrThread();
+            restartXtr();
         } else {
-            LOG.debug("terminating thread");
-            stopXtrThread();
+            LOG.info("Shutting down xTR");
+            stopXtr();
         }
     }
 
@@ -278,18 +256,47 @@ public class LispSouthboundPlugin implements IConfigLispSouthboundPlugin, AutoCl
     public void setXtrPort(int port) {
         this.xtrPort = port;
         if (listenOnXtrPort) {
-            restartXtrThread();
+            restartXtr();
+        }
+    }
+
+    public void setMapRegisterCacheEnabled(final boolean mapRegisterCacheEnabled) {
+        this.mapRegisterCacheEnabled = mapRegisterCacheEnabled;
+        if (mapRegisterCacheEnabled) {
+            LOG.info("Enabling Map-Register cache");
+        } else {
+            LOG.info("Disabling Map-Register cache");
         }
     }
 
     @Override
     public void close() throws Exception {
+        eventLoopGroup.shutdownGracefully();
+        sbRpcRegistration.close();
+        lispSouthboundHandler.close();
         unloadActions();
-        controlPlaneRpc.close();
     }
 
     @Override
-    public void onSessionInitiated(ProviderContext session) {
-        LOG.debug("LispSouthboundPlugin Provider Session Initiated");
+    public void stopModule() {
+        if (lispSouthboundHandler != null) {
+            lispSouthboundHandler.setNotificationProvider(null);
+            lispSouthboundHandler.setIsReadFromChannelEnabled(false);
+        }
+        if (lispXtrSouthboundHandler != null) {
+            lispXtrSouthboundHandler.setNotificationProvider(null);
+        }
+    }
+
+    @Override
+    public void startModule() {
+        if (lispSouthboundHandler != null) {
+            lispSouthboundHandler.setNotificationProvider(notificationPublishService);
+            lispSouthboundHandler.restoreDaoFromDatastore();
+            lispSouthboundHandler.setIsReadFromChannelEnabled(true);
+        }
+        if (lispXtrSouthboundHandler != null) {
+            lispXtrSouthboundHandler.setNotificationProvider(notificationPublishService);
+        }
     }
 }