Bug 9116: Move notification logic to MappingSystem
[lispflowmapping.git] / mappingservice / implementation / src / main / java / org / opendaylight / lispflowmapping / implementation / MappingSystem.java
1 /*
2  * Copyright (c) 2015, 2017 Cisco Systems, Inc.  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.implementation;
10
11 import com.google.common.collect.Sets;
12 import java.util.ArrayList;
13 import java.util.Collections;
14 import java.util.Date;
15 import java.util.EnumMap;
16 import java.util.HashMap;
17 import java.util.HashSet;
18 import java.util.List;
19 import java.util.Map;
20 import java.util.Set;
21 import java.util.concurrent.ConcurrentHashMap;
22 import org.opendaylight.controller.md.sal.binding.api.NotificationPublishService;
23 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
24 import org.opendaylight.lispflowmapping.config.ConfigIni;
25 import org.opendaylight.lispflowmapping.dsbackend.DataStoreBackEnd;
26 import org.opendaylight.lispflowmapping.implementation.timebucket.implementation.TimeBucketMappingTimeoutService;
27 import org.opendaylight.lispflowmapping.implementation.timebucket.interfaces.ISouthBoundMappingTimeoutService;
28 import org.opendaylight.lispflowmapping.implementation.util.DSBEInputUtil;
29 import org.opendaylight.lispflowmapping.implementation.util.LoggingUtil;
30 import org.opendaylight.lispflowmapping.implementation.util.MSNotificationInputUtil;
31 import org.opendaylight.lispflowmapping.implementation.util.MappingMergeUtil;
32 import org.opendaylight.lispflowmapping.interfaces.dao.ILispDAO;
33 import org.opendaylight.lispflowmapping.interfaces.dao.SubKeys;
34 import org.opendaylight.lispflowmapping.interfaces.dao.Subscriber;
35 import org.opendaylight.lispflowmapping.interfaces.mapcache.IAuthKeyDb;
36 import org.opendaylight.lispflowmapping.interfaces.mapcache.ILispMapCache;
37 import org.opendaylight.lispflowmapping.interfaces.mapcache.IMapCache;
38 import org.opendaylight.lispflowmapping.interfaces.mapcache.IMappingSystem;
39 import org.opendaylight.lispflowmapping.interfaces.mappingservice.IMappingService;
40 import org.opendaylight.lispflowmapping.lisp.type.LispMessage;
41 import org.opendaylight.lispflowmapping.lisp.type.MappingData;
42 import org.opendaylight.lispflowmapping.lisp.util.LispAddressStringifier;
43 import org.opendaylight.lispflowmapping.lisp.util.LispAddressUtil;
44 import org.opendaylight.lispflowmapping.lisp.util.MappingRecordUtil;
45 import org.opendaylight.lispflowmapping.lisp.util.MaskUtil;
46 import org.opendaylight.lispflowmapping.lisp.util.SourceDestKeyHelper;
47 import org.opendaylight.lispflowmapping.mapcache.AuthKeyDb;
48 import org.opendaylight.lispflowmapping.mapcache.MultiTableMapCache;
49 import org.opendaylight.lispflowmapping.mapcache.SimpleMapCache;
50 import org.opendaylight.lispflowmapping.mapcache.lisp.LispMapCacheStringifier;
51 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.SimpleAddress;
52 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.ExplicitLocatorPath;
53 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.Ipv4;
54 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.Ipv6;
55 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.ServicePath;
56 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.SourceDestKey;
57 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;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.inet.binary.types.rev160303.IpAddressBinary;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.binary.address.types.rev160504.Ipv4PrefixBinaryAfi;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.binary.address.types.rev160504.Ipv6PrefixBinaryAfi;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.binary.address.types.rev160504.augmented.lisp.address.address.Ipv4PrefixBinary;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.binary.address.types.rev160504.augmented.lisp.address.address.Ipv6PrefixBinary;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.XtrId;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.eid.container.Eid;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.locatorrecords.LocatorRecord;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.locatorrecords.LocatorRecordBuilder;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.authkey.container.MappingAuthkey;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.record.container.MappingRecord;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.record.container.MappingRecordBuilder;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.rloc.container.Rloc;
71 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.mappingservice.rev150906.MappingChange;
72 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.mappingservice.rev150906.MappingOrigin;
73 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.mappingservice.rev150906.db.instance.AuthenticationKey;
74 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.mappingservice.rev150906.db.instance.Mapping;
75 import org.slf4j.Logger;
76 import org.slf4j.LoggerFactory;
77
78 /**
79  * The Mapping System coordinates caching of md-sal stored mappings and if so configured enables longest prefix match
80  * mapping lookups.
81  *
82  * @author Florin Coras
83  * @author Lorand Jakab
84  *
85  */
86 public class MappingSystem implements IMappingSystem {
87     private static final Logger LOG = LoggerFactory.getLogger(MappingSystem.class);
88     private static final String AUTH_KEY_TABLE = "authentication";
89     //private static final int TTL_RLOC_TIMED_OUT = 1;
90     private static final int TTL_NO_RLOC_KNOWN = ConfigIni.getInstance().getNegativeMappingTTL();
91     private NotificationPublishService notificationPublishService;
92     private boolean mappingMerge;
93     private ILispDAO dao;
94     private ILispDAO sdao;
95     private ILispMapCache smc;
96     private IMapCache pmc;
97     private ConcurrentHashMap<Eid, Set<Subscriber>> subscriberdb = new ConcurrentHashMap<>();
98     private IAuthKeyDb akdb;
99     private final EnumMap<MappingOrigin, IMapCache> tableMap = new EnumMap<>(MappingOrigin.class);
100     private DataStoreBackEnd dsbe;
101     private boolean isMaster = false;
102
103     private ISouthBoundMappingTimeoutService sbMappingTimeoutService;
104
105     public MappingSystem(ILispDAO dao, boolean iterateMask, NotificationPublishService nps, boolean mappingMerge) {
106         this.dao = dao;
107         this.notificationPublishService = nps;
108         this.mappingMerge = mappingMerge;
109         buildMapCaches();
110
111         sbMappingTimeoutService = new TimeBucketMappingTimeoutService(ConfigIni.getInstance()
112                 .getNumberOfBucketsInTimeBucketWheel(), ConfigIni.getInstance().getRegistrationValiditySb(),
113                 this);
114     }
115
116     public void setDataStoreBackEnd(DataStoreBackEnd dataStoreBackEnd) {
117         this.dsbe = dataStoreBackEnd;
118     }
119
120     @Override
121     public void setMappingMerge(boolean mappingMerge) {
122         this.mappingMerge = mappingMerge;
123     }
124
125     @Override
126     public void setIterateMask(boolean iterate) {
127         LOG.error("Non-longest prefix match lookups are not properly supported, variable is set to true");
128     }
129
130     public void initialize() {
131         restoreDaoFromDatastore();
132     }
133
134     private void buildMapCaches() {
135         /*
136          * There exists a direct relationship between MappingOrigins and the tables that are part of the MappingSystem.
137          * Therefore, if a new origin is added, probably a new table should be instantiated here as well. Here we
138          * instantiate a SimpleMapCache for southbound originated LISP mappings and a MultiTableMapCache for northbound
139          * originated mappings. Use of FlatMapCache would be possible when no longest prefix match is needed at all,
140          * but that option is no longer supported in the code, since it was never tested and may lead to unexpected
141          * results.
142          */
143         sdao = dao.putTable(MappingOrigin.Southbound.toString());
144         pmc = new MultiTableMapCache(dao.putTable(MappingOrigin.Northbound.toString()));
145         smc = new SimpleMapCache(sdao);
146         akdb = new AuthKeyDb(dao.putTable(AUTH_KEY_TABLE));
147         tableMap.put(MappingOrigin.Northbound, pmc);
148         tableMap.put(MappingOrigin.Southbound, smc);
149     }
150
151     @Override
152     public void updateMapping(MappingOrigin origin, Eid key, MappingData mappingData) {
153         addMapping(origin, key, mappingData, MappingChange.Updated);
154     }
155
156     @Override
157     public void addMapping(MappingOrigin origin, Eid key, MappingData mappingData) {
158         addMapping(origin, key, mappingData, MappingChange.Created);
159     }
160
161     private void addMapping(MappingOrigin origin, Eid key, MappingData mappingData, MappingChange changeType) {
162
163         sbMappingTimeoutService.removeExpiredMappings();
164
165         if (mappingData == null) {
166             LOG.warn("addMapping() called with null mapping, ignoring");
167             return;
168         }
169
170         if (LOG.isDebugEnabled()) {
171             LOG.debug("DAO: Adding {} mapping for EID {}", origin, LispAddressStringifier.getString(key));
172         }
173
174         if (LOG.isTraceEnabled()) {
175             LOG.trace("mappingData = {}", mappingData.getString());
176         }
177
178         // Save the old mapping for the key before we modify anything, so that we can detect changes later
179         final MappingRecord oldMapping = getMappingRecord(getMapping(key));
180
181         if (origin == MappingOrigin.Southbound) {
182             XtrId xtrId = mappingData.getXtrId();
183             if (xtrId == null && mappingMerge && mappingData.isMergeEnabled()) {
184                 LOG.warn("addMapping() called will null xTR-ID in MappingRecord, while merge is set, ignoring");
185                 return;
186             }
187             if (xtrId != null && mappingMerge) {
188                 if (mappingData.isMergeEnabled()) {
189                     smc.addMapping(key, xtrId, mappingData);
190                     handleMergedMapping(key);
191                     return;
192                 } else {
193                     clearPresentXtrIdMappings(key);
194                     smc.addMapping(key, xtrId, mappingData);
195                 }
196             }
197             addOrRefreshMappingInTimeoutService(key, mappingData);
198         }
199
200         tableMap.get(origin).addMapping(key, mappingData);
201
202         // We need to check if the newly added mapping is covering negatives in SB, and remove those (with notification)
203         if (mappingData.isPositive().or(true)) {
204             handleSbNegativeMappings(key);
205         }
206
207         MappingRecord newMapping = getMappingRecord(getMapping(key));
208
209         handleAddMappingNotifications(origin, key, mappingData, oldMapping, newMapping, changeType);
210     }
211
212     private static MappingRecord getMappingRecord(MappingData mappingData) {
213         return (mappingData != null) ? mappingData.getRecord() : null;
214     }
215
216     @SuppressWarnings("unchecked")
217     private void clearPresentXtrIdMappings(Eid key) {
218         List<MappingData> allXtrMappingList = (List<MappingData>) (List<?>) smc.getAllXtrIdMappings(key);
219
220         if (((MappingData) smc.getMapping(key, (XtrId) null)).isMergeEnabled()) {
221             LOG.trace("Different xTRs have different merge configuration!");
222         }
223
224         for (MappingData mappingData : allXtrMappingList) {
225             removeSbXtrIdSpecificMapping(key, mappingData.getXtrId(), mappingData);
226         }
227     }
228
229     private void addOrRefreshMappingInTimeoutService(Eid key, MappingData mappingData) {
230         Integer oldBucketId = (Integer) smc.getData(key, SubKeys.TIME_BUCKET_ID);
231         Integer updatedBucketId;
232
233         if (oldBucketId != null) {
234             //refresh mapping
235             updatedBucketId = sbMappingTimeoutService.refreshMapping(key, mappingData, oldBucketId);
236         } else {
237             updatedBucketId = sbMappingTimeoutService.addMapping(key, mappingData);
238         }
239
240         smc.addData(key, SubKeys.TIME_BUCKET_ID, updatedBucketId);
241     }
242
243     private void handleSbNegativeMappings(Eid key) {
244         Set<Eid> childPrefixes = getSubtree(MappingOrigin.Southbound, key);
245
246         LOG.trace("handleSbNegativeMappings(): subtree prefix set for EID {} (excluding the EID itself): {}",
247                 LispAddressStringifier.getString(key),
248                 LispAddressStringifier.getString(childPrefixes));
249         if (childPrefixes == null || childPrefixes.isEmpty()) {
250             // The assumption here is that negative prefixes are well maintained and never overlapping.
251             // If we have children for the EID, no parent lookup should thus be necessary.
252             Eid parentPrefix = smc.getCoveringLessSpecific(key);
253             LOG.trace("handleSbNegativeMappings(): parent prefix for EID {}: {}",
254                     LispAddressStringifier.getString(key),
255                     LispAddressStringifier.getString(parentPrefix));
256             handleSbNegativeMapping(parentPrefix);
257             return;
258         }
259
260         for (Eid prefix : childPrefixes) {
261             handleSbNegativeMapping(prefix);
262         }
263     }
264
265     private void handleSbNegativeMapping(Eid key) {
266         MappingData mappingData = getSbMappingWithExpiration(null, key, null);
267         if (mappingData != null && mappingData.isNegative().or(false)) {
268             removeSbMapping(mappingData.getRecord().getEid(), mappingData);
269         }
270     }
271
272     private void handleAddMappingNotifications(MappingOrigin origin, Eid key, MappingData mappingData,
273                                                MappingRecord oldMapping, MappingRecord newMapping,
274                                                MappingChange changeType) {
275         // Non-southbound origins are MD-SAL first, so they only get to call addMapping() if there is a change
276         // Southbound is different, so we need to check if there is a change in the mapping. This check takes into
277         // account policy as well
278         if (origin != MappingOrigin.Southbound || MappingRecordUtil.mappingChanged(oldMapping, newMapping)) {
279             notifyChange(key, mappingData.getRecord(), changeType);
280
281             Eid dstKey = key;
282             // Since the above notifyChange() already notifies the dest part of source/dest addresses, we save the dest
283             // for the checks that we do afterwards
284             if (key.getAddress() instanceof SourceDestKey) {
285                 dstKey = SourceDestKeyHelper.getDstBinary(key);
286             }
287             // If the old mapping had a different EID than what was just added, notify those subscribers too
288             if (oldMapping != null && !oldMapping.getEid().equals(key) && !oldMapping.getEid().equals(dstKey)) {
289                 notifyChange(oldMapping.getEid(), oldMapping, changeType);
290             }
291             // If the new mapping has a different EID than what was just added (e.g., due to NB_AND_SB), notify those
292             // subscribers too
293             if (newMapping != null && !newMapping.getEid().equals(key) && !newMapping.getEid().equals(dstKey)) {
294                 notifyChange(newMapping.getEid(), newMapping, changeType);
295             }
296         }
297
298     }
299
300     @Override
301     public MappingData addNegativeMapping(Eid key) {
302         MappingRecord mapping = buildNegativeMapping(key);
303         MappingData mappingData = new MappingData(mapping);
304         LOG.debug("Adding negative mapping for EID {}", LispAddressStringifier.getString(mapping.getEid()));
305         LOG.trace(mappingData.getString());
306         smc.addMapping(mapping.getEid(), mappingData);
307         dsbe.addMapping(DSBEInputUtil.toMapping(MappingOrigin.Southbound, mapping.getEid(), null, mappingData));
308         return mappingData;
309     }
310
311     private MappingRecord buildNegativeMapping(Eid eid) {
312         MappingRecordBuilder recordBuilder = new MappingRecordBuilder();
313         recordBuilder.setAuthoritative(false);
314         recordBuilder.setMapVersion((short) 0);
315         recordBuilder.setEid(eid);
316         if (eid.getAddressType().equals(Ipv4PrefixBinaryAfi.class)
317                 || eid.getAddressType().equals(Ipv6PrefixBinaryAfi.class)) {
318             Eid widestNegativePrefix = getWidestNegativePrefix(eid);
319             if (widestNegativePrefix != null) {
320                 recordBuilder.setEid(widestNegativePrefix);
321             }
322         }
323         recordBuilder.setAction(LispMessage.NEGATIVE_MAPPING_ACTION);
324         //if (getAuthenticationKey(eid) != null) {
325         //    recordBuilder.setRecordTtl(TTL_RLOC_TIMED_OUT);
326         //} else {
327         recordBuilder.setRecordTtl(TTL_NO_RLOC_KNOWN);
328         //}
329         return recordBuilder.build();
330     }
331
332     /*
333      * Since this method is only called when there is a hit in the southbound Map-Register cache, and that cache is
334      * not used when merge is on, it's OK to ignore the effects of timestamp changes on merging for now.
335      */
336     public void refreshMappingRegistration(Eid key, XtrId xtrId, Long timestamp) {
337
338         sbMappingTimeoutService.removeExpiredMappings();
339
340         if (timestamp == null) {
341             timestamp = System.currentTimeMillis();
342         }
343         MappingData mappingData = (MappingData) smc.getMapping(null, key);
344         if (mappingData != null) {
345             mappingData.setTimestamp(new Date(timestamp));
346             addOrRefreshMappingInTimeoutService(key, mappingData);
347         } else {
348             LOG.warn("Could not update timestamp for EID {}, no mapping found", LispAddressStringifier.getString(key));
349         }
350         if (mappingMerge && xtrId != null) {
351             MappingData xtrIdMappingData = (MappingData) smc.getMapping(key, xtrId);
352             if (xtrIdMappingData != null) {
353                 xtrIdMappingData.setTimestamp(new Date(timestamp));
354             } else {
355                 LOG.warn("Could not update timestamp for EID {} xTR-ID {}, no mapping found",
356                         LispAddressStringifier.getString(key), LispAddressStringifier.getString(xtrId));
357             }
358         }
359     }
360
361     private MappingData updateServicePathMappingRecord(MappingData mappingData, Eid eid) {
362         // keep properties of original record
363         MappingRecordBuilder recordBuilder = new MappingRecordBuilder(mappingData.getRecord());
364         recordBuilder.setLocatorRecord(new ArrayList<LocatorRecord>());
365
366         // there should only be one locator record
367         if (mappingData.getRecord().getLocatorRecord().size() != 1) {
368             LOG.warn("MappingRecord associated to ServicePath EID has more than one locator!");
369             return mappingData;
370         }
371
372         LocatorRecord locatorRecord = mappingData.getRecord().getLocatorRecord().get(0);
373         long serviceIndex = ((ServicePath) eid.getAddress()).getServicePath().getServiceIndex();
374         int index = LispAddressUtil.STARTING_SERVICE_INDEX - (int) serviceIndex;
375         Rloc rloc = locatorRecord.getRloc();
376         if (rloc.getAddress() instanceof Ipv4 || rloc.getAddress() instanceof Ipv6) {
377             if (index != 0) {
378                 LOG.warn("Service Index should be 255 for simple IP RLOCs!");
379             }
380             return mappingData;
381         } else if (rloc.getAddress() instanceof ExplicitLocatorPath) {
382             ExplicitLocatorPath elp = (ExplicitLocatorPath) rloc.getAddress();
383             List<Hop> hops = elp.getExplicitLocatorPath().getHop();
384
385             if (index < 0 || index > hops.size())  {
386                 LOG.warn("Service Index out of bounds!");
387                 return mappingData;
388             }
389
390             SimpleAddress nextHop = hops.get(index).getAddress();
391             LocatorRecordBuilder lrb = new LocatorRecordBuilder(locatorRecord);
392             lrb.setRloc(LispAddressUtil.toRloc(nextHop));
393             recordBuilder.getLocatorRecord().add(lrb.build());
394             return new MappingData(recordBuilder.build());
395         } else {
396             LOG.warn("Nothing to do with ServicePath mapping record");
397             return mappingData;
398         }
399     }
400
401     private MappingData handleMergedMapping(Eid key) {
402         LOG.trace("Merging mappings for EID {}", LispAddressStringifier.getString(key));
403         List<MappingData> expiredMappingDataList = new ArrayList<>();
404         Set<IpAddressBinary> sourceRlocs = new HashSet<>();
405
406         MappingData mergedMappingData = MappingMergeUtil.mergeXtrIdMappings(smc.getAllXtrIdMappings(key),
407                 expiredMappingDataList, sourceRlocs);
408
409         for (MappingData mappingData : expiredMappingDataList) {
410             removeSbXtrIdSpecificMapping(key, mappingData.getXtrId(), mappingData);
411         }
412
413         if (mergedMappingData != null) {
414             smc.addMapping(key, mergedMappingData, sourceRlocs);
415             dsbe.addMapping(DSBEInputUtil.toMapping(MappingOrigin.Southbound, key, mergedMappingData));
416             addOrRefreshMappingInTimeoutService(key, mergedMappingData);
417         } else {
418             removeSbMapping(key, mergedMappingData);
419         }
420         return mergedMappingData;
421     }
422
423     @Override
424     public MappingData getMapping(Eid src, Eid dst) {
425         // NOTE: Currently we have two lookup algorithms implemented, which are configurable
426         IMappingService.LookupPolicy policy = ConfigIni.getInstance().getLookupPolicy();
427         LOG.debug("DAO: Looking up mapping for {}, source EID {} with policy {}",
428                 LispAddressStringifier.getString(dst),
429                 LispAddressStringifier.getString(src),
430                 policy);
431
432         if (policy == IMappingService.LookupPolicy.NB_AND_SB) {
433             return getMappingNbSbIntersection(src, dst);
434         } else {
435             return getMappingNbFirst(src, dst);
436         }
437     }
438
439     @Override
440     public MappingData getMapping(Eid dst) {
441         return getMapping((Eid) null, dst);
442     }
443
444     @Override
445     public MappingData getMapping(Eid src, Eid dst, XtrId xtrId) {
446         // Note: If xtrId is null, we need to go through regular policy checking else Policy doesn't matter
447
448         if (xtrId == null) {
449             return getMapping(src, dst);
450         }
451
452         return getSbMappingWithExpiration(src, dst, xtrId);
453     }
454
455     @Override
456     public MappingData getMapping(MappingOrigin origin, Eid key) {
457         if (origin.equals(MappingOrigin.Southbound)) {
458             return getSbMappingWithExpiration(null, key, null);
459         }
460         return (MappingData) tableMap.get(origin).getMapping(null, key);
461     }
462
463     private MappingData getMappingNbFirst(Eid src, Eid dst) {
464
465         // Default lookup policy is northboundFirst
466         //lookupPolicy == NB_FIRST
467
468         MappingData nbMappingData = (MappingData) pmc.getMapping(src, dst);
469
470         if (nbMappingData == null) {
471             return getSbMappingWithExpiration(src, dst, null);
472         }
473         if (dst.getAddress() instanceof ServicePath) {
474             return updateServicePathMappingRecord(nbMappingData, dst);
475         }
476         return nbMappingData;
477     }
478
479     private MappingData getMappingNbSbIntersection(Eid src, Eid dst) {
480         //lookupPolicy == NB_AND_SB, we return intersection
481         //of NB and SB mappings, or NB mapping if intersection is empty.
482
483         MappingData nbMappingData = (MappingData) pmc.getMapping(src, dst);
484         if (nbMappingData == null) {
485             return nbMappingData;
486         }
487         // no intersection for Service Path mappings
488         if (dst.getAddress() instanceof ServicePath) {
489             return updateServicePathMappingRecord(nbMappingData, dst);
490         }
491         MappingData sbMappingData = getSbMappingWithExpiration(src, dst, null);
492         if (sbMappingData == null) {
493             return nbMappingData;
494         }
495         // both NB and SB mappings exist. Compute intersection of the mappings
496         return MappingMergeUtil.computeNbSbIntersection(nbMappingData, sbMappingData);
497     }
498
499     private MappingData getSbMappingWithExpiration(Eid src, Eid dst, XtrId xtrId) {
500         MappingData mappingData = (MappingData) smc.getMapping(dst, xtrId);
501         if (mappingData != null && MappingMergeUtil.mappingIsExpired(mappingData)) {
502             return handleSbExpiredMapping(dst, xtrId, mappingData);
503         } else {
504             return mappingData;
505         }
506     }
507
508     public MappingData handleSbExpiredMapping(Eid key, XtrId xtrId, MappingData mappingData) {
509         if (mappingMerge && mappingData.isMergeEnabled()) {
510             return handleMergedMapping(key);
511         }
512
513         if (xtrId != null) {
514             removeSbXtrIdSpecificMapping(key, xtrId, mappingData);
515         } else {
516             removeSbMapping(key, mappingData);
517         }
518         return null;
519     }
520
521     private void removeSbXtrIdSpecificMapping(Eid key, XtrId xtrId, MappingData mappingData) {
522         if (LOG.isDebugEnabled()) {
523             LOG.debug("DAO: Removing southbound mapping for EID {}, xTR-ID {}",
524                     LispAddressStringifier.getString(key),
525                     LispAddressStringifier.getString(xtrId));
526         }
527         smc.removeMapping(key, xtrId);
528         dsbe.removeXtrIdMapping(DSBEInputUtil.toXtrIdMapping(mappingData));
529     }
530
531     private void removeSbMapping(Eid key, MappingData mappingData) {
532         if (mappingData != null && mappingData.getXtrId() != null) {
533             removeSbXtrIdSpecificMapping(key, mappingData.getXtrId(), mappingData);
534         }
535
536         removeFromSbTimeoutService(key);
537         final Set<Subscriber> subscribers = getSubscribers(key);
538         if (LOG.isDebugEnabled()) {
539             LOG.debug("DAO: Removing southbound mapping for EID {}", LispAddressStringifier.getString(key));
540         }
541         smc.removeMapping(key);
542         dsbe.removeMapping(DSBEInputUtil.toMapping(MappingOrigin.Southbound, key, mappingData));
543         publishNotification(mappingData.getRecord(), null, subscribers, null, MappingChange.Removed);
544         removeSubscribersConditionally(MappingOrigin.Southbound, key);
545     }
546
547     private void removeFromSbTimeoutService(Eid key) {
548         Integer bucketId = (Integer) smc.getData(key, SubKeys.TIME_BUCKET_ID);
549         if (bucketId != null) {
550             sbMappingTimeoutService.removeMappingFromTimeoutService(key, bucketId);
551         }
552     }
553
554     @Override
555     public Eid getWidestNegativePrefix(Eid key) {
556         if (!MaskUtil.isMaskable(key.getAddress())) {
557             LOG.warn("Widest negative prefix only makes sense for maskable addresses!");
558             return null;
559         }
560
561         // We assume that ILispMapCache#getWidestNegativeMapping() returns null for positive mappings, and 0/0
562         // for empty cache.
563         Eid nbPrefix = pmc.getWidestNegativeMapping(key);
564         if (nbPrefix == null) {
565             LOG.trace("getWidestNegativePrefix NB: positive mapping, returning null");
566             return null;
567         }
568         if (LOG.isTraceEnabled()) {
569             LOG.trace("getWidestNegativePrefix NB: {}", LispAddressStringifier.getString(nbPrefix));
570         }
571
572         Eid sbPrefix = smc.getWidestNegativeMapping(key);
573         if (sbPrefix == null) {
574             LOG.trace("getWidestNegativePrefix SB: positive mapping, returning null");
575             return null;
576         }
577         if (LOG.isTraceEnabled()) {
578             LOG.trace("getWidestNegativePrefix SB: {}", LispAddressStringifier.getString(sbPrefix));
579         }
580
581         // since prefixes overlap, just return the more specific (larger mask)
582         if (LispAddressUtil.getIpPrefixMask(nbPrefix) < LispAddressUtil.getIpPrefixMask(sbPrefix)) {
583             return sbPrefix;
584         } else {
585             return nbPrefix;
586         }
587     }
588
589     @Override
590     public Set<Eid> getSubtree(MappingOrigin origin, Eid key) {
591         if (!MaskUtil.isMaskable(key.getAddress())) {
592             LOG.warn("Child prefixes only make sense for maskable addresses!");
593             return Collections.emptySet();
594         }
595
596         return tableMap.get(origin).getSubtree(key);
597     }
598
599     @Override
600     public void removeMapping(MappingOrigin origin, Eid key) {
601         Eid dstAddr = null;
602         Set<Subscriber> subscribers = null;
603         Set<Subscriber> dstSubscribers = null;
604         MappingData mapping = (MappingData) tableMap.get(origin).getMapping(null, key);
605
606         if (LOG.isDebugEnabled()) {
607             LOG.debug("Removing mapping for EID {} from {}",
608                     LispAddressStringifier.getString(key), origin);
609         }
610         if (LOG.isTraceEnabled() && mapping != null) {
611             LOG.trace(mapping.getString());
612         }
613
614         MappingRecord notificationMapping = null;
615
616         if (mapping != null) {
617             notificationMapping = mapping.getRecord();
618             subscribers = getSubscribers(key);
619             // For SrcDst LCAF also send SMRs to Dst prefix
620             if (key.getAddress() instanceof SourceDestKey) {
621                 dstAddr = SourceDestKeyHelper.getDstBinary(key);
622                 dstSubscribers = getSubscribers(dstAddr);
623             }
624         }
625
626         removeSubscribersConditionally(origin, key);
627
628         if (origin == MappingOrigin.Southbound) {
629             removeFromSbTimeoutService(key);
630         }
631
632         if (origin == MappingOrigin.Southbound && mapping != null && mapping.isPositive().or(false)) {
633             mergeNegativePrefixes(key);
634         } else {
635             // mergeNegativePrefixes() above removes the mapping, so addNegativeMapping() will work correctly
636             tableMap.get(origin).removeMapping(key);
637         }
638
639         if (notificationMapping != null) {
640             publishNotification(notificationMapping, key, subscribers, dstSubscribers, MappingChange.Removed);
641             notifyChildren(key, notificationMapping, MappingChange.Removed);
642             if (dstAddr != null) {
643                 notifyChildren(dstAddr, notificationMapping, MappingChange.Removed);
644             }
645         }
646     }
647
648     public void notifyChange(Eid eid, MappingRecord mapping, MappingChange mappingChange) {
649         Set<Subscriber> subscribers = getSubscribers(eid);
650
651         Set<Subscriber> dstSubscribers = null;
652         // For SrcDst LCAF also send SMRs to Dst prefix
653         if (eid.getAddress() instanceof SourceDestKey) {
654             Eid dstAddr = SourceDestKeyHelper.getDstBinary(eid);
655             dstSubscribers = getSubscribers(dstAddr);
656             notifyChildren(dstAddr, mapping, mappingChange);
657         }
658
659         // No reason to send a notification when no subscribers exist
660         if (subscribers != null || dstSubscribers != null) {
661             publishNotification(mapping, eid, subscribers, dstSubscribers, mappingChange);
662         }
663
664         notifyChildren(eid, mapping, mappingChange);
665     }
666
667     private void notifyChildren(Eid eid, MappingRecord mapping, MappingChange mappingChange) {
668         // Update/created only happens for NB mappings. We assume no overlapping prefix support for NB mappings - so
669         // this NB mapping should not have any children. Both for NB first and NB&SB cases all subscribers for SB
670         // prefixes that are equal or more specific to this NB prefix have to be notified of the potential change.
671         // Each subscriber is notified for the prefix that it is currently subscribed to, and MS should return to them
672         // a Map-Reply with the same prefix and update mapping in cases of EID_INTERSECTION_RLOC_NB_FIRST which is a
673         // new option we are creating TODO
674         Set<Eid> childPrefixes = getSubtree(MappingOrigin.Southbound, eid);
675         if (childPrefixes == null || childPrefixes.isEmpty()) {
676             return;
677         }
678
679         childPrefixes.remove(eid);
680         for (Eid prefix : childPrefixes) {
681             Set<Subscriber> subscribers = getSubscribers(prefix);
682             // No reason to send a notification when no subscribers exist
683             if (subscribers != null) {
684                 publishNotification(mapping, prefix, subscribers, null, mappingChange);
685             }
686         }
687     }
688
689     private void publishNotification(MappingRecord mapping, Eid eid, Set<Subscriber> subscribers,
690                                      Set<Subscriber> dstSubscribers, MappingChange mappingChange) {
691         try {
692             // The notifications are used for sending SMR.
693             notificationPublishService.putNotification(MSNotificationInputUtil.toMappingChanged(
694                     mapping, eid, subscribers, dstSubscribers, mappingChange));
695         } catch (InterruptedException e) {
696             LOG.warn("Notification publication interrupted!");
697         }
698     }
699
700     /*
701      * Merges adjacent negative prefixes and notifies their subscribers.
702      */
703     private void mergeNegativePrefixes(Eid eid) {
704         LOG.debug("Merging negative prefixes starting from EID {}", LispAddressStringifier.getString(eid));
705
706         // If we delete nodes while we walk up the radix trie the algorithm will give incorrect results, because
707         // removals rearrange relationships in the trie. So we save prefixes to be removed into a HashMap.
708         Map<Eid, MappingData> mergedMappings = new HashMap<>();
709
710         Eid currentNode = smc.getSiblingPrefix(eid);
711         MappingData mapping = (MappingData) smc.getMapping(null, currentNode);
712         if (mapping != null && mapping.isNegative().or(false)) {
713             mergedMappings.put(currentNode, mapping);
714         } else {
715             return;
716         }
717
718         Eid previousNode = currentNode;
719         currentNode = smc.getVirtualParentSiblingPrefix(currentNode);
720         while (currentNode != null) {
721             mapping = (MappingData) smc.getMapping(null, currentNode);
722             if (mapping != null && mapping.isNegative().or(false)) {
723                 mergedMappings.put(currentNode, mapping);
724             } else {
725                 break;
726             }
727             previousNode = currentNode;
728             currentNode = smc.getVirtualParentSiblingPrefix(previousNode);
729         }
730
731         for (Eid key : mergedMappings.keySet()) {
732             removeSbMapping(key, mergedMappings.get(key));
733         }
734         smc.removeMapping(eid);
735
736         addNegativeMapping(getVirtualParent(previousNode));
737     }
738
739     private static Eid getVirtualParent(Eid eid) {
740         if (eid.getAddress() instanceof Ipv4PrefixBinary) {
741             Ipv4PrefixBinary prefix = (Ipv4PrefixBinary) eid.getAddress();
742             short parentPrefixLength = (short) (prefix.getIpv4MaskLength() - 1);
743             byte[] parentPrefix = MaskUtil.normalizeByteArray(prefix.getIpv4AddressBinary().getValue(),
744                     parentPrefixLength);
745             return LispAddressUtil.asIpv4PrefixBinaryEid(eid, parentPrefix, parentPrefixLength);
746         } else if (eid.getAddress() instanceof Ipv6PrefixBinary) {
747             Ipv6PrefixBinary prefix = (Ipv6PrefixBinary) eid.getAddress();
748             short parentPrefixLength = (short) (prefix.getIpv6MaskLength() - 1);
749             byte[] parentPrefix = MaskUtil.normalizeByteArray(prefix.getIpv6AddressBinary().getValue(),
750                     parentPrefixLength);
751             return LispAddressUtil.asIpv6PrefixBinaryEid(eid, parentPrefix, parentPrefixLength);
752         }
753         return null;
754     }
755
756     @Override
757     public synchronized void subscribe(Subscriber subscriber, Eid subscribedEid) {
758         Set<Subscriber> subscribers = getSubscribers(subscribedEid);
759         if (subscribers == null) {
760             subscribers = Sets.newConcurrentHashSet();
761         } else if (subscribers.contains(subscriber)) {
762             // If there is an entry already for this subscriber, remove it, so that it gets the new timestamp
763             subscribers.remove(subscriber);
764         }
765         if (LOG.isDebugEnabled()) {
766             LOG.debug("Adding new subscriber {} for EID {}", subscriber.getString(),
767                     LispAddressStringifier.getString(subscribedEid));
768         }
769         subscribers.add(subscriber);
770         addSubscribers(subscribedEid, subscribers);
771     }
772
773     private void addSubscribers(Eid address, Set<Subscriber> subscribers) {
774         LoggingUtil.logSubscribers(LOG, address, subscribers);
775         subscriberdb.put(address, subscribers);
776     }
777
778     @Override
779     public Set<Subscriber> getSubscribers(Eid address) {
780         if (LOG.isDebugEnabled()) {
781             LOG.debug("Retrieving subscribers for EID {}", LispAddressStringifier.getString(address));
782         }
783
784         Set<Subscriber> subscribers = subscriberdb.get(address);
785         LoggingUtil.logSubscribers(LOG, address, subscribers);
786         return subscribers;
787     }
788
789     /*
790      * Only remove subscribers if there is no exact match mapping in the map-cache other than the one specified by
791      * origin. Right now we only have two origins, but in case we will have more, we only need to update this method,
792      * not the callers. We use getData() instead of getMapping to do exact match instead of longest prefix match.
793      */
794     private void removeSubscribersConditionally(MappingOrigin origin, Eid address) {
795         if (origin == MappingOrigin.Southbound) {
796             if (pmc.getData(address, SubKeys.RECORD) == null) {
797                 removeSubscribers(address);
798             }
799         } else if (origin == MappingOrigin.Northbound) {
800             if (smc.getData(address, SubKeys.RECORD) == null) {
801                 removeSubscribers(address);
802             }
803         }
804     }
805
806     private void removeSubscribers(Eid address) {
807         if (LOG.isDebugEnabled()) {
808             LOG.debug("Removing subscribers for EID {}", LispAddressStringifier.getString(address));
809         }
810         subscriberdb.remove(address);
811     }
812
813     @Override
814     public void addAuthenticationKey(Eid key, MappingAuthkey authKey) {
815         LOG.debug("Adding authentication key '{}' with key-ID {} for {}", authKey.getKeyString(), authKey.getKeyType(),
816                 LispAddressStringifier.getString(key));
817         akdb.addAuthenticationKey(key, authKey);
818     }
819
820     @Override
821     public MappingAuthkey getAuthenticationKey(Eid key) {
822         if (LOG.isDebugEnabled()) {
823             LOG.debug("Retrieving authentication key for {}", LispAddressStringifier.getString(key));
824         }
825         return akdb.getAuthenticationKey(key);
826     }
827
828     @Override
829     public void removeAuthenticationKey(Eid key) {
830         if (LOG.isDebugEnabled()) {
831             LOG.debug("Removing authentication key for {}", LispAddressStringifier.getString(key));
832         }
833         akdb.removeAuthenticationKey(key);
834     }
835
836     @Override
837     public void addData(MappingOrigin origin, Eid key, String subKey, Object data) {
838         if (LOG.isDebugEnabled()) {
839             LOG.debug("Add data of {} for key {} and subkey {}", data.getClass(),
840                     LispAddressStringifier.getString(key), subKey);
841         }
842         tableMap.get(origin).addData(key, subKey, data);
843     }
844
845     @Override
846     public Object getData(MappingOrigin origin, Eid key, String subKey) {
847         if (LOG.isDebugEnabled()) {
848             LOG.debug("Retrieving data for key {} and subkey {}", LispAddressStringifier.getString(key), subKey);
849         }
850         return tableMap.get(origin).getData(key, subKey);
851     }
852
853     @Override
854     public void removeData(MappingOrigin origin, Eid key, String subKey) {
855         if (LOG.isDebugEnabled()) {
856             LOG.debug("Removing data for key {} and subkey {}", LispAddressStringifier.getString(key), subKey);
857         }
858         tableMap.get(origin).removeData(key, subKey);
859     }
860
861     @Override
862     public Eid getParentPrefix(Eid key) {
863         return smc.getParentPrefix(key);
864     }
865
866
867     /**
868      * Restore all mappings and keys from mdsal datastore.
869      */
870     private void restoreDaoFromDatastore() {
871         List<AuthenticationKey> authKeys = dsbe.getAllAuthenticationKeys();
872         List<Mapping> mappings = dsbe.getAllMappings(LogicalDatastoreType.CONFIGURATION);
873
874         /*
875          * XXX By default, the operational datastore is not persisted to disk, either at run-time, or on shutdown,
876          * so the following will have no effect (getLastUpdateTimestamp() will fail, since it's reading from
877          * the operational datastore, and even if it didn't getAllMappings() will fail anyway). According to rovarga it
878          * should be possible to turn on persistence for the operational datastore editing
879          * etc/opendaylight/karaf/05-clustering.xml, by setting <persistence>true</persistence>. At the time of writing
880          * the below code block that didn't seem to work though.
881          */
882         Long lastUpdateTimestamp = dsbe.getLastUpdateTimestamp();
883         if (lastUpdateTimestamp != null && System.currentTimeMillis() - lastUpdateTimestamp
884                 > ConfigIni.getInstance().getRegistrationValiditySb()) {
885             LOG.warn("Restore threshold passed, not restoring operational datastore into DAO");
886         } else {
887             mappings.addAll(dsbe.getAllMappings(LogicalDatastoreType.OPERATIONAL));
888         }
889         dsbe.removeLastUpdateTimestamp();
890
891         LOG.info("Restoring {} mappings and {} keys from datastore into DAO", mappings.size(), authKeys.size());
892
893         for (Mapping mapping : mappings) {
894             addMapping(mapping.getOrigin(), mapping.getMappingRecord().getEid(),
895                     new MappingData(mapping.getMappingRecord()));
896         }
897
898         for (AuthenticationKey authKey : authKeys) {
899             addAuthenticationKey(authKey.getEid(), authKey.getMappingAuthkey());
900         }
901     }
902
903     public void destroy() {
904         LOG.info("Mapping System is being destroyed!");
905         dsbe.saveLastUpdateTimestamp();
906     }
907
908     @Override
909     public String printMappings() {
910         sbMappingTimeoutService.removeExpiredMappings();
911
912         final StringBuilder sb = new StringBuilder();
913         sb.append("Policy map-cache\n----------------\n");
914         sb.append(pmc.printMappings());
915         sb.append("\nSouthbound map-cache\n--------------------\n");
916         sb.append(smc.printMappings());
917         return sb.toString();
918     }
919
920     @Override
921     public String prettyPrintMappings() {
922         sbMappingTimeoutService.removeExpiredMappings();
923
924         final StringBuilder sb = new StringBuilder();
925         sb.append("Policy map-cache\n----------------\n");
926         sb.append(pmc.prettyPrintMappings());
927         sb.append("\nSouthbound map-cache\n--------------------\n");
928         sb.append(smc.prettyPrintMappings());
929         sb.append("\nSubscribers\n-----------\n");
930         sb.append(prettyPrintSubscribers(subscriberdb));
931         return sb.toString();
932     }
933
934     private static String prettyPrintSubscribers(Map<Eid, Set<Subscriber>> subscribers) {
935         final StringBuilder sb = new StringBuilder();
936         for (Eid eid: subscribers.keySet()) {
937             sb.append("\n  ");
938             sb.append(LispAddressStringifier.getString(eid));
939             sb.append("\n");
940             sb.append(LispMapCacheStringifier.prettyPrintSubscriberSet(subscribers.get(eid), 4));
941             sb.append("\n");
942         }
943         return sb.toString();
944     }
945
946     @Override
947     public String printKeys() {
948         return akdb.printKeys();
949     }
950
951     @Override
952     public String prettyPrintKeys() {
953         return akdb.prettyPrintKeys();
954     }
955
956     public void cleanCaches() {
957         dao.removeAll();
958         subscriberdb.clear();
959         buildMapCaches();
960     }
961
962     public void cleanSBMappings() {
963         smc = new SimpleMapCache(sdao);
964     }
965
966     @Override
967     public void setIsMaster(boolean isMaster) {
968         this.isMaster = isMaster;
969     }
970
971     @Override
972     public boolean isMaster() {
973         return isMaster;
974     }
975 }