Clustering - adding to LispSouthboundPlugin.
[lispflowmapping.git] / mappingservice / southbound / src / main / java / org / opendaylight / lispflowmapping / southbound / lisp / LispSouthboundHandler.java
index af92027a9c57d75611b0c41055267055382cb9d4..2b4cef6af38fd0d26f9b5047fd585575544ca3c7 100644 (file)
@@ -9,11 +9,13 @@
 package org.opendaylight.lispflowmapping.southbound.lisp;
 
 import com.google.common.base.Preconditions;
+
 import io.netty.buffer.ByteBufUtil;
 import io.netty.channel.ChannelHandler;
 import io.netty.channel.ChannelHandlerContext;
 import io.netty.channel.SimpleChannelInboundHandler;
 import io.netty.channel.socket.DatagramPacket;
+
 import java.net.InetAddress;
 import java.nio.ByteBuffer;
 import java.util.ArrayList;
@@ -21,12 +23,13 @@ import java.util.Arrays;
 import java.util.List;
 import java.util.Map;
 import java.util.Objects;
+
 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
 import org.opendaylight.controller.md.sal.binding.api.NotificationPublishService;
 import org.opendaylight.lispflowmapping.dsbackend.DataStoreBackEnd;
 import org.opendaylight.lispflowmapping.inmemorydb.HashMapDb;
-import org.opendaylight.lispflowmapping.southbound.authentication.LispAuthenticationUtil;
-import org.opendaylight.lispflowmapping.interfaces.lisp.ILispAuthentication;
+import org.opendaylight.lispflowmapping.lisp.authentication.ILispAuthentication;
+import org.opendaylight.lispflowmapping.lisp.authentication.LispAuthenticationUtil;
 import org.opendaylight.lispflowmapping.lisp.serializer.MapNotifySerializer;
 import org.opendaylight.lispflowmapping.lisp.serializer.MapRegisterSerializer;
 import org.opendaylight.lispflowmapping.lisp.serializer.MapReplySerializer;
@@ -43,7 +46,7 @@ import org.opendaylight.lispflowmapping.southbound.lisp.cache.MapRegisterPartial
 import org.opendaylight.lispflowmapping.southbound.lisp.exception.LispMalformedPacketException;
 import org.opendaylight.lispflowmapping.southbound.lisp.network.PacketHeader;
 import org.opendaylight.lispflowmapping.southbound.util.LispNotificationHelper;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.PortNumber;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.AddMappingBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.GotMapNotifyBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.GotMapReplyBuilder;
@@ -67,7 +70,7 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.ma
 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.record.list.MappingRecordItem;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.transport.address.TransportAddressBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.mappingservice.rev150906.db.instance.AuthenticationKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.mappingservice.rev150906.mapping.authkey.container.MappingAuthkey;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.authkey.container.MappingAuthkey;
 import org.opendaylight.yangtools.yang.binding.Notification;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -97,6 +100,7 @@ public class LispSouthboundHandler extends SimpleChannelInboundHandler<DatagramP
     private SimpleMapCache smc;
     private AuthenticationKeyDataListener authenticationKeyDataListener;
     private DataStoreBackEnd dsbe;
