Revert "Bug 7947: Store MappingOrigin in MappingData"
[lispflowmapping.git] / mappingservice / implementation / src / main / java / org / opendaylight / lispflowmapping / implementation / MappingSystem.java
index 314c8c514039e047d8425252d0e1dc5df97754b4..b464d50070c983fc34c2cf7d41848053bc707944 100644 (file)
@@ -8,12 +8,13 @@
 
 package org.opendaylight.lispflowmapping.implementation;
 
-import java.util.AbstractMap.SimpleImmutableEntry;
 import java.util.ArrayList;
 import java.util.Date;
 import java.util.EnumMap;
+import java.util.HashMap;
 import java.util.HashSet;
 import java.util.List;
+import java.util.Map;
 import java.util.Set;
 import org.opendaylight.controller.md.sal.binding.api.NotificationPublishService;
 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
@@ -37,6 +38,7 @@ import org.opendaylight.lispflowmapping.lisp.type.MappingData;
 import org.opendaylight.lispflowmapping.lisp.util.LispAddressStringifier;
 import org.opendaylight.lispflowmapping.lisp.util.LispAddressUtil;
 import org.opendaylight.lispflowmapping.lisp.util.MaskUtil;
+import org.opendaylight.lispflowmapping.lisp.util.SourceDestKeyHelper;
 import org.opendaylight.lispflowmapping.mapcache.AuthKeyDb;
 import org.opendaylight.lispflowmapping.mapcache.MultiTableMapCache;
 import org.opendaylight.lispflowmapping.mapcache.SimpleMapCache;
@@ -45,6 +47,7 @@ import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.addres
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.Ipv4;
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.Ipv6;
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.ServicePath;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.SourceDestKey;
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.explicit.locator.path.explicit.locator.path.Hop;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.inet.binary.types.rev160303.IpAddressBinary;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.binary.address.types.rev160504.Ipv4PrefixBinaryAfi;
@@ -60,6 +63,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.container.MappingRecordBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.rloc.container.Rloc;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.mappingservice.rev150906.MappingChange;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.mappingservice.rev150906.MappingChanged;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.mappingservice.rev150906.MappingOrigin;
 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.db.instance.Mapping;
