Merge "Bug 6297: Change subscriber's RLOC selection algo"
[lispflowmapping.git] / mappingservice / southbound / src / main / java / org / opendaylight / lispflowmapping / southbound / lisp / LispSouthboundHandler.java
index 2d1d267d37bbbf834d085921d4d64585d7cd68a9..dba899a532b299af0db0a43e37ec82151807d430 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,11 +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;
@@ -42,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;
@@ -65,7 +69,8 @@ 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.container.MappingRecord;
 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.mapping.authkey.container.MappingAuthkey;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.mappingservice.rev150906.db.instance.AuthenticationKey;
+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;
@@ -75,25 +80,20 @@ public class LispSouthboundHandler extends SimpleChannelInboundHandler<DatagramP
         implements ILispSouthboundService, AutoCloseable {
     private MapRegisterCache mapRegisterCache;
     private boolean mapRegisterCacheEnabled = true;
+    private long mapRegisterCacheTimeout;
 
-    /**
-     * How long is record supposed to be relevant. After this time record isn't valid.
-     *
-     * If you modify this value, please update the LispSouthboundServiceTest class too.
-     */
-    private static final long CACHE_RECORD_TIMEOUT = 90000;
     private DataBroker dataBroker;
-
     private NotificationPublishService notificationPublishService;
+
     protected static final Logger LOG = LoggerFactory.getLogger(LispSouthboundHandler.class);
 
     //TODO: think whether this field can be accessed through mappingservice or some other configuration parameter
     private boolean authenticationEnabled = true;
-
     private final LispSouthboundPlugin lispSbPlugin;
     private LispSouthboundStats lispSbStats = null;
     private SimpleMapCache smc;
     private AuthenticationKeyDataListener authenticationKeyDataListener;
+    private DataStoreBackEnd dsbe;
 
     public LispSouthboundHandler(LispSouthboundPlugin lispSbPlugin) {
         this.lispSbPlugin = lispSbPlugin;
@@ -114,7 +114,7 @@ public class LispSouthboundHandler extends SimpleChannelInboundHandler<DatagramP
             handleEncapsulatedControlMessage(inBuffer, msg.sender().getAddress());
         } else if (lispType == MessageType.MapRequest) {
             LOG.trace("Received packet of type Map-Request");
-            handleMapRequest(inBuffer, msg.sender().getPort());
+            handleMapRequest(inBuffer, msg.sender().getAddress(), msg.sender().getPort());
         } else if (lispType == MessageType.MapRegister) {
             LOG.trace("Received packet of type Map-Register");
             handleMapRegister(inBuffer, msg.sender().getAddress(), msg.sender().getPort());
@@ -131,16 +131,16 @@ public class LispSouthboundHandler extends SimpleChannelInboundHandler<DatagramP
 
     private void handleEncapsulatedControlMessage(ByteBuffer inBuffer, InetAddress sourceAddress) {
         try {
-            handleMapRequest(inBuffer, extractEncapsulatedSourcePort(inBuffer));
+            handleMapRequest(inBuffer, sourceAddress, extractEncapsulatedSourcePort(inBuffer));
         } catch (RuntimeException re) {
             throw new LispMalformedPacketException("Couldn't deserialize Map-Request (len="
                     + inBuffer.capacity() + ")", re);
         }
     }
 
-    private void handleMapRequest(ByteBuffer inBuffer, int port) {
+    private void handleMapRequest(ByteBuffer inBuffer, InetAddress sourceAddress, int port) {
         try {
-            MapRequest request = MapRequestSerializer.getInstance().deserialize(inBuffer);
+            MapRequest request = MapRequestSerializer.getInstance().deserialize(inBuffer, sourceAddress);
             InetAddress finalSourceAddress = MapRequestUtil.selectItrRloc(request);
             if (finalSourceAddress == null) {
                 throw new LispMalformedPacketException("Couldn't deserialize Map-Request, no ITR Rloc found!");
@@ -200,18 +200,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();
@@ -232,6 +235,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());
@@ -247,13 +251,48 @@ 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() > mapRegisterCacheTimeout;
+            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());
             if (mapRegisterCacheValue != null) {
                 final long creationTime = mapRegisterCacheValue.getMapRegisterCacheMetadata().getTimestamp();
                 final long currentTime = System.currentTimeMillis();
-                if (currentTime - creationTime > CACHE_RECORD_TIMEOUT) {
+                if (currentTime - creationTime > mapRegisterCacheTimeout) {
                     mapRegisterCache.removeEntry(entry.getKey());
                     return null;
                 } else if (Arrays.equals(mapRegisterCacheValue.getPacketData(), entry.getValue())) {
@@ -279,22 +318,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();
@@ -307,8 +334,22 @@ 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");
+        }
     }
 
     /**
@@ -326,7 +367,14 @@ public class LispSouthboundHandler extends SimpleChannelInboundHandler<DatagramP
 
     private ByteBuffer transformMapRegisterToMapNotify(final ByteBuffer buffer) {
         buffer.position(0);
-        byte[] byteReplacement = new byte[] {0x04, 0x00, 0x00};
+        byte typeAndFlags = buffer.get(0);
+        // Shift the xTR-ID present and built for an RTR bits to their correct position
+        byte flags = (byte) ((typeAndFlags << 2) & 0x0F);
+        // Set control message type to 4 (Map-Notify)
+        byte type = 0x40;
+        // Combine the nibbles
+        typeAndFlags = (byte) (type | flags);
+        byte[] byteReplacement = new byte[] {typeAndFlags, 0x00, 0x00};
         buffer.put(byteReplacement);
 
         return buffer;
@@ -354,16 +402,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;
@@ -374,7 +422,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();
@@ -382,11 +430,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) {
@@ -492,9 +540,31 @@ public class LispSouthboundHandler extends SimpleChannelInboundHandler<DatagramP
         this.mapRegisterCacheEnabled = mapRegisterCacheEnabled;
     }
 
+    /**
+    * Restore all keys from MDSAL datastore
+    */
+   public void restoreDaoFromDatastore() {
+       final List<AuthenticationKey> authKeys = dsbe.getAllAuthenticationKeys();
+       LOG.info("Restoring {} keys from datastore into southbound DAO", authKeys.size());
+
+       for (AuthenticationKey authKey : authKeys) {
+           final Eid key = authKey.getEid();
+           final MappingAuthkey mappingAuthkey = authKey.getMappingAuthkey();
+           LOG.debug("Adding authentication key '{}' with key-ID {} for {}", mappingAuthkey.getKeyString(),
+                   mappingAuthkey.getKeyType(),
+                   LispAddressStringifier.getString(key));
+           smc.addAuthenticationKey(key, mappingAuthkey);
+       }
+    }
+
     public void init() {
         Preconditions.checkNotNull(dataBroker);
         Preconditions.checkNotNull(smc);
         this.authenticationKeyDataListener = new AuthenticationKeyDataListener(dataBroker, smc);
+        dsbe = new DataStoreBackEnd(dataBroker);
+    }
+
+    public void setMapRegisterCacheTimeout(long mapRegisterCacheTimeout) {
+        this.mapRegisterCacheTimeout = mapRegisterCacheTimeout;
     }
 }