+    private boolean isReadFromChannelEnabled = true;
 
     public LispSouthboundHandler(LispSouthboundPlugin lispSbPlugin) {
         this.lispSbPlugin = lispSbPlugin;
@@ -203,18 +207,21 @@ public class LispSouthboundHandler extends SimpleChannelInboundHandler<DatagramP
                 cacheValue = resolveCacheValue(artificialEntry);
             }
             if (cacheValue != null) {
-                final MapRegisterCacheMetadata mapRegisterValue = cacheValue.getMapRegisterCacheMetadata();
-                LOG.debug("Map register message site-ID: {} xTR-ID: {} from cache.", mapRegisterValue.getSiteId(),
-                        mapRegisterValue.getXtrId());
-                mapRegisterCache.refreshEntry(cacheKey);
-                sendNotificationIfPossible(createMappingKeepAlive(cacheValue));
-                if (mapRegisterValue.isWantMapNotify()) {
-                    sendMapNotifyMsg(inBuffer, sourceAddress, port, mapRegisterValue.getEidLispAddress());
+                MapRegisterCacheMetadata mapRegisterMeta = cacheValue.getMapRegisterCacheMetadata();
+                LOG.debug("Map register message site-ID: {} xTR-ID: {} from cache.", mapRegisterMeta.getSiteId(),
+                        mapRegisterMeta.getXtrId());
+                cacheValue = refreshEntry(cacheKey);
+                if (cacheValue != null) {
+                    sendNotificationIfPossible(createMappingKeepAlive(cacheValue));
+                    if (cacheValue.getMapRegisterCacheMetadata().isWantMapNotify()) {
+                        sendMapNotifyMsg(inBuffer, sourceAddress, port, cacheValue);
+                    }
                 }
                 lispSbStats.incrementCacheHits();
             } else {
                 MapRegister mapRegister = MapRegisterSerializer.getInstance().deserialize(inBuffer, sourceAddress);
-                if (isAuthenticationSuccessful(mapRegister, inBuffer)) {
+                final MappingAuthkey mappingAuthkey = tryToAuthenticateMessage(mapRegister, inBuffer);
+                if (mappingAuthkey != null) {
                     AddMappingBuilder addMappingBuilder = new AddMappingBuilder();
                     addMappingBuilder.setMapRegister(LispNotificationHelper.convertMapRegister(mapRegister));
                     TransportAddressBuilder transportAddressBuilder = new TransportAddressBuilder();
@@ -235,6 +242,7 @@ public class LispSouthboundHandler extends SimpleChannelInboundHandler<DatagramP
 
                         final MapRegisterCacheValueBuilder cacheValueBldNew = new MapRegisterCacheValueBuilder();
                         cacheValueBldNew.setPacketData(artificialEntry.getValue());
+                        cacheValueBldNew.setMappingAuthkey(mappingAuthkey);
                         cacheValueBldNew.setMapRegisterCacheMetadata(cacheMetadataBldNew.build());
 
                         mapRegisterCache.addEntry(cacheKey, cacheValueBldNew.build());
@@ -250,6 +258,41 @@ public class LispSouthboundHandler extends SimpleChannelInboundHandler<DatagramP
         }
     }
 
+    private MapRegisterCacheValue refreshEntry(final MapRegisterCacheKey cacheKey) {
+        MapRegisterCacheValue mapRegisterCacheValue = mapRegisterCache.refreshEntry(cacheKey);
+        if (mapRegisterCacheValue != null) {
+            mapRegisterCacheValue = refreshAuthKeyIfNecessary(mapRegisterCacheValue);
+            mapRegisterCache.addEntry(cacheKey, mapRegisterCacheValue);
+            return mapRegisterCacheValue;
+        }
+        return null;
+    }
+
+    private MapRegisterCacheValue refreshAuthKeyIfNecessary(MapRegisterCacheValue mapRegisterCacheValue) {
+        if (authenticationKeyDataListener.isAuthKeyRefreshing()) {
+            final boolean shouldAuthKeyRefreshingStop = System.currentTimeMillis() - authenticationKeyDataListener
+                    .getAuthKeyRefreshingDate() > CACHE_RECORD_TIMEOUT;
+            if (shouldAuthKeyRefreshingStop) {
+                authenticationKeyDataListener.setAuthKeyRefreshing(false);
+            } else {
+                final MappingAuthkey mappingAuthkey = provideAuthenticateKey(mapRegisterCacheValue
+                        .getMapRegisterCacheMetadata().getEidLispAddress());
+
+                final MapRegisterCacheValueBuilder newMapRegisterCacheValueBuilder = new MapRegisterCacheValueBuilder
+                        (mapRegisterCacheValue);
+                final MapRegisterCacheMetadataBuilder newMapRegisterCacheMetadataBuilder =
+                        new MapRegisterCacheMetadataBuilder(mapRegisterCacheValue.getMapRegisterCacheMetadata());
+
+                newMapRegisterCacheValueBuilder.setMappingAuthkey(mappingAuthkey);
+                newMapRegisterCacheValueBuilder.setMapRegisterCacheMetadata(newMapRegisterCacheMetadataBuilder.build());
+                return newMapRegisterCacheValueBuilder.build();
+            }
+        }
+
+        return mapRegisterCacheValue;
+
+    }
+
     private MapRegisterCacheValue resolveCacheValue(Map.Entry<MapRegisterCacheKey, byte[]> entry) {
         if (entry != null) {
             final MapRegisterCacheValue mapRegisterCacheValue = mapRegisterCache.getEntry(entry.getKey());
@@ -282,22 +325,10 @@ public class LispSouthboundHandler extends SimpleChannelInboundHandler<DatagramP
         return mappingKeepAliveBuilder.build();
     }
 
-    private void sendMapNotifyMsg(final ByteBuffer inBuffer, final InetAddress inetAddress, int portNumber,
-                                  List<EidLispAddress> cacheValue) {
-
-        final String authKey = provideAuthenticateKey(cacheValue);
-        if (authKey != null) {
-            ByteBuffer outBuffer = transformMapRegisterToMapNotify(inBuffer);
-            outBuffer = calculateAndSetNewMAC(outBuffer, authKey);
-            outBuffer.position(0);
-            lispSbPlugin.handleSerializedLispBuffer(inetAddress, outBuffer, MessageType.MapNotify, portNumber);
-        }
-    }
-
     /**
      * Returns null if not all of eids have the same value of authentication key
      */
-    private String provideAuthenticateKey(final List<EidLispAddress> eidLispAddresses) {
+    private MappingAuthkey provideAuthenticateKey(final List<EidLispAddress> eidLispAddresses) {
         MappingAuthkey firstAuthKey = null;
         for (int i = 0; i < eidLispAddresses.size(); i++) {
             final Eid eid = eidLispAddresses.get(i).getEid();
@@ -310,10 +341,24 @@ public class LispSouthboundHandler extends SimpleChannelInboundHandler<DatagramP
                 }
             }
         }
-        return firstAuthKey.getKeyString();
+        return firstAuthKey;
 
     }
 
+    private void sendMapNotifyMsg(final ByteBuffer inBuffer, final InetAddress inetAddress, int portNumber,
+                                  MapRegisterCacheValue mapRegisterValue) {
+        if (mapRegisterValue.getMappingAuthkey().getKeyType() != null) {
+            ByteBuffer outBuffer = transformMapRegisterToMapNotify(inBuffer);
+            if (mapRegisterValue.getMappingAuthkey().getKeyType() != 0) {
+                outBuffer = calculateAndSetNewMAC(outBuffer, mapRegisterValue.getMappingAuthkey().getKeyString());
+            }
+            outBuffer.position(0);
+            lispSbPlugin.handleSerializedLispBuffer(inetAddress, outBuffer, MessageType.MapNotify, portNumber);
+        } else {
+            LOG.error("Map-Register Cache: authentication succeeded, but can't find auth key for sending Map-Notify");
+        }
+    }
+
     /**
      * Calculates new message authentication code (MAC) for notify message.
      *
@@ -364,16 +409,16 @@ public class LispSouthboundHandler extends SimpleChannelInboundHandler<DatagramP
      *
      * @param mapRegister
      * @param byteBuffer
-     * @return
+     * @return Returns authentication key if all of EIDs have the same authentication key or null otherwise
      */
-    private boolean isAuthenticationSuccessful(final MapRegister mapRegister, final ByteBuffer byteBuffer) {
+    private MappingAuthkey tryToAuthenticateMessage(final MapRegister mapRegister, final ByteBuffer byteBuffer) {
         if (!authenticationEnabled) {
-            return true;
+            return null;
         }
 
         if (smc == null) {
             LOG.debug("Simple map cache wasn't instantieted and set.");
-            return false;
+            return null;
         }
 
         MappingAuthkey firstAuthKey = null;
@@ -384,7 +429,7 @@ public class LispSouthboundHandler extends SimpleChannelInboundHandler<DatagramP
             if (i == 0) {
                 firstAuthKey = smc.getAuthenticationKey(mappingRecord.getEid());
                 if (!LispAuthenticationUtil.validate(mapRegister, byteBuffer, mappingRecord.getEid(), firstAuthKey)) {
-                    return false;
+                    return null;
                 }
             } else {
                 final Eid eid = mappingRecord.getEid();
@@ -392,11 +437,11 @@ public class LispSouthboundHandler extends SimpleChannelInboundHandler<DatagramP
                 if (!firstAuthKey.equals(authKey)) {
                     LOG.debug("Map register packet contained several eids. Authentication keys for first one and for " +
                             "{} are different.",LispAddressStringifier.getString(eid));
-                    return false;
+                    return null;
                 }
             }
         }
-        return true;
+        return firstAuthKey;
     }
 
     private void handleMapNotify(ByteBuffer inBuffer, InetAddress sourceAddress, int port) {
@@ -460,11 +505,13 @@ public class LispSouthboundHandler extends SimpleChannelInboundHandler<DatagramP
 
     @Override
     protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
-        if (LOG.isTraceEnabled()) {
-            LOG.trace("Received UDP packet from {}:{} with content:\n{}", msg.sender().getHostString(),
-                    msg.sender().getPort(), ByteBufUtil.prettyHexDump(msg.content()));
+        if (isReadFromChannelEnabled) {
+            if (LOG.isTraceEnabled()) {
+                LOG.trace("Received UDP packet from {}:{} with content:\n{}", msg.sender().getHostString(),
+                        msg.sender().getPort(), ByteBufUtil.prettyHexDump(msg.content()));
+            }
+            handlePacket(msg);
         }
-        handlePacket(msg);
     }
 
     @Override
@@ -525,4 +572,8 @@ public class LispSouthboundHandler extends SimpleChannelInboundHandler<DatagramP
         this.authenticationKeyDataListener = new AuthenticationKeyDataListener(dataBroker, smc);
         dsbe = new DataStoreBackEnd(dataBroker);
     }
+
+    public void setIsReadFromChannelEnabled(boolean isReadFromChannelEnabled) {
+        this.isReadFromChannelEnabled = isReadFromChannelEnabled;
+    }
 }