@@ -77,8 +81,8 @@ import org.slf4j.LoggerFactory;
 public class MappingSystem implements IMappingSystem {
     private static final Logger LOG = LoggerFactory.getLogger(MappingSystem.class);
     private static final String AUTH_KEY_TABLE = "authentication";
-    private static final int TTL_RLOC_TIMED_OUT = 1;
-    private static final int TTL_NO_RLOC_KNOWN = 15;
+    //private static final int TTL_RLOC_TIMED_OUT = 1;
+    private static final int TTL_NO_RLOC_KNOWN = ConfigIni.getInstance().getNegativeMappingTTL();
     private NotificationPublishService notificationPublishService;
     private boolean mappingMerge;
     private ILispDAO dao;
@@ -169,6 +173,7 @@ public class MappingSystem implements IMappingSystem {
         tableMap.get(origin).addMapping(key, mappingData);
     }
 
+    @SuppressWarnings("unchecked")
     private void clearPresentXtrIdMappings(Eid key) {
         List<MappingData> allXtrMappingList = (List<MappingData>) (List<?>) smc.getAllXtrIdMappings(key);
 
@@ -199,6 +204,8 @@ public class MappingSystem implements IMappingSystem {
     public MappingData addNegativeMapping(Eid key) {
         MappingRecord mapping = buildNegativeMapping(key);
         MappingData mappingData = new MappingData(mapping);
+        LOG.debug("Adding negative mapping for EID {}", LispAddressStringifier.getString(key));
+        LOG.trace(mappingData.getString());
         smc.addMapping(mapping.getEid(), mappingData);
         dsbe.addMapping(DSBEInputUtil.toMapping(MappingOrigin.Southbound, mapping.getEid(), null, mappingData));
         return mappingData;
@@ -217,11 +224,11 @@ public class MappingSystem implements IMappingSystem {
             }
         }
         recordBuilder.setAction(LispMessage.NEGATIVE_MAPPING_ACTION);
-        if (getAuthenticationKey(eid) != null) {
-            recordBuilder.setRecordTtl(TTL_RLOC_TIMED_OUT);
-        } else {
-            recordBuilder.setRecordTtl(TTL_NO_RLOC_KNOWN);
-        }
+        //if (getAuthenticationKey(eid) != null) {
+        //    recordBuilder.setRecordTtl(TTL_RLOC_TIMED_OUT);
+        //} else {
+        recordBuilder.setRecordTtl(TTL_NO_RLOC_KNOWN);
+        //}
         return recordBuilder.build();
     }
 
@@ -413,13 +420,17 @@ public class MappingSystem implements IMappingSystem {
         dsbe.removeXtrIdMapping(DSBEInputUtil.toXtrIdMapping(mappingData));
     }
 
+    @SuppressWarnings("unchecked")
     private void removeSbMapping(Eid key, MappingData mappingData) {
         if (mappingData != null && mappingData.getXtrId() != null) {
             removeSbXtrIdSpecificMapping(key, mappingData.getXtrId(), mappingData);
         }
+
         removeFromSbTimeoutService(key);
+        Set<Subscriber> subscribers = (Set<Subscriber>) getData(MappingOrigin.Southbound, key, SubKeys.SUBSCRIBERS);
         smc.removeMapping(key);
         dsbe.removeMapping(DSBEInputUtil.toMapping(MappingOrigin.Southbound, key, mappingData));
+        notifyChange(mappingData, subscribers, null, MappingChange.Removed);
     }
 
     private void removeFromSbTimeoutService(Eid key) {
@@ -431,15 +442,30 @@ public class MappingSystem implements IMappingSystem {
 
     @Override
     public Eid getWidestNegativePrefix(Eid key) {
+        if (!MaskUtil.isMaskable(key.getAddress())) {
+            LOG.warn("Widest negative prefix only makes sense for maskable addresses!");
+            return null;
+        }
+
+        // We assume that ILispMapCache#getWidestNegativeMapping() returns null for positive mappings, and 0/0
+        // for empty cache.
         Eid nbPrefix = pmc.getWidestNegativeMapping(key);
         if (nbPrefix == null) {
+            LOG.trace("getWidestNegativePrefix NB: positive mapping, returning null");
             return null;
         }
+        if (LOG.isTraceEnabled()) {
+            LOG.trace("getWidestNegativePrefix NB: {}", LispAddressStringifier.getString(nbPrefix));
+        }
 
         Eid sbPrefix = smc.getWidestNegativeMapping(key);
         if (sbPrefix == null) {
+            LOG.trace("getWidestNegativePrefix SB: positive mapping, returning null");
             return null;
         }
+        if (LOG.isTraceEnabled()) {
+            LOG.trace("getWidestNegativePrefix SB: {}", LispAddressStringifier.getString(sbPrefix));
+        }
 
         // since prefixes overlap, just return the more specific (larger mask)
         if (LispAddressUtil.getIpPrefixMask(nbPrefix) < LispAddressUtil.getIpPrefixMask(sbPrefix)) {
@@ -450,59 +476,103 @@ public class MappingSystem implements IMappingSystem {
     }
 
     @Override
+    @SuppressWarnings("unchecked")
     public void removeMapping(MappingOrigin origin, Eid key) {
         Set<Subscriber> subscribers = null;
-        if (origin == MappingOrigin.Southbound) {
-            removeFromSbTimeoutService(key);
-            MappingData mapping = (MappingData) smc.getMapping(null, key);
-            if (mapping != null && mapping.isPositive().or(false)) {
-                SimpleImmutableEntry<Eid, Set<Subscriber>> mergedNegativePrefix = computeMergedNegativePrefix(key);
-                if (mergedNegativePrefix != null) {
-                    addNegativeMapping(mergedNegativePrefix.getKey());
-                    subscribers = mergedNegativePrefix.getValue();
-                    try {
-                        notificationPublishService.putNotification(
-                                MSNotificationInputUtil.toMappingChanged(mapping, subscribers, MappingChange.Created));
-                    } catch (InterruptedException e) {
-                        LOG.warn("Notification publication interrupted!");
-                    }
+        Set<Subscriber> dstSubscribers = null;
+        MappingData mapping = (MappingData) tableMap.get(origin).getMapping(null, key);
+
+        if (LOG.isDebugEnabled()) {
+            LOG.debug("Removing mapping for EID {} from {}",
+                    LispAddressStringifier.getString(key), origin);
+        }
+        if (LOG.isTraceEnabled()) {
+            LOG.trace(mapping.getString());
+        }
+
+        MappingData notificationMapping = mapping;
+
+        if (mapping != null) {
+            subscribers = (Set<Subscriber>) getData(MappingOrigin.Southbound, key, SubKeys.SUBSCRIBERS);
+            // For SrcDst LCAF also send SMRs to Dst prefix
+            if (key.getAddress() instanceof SourceDestKey) {
+                Eid dstAddr = SourceDestKeyHelper.getDstBinary(key);
+                dstSubscribers = (Set<Subscriber>) getData(MappingOrigin.Southbound, dstAddr, SubKeys.SUBSCRIBERS);
+                if (!(mapping.getRecord().getEid().getAddress() instanceof SourceDestKey)) {
+                    notificationMapping = new MappingData(new MappingRecordBuilder().setEid(key).build());
                 }
             }
         }
-        tableMap.get(origin).removeMapping(key);
+
+        if (origin == MappingOrigin.Northbound) {
+            removeData(MappingOrigin.Southbound, key, SubKeys.SUBSCRIBERS);
+        }
+
+        if (origin == MappingOrigin.Southbound) {
+            removeFromSbTimeoutService(key);
+        }
+
+        if (origin == MappingOrigin.Southbound && mapping != null && mapping.isPositive().or(false)) {
+            mergeNegativePrefixes(key);
+        } else {
+            // mergeNegativePrefixes() above removes the mapping, so addNegativeMapping() will work correctly
+            tableMap.get(origin).removeMapping(key);
+        }
+
+        if (notificationMapping != null) {
+            notifyChange(notificationMapping, subscribers, dstSubscribers, MappingChange.Removed);
+        }
     }
 
-    @SuppressWarnings("unchecked")
+    private void notifyChange(MappingData mapping, Set<Subscriber> subscribers, Set<Subscriber> dstSubscribers,
+            MappingChange mappingChange) {
+        MappingChanged notification = MSNotificationInputUtil.toMappingChanged(mapping, subscribers, dstSubscribers,
+                mappingChange);
+        try {
+            notificationPublishService.putNotification(notification);
+        } catch (InterruptedException e) {
+            LOG.warn("Notification publication interrupted!");
+        }
+    }
+
+
     /*
-     * Returns the "merged" prefix and the subscribers of the prefixes that were merged.
+     * Merges adjacent negative prefixes and notifies their subscribers.
      */
-    private SimpleImmutableEntry<Eid, Set<Subscriber>> computeMergedNegativePrefix(Eid eid) {
-        // Variable to hold subscribers we collect along the way
-        Set<Subscriber> subscribers = null;
+    private void mergeNegativePrefixes(Eid eid) {
+        LOG.debug("Merging negative prefixes starting from EID {}", LispAddressStringifier.getString(eid));
 
-        // If prefix sibling has a negative mapping, save its subscribers
-        Eid sibling = smc.getSiblingPrefix(eid);
-        MappingData mapping = (MappingData) smc.getMapping(null, sibling);
+        // If we delete nodes while we walk up the radix trie the algorithm will give incorrect results, because
+        // removals rearrange relationships in the trie. So we save prefixes to be removed into a HashMap.
+        Map<Eid, MappingData> mergedMappings = new HashMap<>();
+
+        Eid currentNode = smc.getSiblingPrefix(eid);
+        MappingData mapping = (MappingData) smc.getMapping(null, currentNode);
         if (mapping != null && mapping.isNegative().or(false)) {
-            subscribers = (Set<Subscriber>) getData(MappingOrigin.Southbound, eid, SubKeys.SUBSCRIBERS);
+            mergedMappings.put(currentNode, mapping);
         } else {
-            return null;
+            return;
         }
 
-        Eid currentNode = sibling;
-        Eid previousNode = sibling;
-        while ((currentNode = smc.getVirtualParentSiblingPrefix(currentNode)) != null) {
+        Eid previousNode = currentNode;
+        currentNode = smc.getVirtualParentSiblingPrefix(currentNode);
+        while (currentNode != null) {
             mapping = (MappingData) smc.getMapping(null, currentNode);
             if (mapping != null && mapping.isNegative().or(false)) {
-                subscribers.addAll((Set<Subscriber>)
-                        getData(MappingOrigin.Southbound, currentNode, SubKeys.SUBSCRIBERS));
-                removeSbMapping(currentNode, mapping);
+                mergedMappings.put(currentNode, mapping);
             } else {
                 break;
             }
             previousNode = currentNode;
+            currentNode = smc.getVirtualParentSiblingPrefix(previousNode);
         }
-        return new SimpleImmutableEntry<>(getVirtualParent(previousNode), subscribers);
+
+        for (Eid key : mergedMappings.keySet()) {
+            removeSbMapping(key, mergedMappings.get(key));
+        }
+        smc.removeMapping(eid);
+
+        addNegativeMapping(getVirtualParent(previousNode));
     }
 
     private static Eid getVirtualParent(Eid eid) {
@@ -548,7 +618,7 @@ public class MappingSystem implements IMappingSystem {
     @Override
     public void addData(MappingOrigin origin, Eid key, String subKey, Object data) {
         if (LOG.isDebugEnabled()) {
-            LOG.debug("Add data of class {} for key {} and subkey {}", data.getClass(),
+            LOG.debug("Add data of {} for key {} and subkey {}", data.getClass(),
                     LispAddressStringifier.getString(key), subKey);
         }
         tableMap.get(origin).addData(key, subKey, data);
@@ -620,27 +690,38 @@ public class MappingSystem implements IMappingSystem {
     @Override
     public String printMappings() {
         final StringBuffer sb = new StringBuffer();
-        sb.append("PolicyMapCache\n--------------\n");
+        sb.append("Policy map-cache\n----------------\n");
         sb.append(pmc.printMappings());
-        sb.append("SbMapCache\n----------\n");
+        sb.append("\nSouthbound map-cache\n--------------------\n");
         sb.append(smc.printMappings());
         return sb.toString();
     }
 
+    @Override
+    public String prettyPrintMappings() {
+        final StringBuffer sb = new StringBuffer();
+        sb.append("Policy map-cache\n----------------\n");
+        sb.append(pmc.prettyPrintMappings());
+        sb.append("\nSouthbound map-cache\n--------------------\n");
+        sb.append(smc.prettyPrintMappings());
+        return sb.toString();
+    }
+
     @Override
     public String printKeys() {
         return akdb.printKeys();
     }
 
+    @Override
+    public String prettyPrintKeys() {
+        return akdb.prettyPrintKeys();
+    }
+
     public void cleanCaches() {
         dao.removeAll();
         buildMapCaches();
     }
 
-    /*
-     * XXX  Mappings and keys should be separated for this to work properly, as is it will remove northbound originated
-     * authentication keys too, since they are currently stored in smc.
-     */
     public void cleanSBMappings() {
         smc = new SimpleMapCache(sdao);
     }