Merge "Switch to MD-SAL LISP address model"
[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 java.util.ArrayList;
12 import java.util.Date;
13 import java.util.EnumMap;
14 import java.util.HashSet;
15 import java.util.List;
16 import java.util.Set;
17 import org.opendaylight.controller.md.sal.binding.api.NotificationPublishService;
18 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
19 import org.opendaylight.lispflowmapping.config.ConfigIni;
20 import org.opendaylight.lispflowmapping.dsbackend.DataStoreBackEnd;
21 import org.opendaylight.lispflowmapping.implementation.timebucket.implementation.TimeBucketMappingTimeoutService;
22 import org.opendaylight.lispflowmapping.implementation.timebucket.interfaces.ISouthBoundMappingTimeoutService;
23 import org.opendaylight.lispflowmapping.implementation.util.DSBEInputUtil;
24 import org.opendaylight.lispflowmapping.implementation.util.MSNotificationInputUtil;
25 import org.opendaylight.lispflowmapping.implementation.util.MappingMergeUtil;
26 import org.opendaylight.lispflowmapping.interfaces.dao.ILispDAO;
27 import org.opendaylight.lispflowmapping.interfaces.dao.SubKeys;
28 import org.opendaylight.lispflowmapping.interfaces.dao.Subscriber;
29 import org.opendaylight.lispflowmapping.interfaces.mapcache.IAuthKeyDb;
30 import org.opendaylight.lispflowmapping.interfaces.mapcache.ILispMapCache;
31 import org.opendaylight.lispflowmapping.interfaces.mapcache.IMapCache;
32 import org.opendaylight.lispflowmapping.interfaces.mapcache.IMappingSystem;
33 import org.opendaylight.lispflowmapping.interfaces.mappingservice.IMappingService;
34 import org.opendaylight.lispflowmapping.lisp.type.LispMessage;
35 import org.opendaylight.lispflowmapping.lisp.type.MappingData;
36 import org.opendaylight.lispflowmapping.lisp.util.LispAddressStringifier;
37 import org.opendaylight.lispflowmapping.lisp.util.LispAddressUtil;
38 import org.opendaylight.lispflowmapping.lisp.util.MaskUtil;
39 import org.opendaylight.lispflowmapping.lisp.util.SourceDestKeyHelper;
40 import org.opendaylight.lispflowmapping.mapcache.AuthKeyDb;
41 import org.opendaylight.lispflowmapping.mapcache.MultiTableMapCache;
42 import org.opendaylight.lispflowmapping.mapcache.SimpleMapCache;
43 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.SimpleAddress;
44 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.ExplicitLocatorPath;
45 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.Ipv4;
46 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.Ipv6;
47 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.ServicePath;
48 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.SourceDestKey;
49 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;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.inet.binary.types.rev160303.IpAddressBinary;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.binary.address.types.rev160504.Ipv4PrefixBinaryAfi;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.binary.address.types.rev160504.Ipv6PrefixBinaryAfi;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.binary.address.types.rev160504.augmented.lisp.address.address.Ipv4PrefixBinary;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.binary.address.types.rev160504.augmented.lisp.address.address.Ipv6PrefixBinary;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.XtrId;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.eid.container.Eid;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.locatorrecords.LocatorRecord;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.locatorrecords.LocatorRecordBuilder;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.authkey.container.MappingAuthkey;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.record.container.MappingRecord;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.record.container.MappingRecordBuilder;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.rloc.container.Rloc;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.mappingservice.rev150906.MappingChange;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.mappingservice.rev150906.MappingChanged;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.mappingservice.rev150906.MappingOrigin;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.mappingservice.rev150906.db.instance.AuthenticationKey;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.mappingservice.rev150906.db.instance.Mapping;
68 import org.slf4j.Logger;
69 import org.slf4j.LoggerFactory;
70
71 /**
72  * The Mapping System coordinates caching of md-sal stored mappings and if so configured enables longest prefix match
73  * mapping lookups.
74  *
75  * @author Florin Coras
76  * @author Lorand Jakab
77  *
78  */
79 public class MappingSystem implements IMappingSystem {
80     private static final Logger LOG = LoggerFactory.getLogger(MappingSystem.class);
81     private static final String AUTH_KEY_TABLE = "authentication";
82     //private static final int TTL_RLOC_TIMED_OUT = 1;
83     private static final int TTL_NO_RLOC_KNOWN = ConfigIni.getInstance().getNegativeMappingTTL();
84     private NotificationPublishService notificationPublishService;
85     private boolean mappingMerge;
86     private ILispDAO dao;
87     private ILispDAO sdao;
88     private ILispMapCache smc;
89     private IMapCache pmc;
90     private IAuthKeyDb akdb;
91     private final EnumMap<MappingOrigin, IMapCache> tableMap = new EnumMap<>(MappingOrigin.class);
92     private DataStoreBackEnd dsbe;
93     private boolean isMaster = false;
94
95     private ISouthBoundMappingTimeoutService sbMappingTimeoutService;
96
97     public MappingSystem(ILispDAO dao, boolean iterateMask, NotificationPublishService nps, boolean mappingMerge) {
98         this.dao = dao;
99         this.notificationPublishService = nps;
100         this.mappingMerge = mappingMerge;
101         buildMapCaches();
102
103         sbMappingTimeoutService = new TimeBucketMappingTimeoutService(ConfigIni.getInstance()
104                 .getNumberOfBucketsInTimeBucketWheel(), ConfigIni.getInstance().getRegistrationValiditySb(),
105                 this);
106     }
107
108     public void setDataStoreBackEnd(DataStoreBackEnd dsbe) {
109         this.dsbe = dsbe;
110     }
111
112     @Override
113     public void setMappingMerge(boolean mappingMerge) {
114         this.mappingMerge = mappingMerge;
115     }
116
117     @Override
118     public void setIterateMask(boolean iterate) {
119         LOG.error("Non-longest prefix match lookups are not properly supported, variable is set to true");
120     }
121
122     public void initialize() {
123         restoreDaoFromDatastore();
124     }
125
126     private void buildMapCaches() {
127         /*
128          * There exists a direct relationship between MappingOrigins and the tables that are part of the MappingSystem.
129          * Therefore, if a new origin is added, probably a new table should be instantiated here as well. Here we
130          * instantiate a SimpleMapCache for southbound originated LISP mappings and a MultiTableMapCache for northbound
131          * originated mappings. Use of FlatMapCache would be possible when no longest prefix match is needed at all,
132          * but that option is no longer supported in the code, since it was never tested and may lead to unexpected
133          * results.
134          */
135         sdao = dao.putTable(MappingOrigin.Southbound.toString());
136         pmc = new MultiTableMapCache(dao.putTable(MappingOrigin.Northbound.toString()));
137         smc = new SimpleMapCache(sdao);
138         akdb = new AuthKeyDb(dao.putTable(AUTH_KEY_TABLE));
139         tableMap.put(MappingOrigin.Northbound, pmc);
140         tableMap.put(MappingOrigin.Southbound, smc);
141     }
142
143     public void addMapping(MappingOrigin origin, Eid key, MappingData mappingData) {
144
145         sbMappingTimeoutService.removeExpiredMappings();
146
147         if (mappingData == null) {
148             LOG.warn("addMapping() called with null mapping, ignoring");
149             return;
150         }
151
152         if (origin == MappingOrigin.Southbound) {
153             XtrId xtrId = mappingData.getXtrId();
154             if (xtrId == null && mappingMerge && mappingData.isMergeEnabled()) {
155                 LOG.warn("addMapping() called will null xTR-ID in MappingRecord, while merge is set, ignoring");
156                 return;
157             }
158             if (xtrId != null && mappingMerge) {
159                 if (mappingData.isMergeEnabled()) {
160                     smc.addMapping(key, xtrId, mappingData);
161                     handleMergedMapping(key);
162                     return;
163                 } else {
164                     clearPresentXtrIdMappings(key);
165                     smc.addMapping(key, xtrId, mappingData);
166                 }
167             }
168             addOrRefreshMappingInTimeoutService(key, mappingData);
169         }
170
171         tableMap.get(origin).addMapping(key, mappingData);
172     }
173
174     @SuppressWarnings("unchecked")
175     private void clearPresentXtrIdMappings(Eid key) {
176         List<MappingData> allXtrMappingList = (List<MappingData>) (List<?>) smc.getAllXtrIdMappings(key);
177
178         if (((MappingData) smc.getMapping(key, (XtrId) null)).isMergeEnabled()) {
179             LOG.trace("Different xTRs have different merge configuration!");
180         }
181
182         for (MappingData mappingData : allXtrMappingList) {
183             removeSbXtrIdSpecificMapping(key, mappingData.getXtrId(), mappingData);
184         }
185     }
186
187     private void addOrRefreshMappingInTimeoutService(Eid key, MappingData mappingData) {
188         Integer oldBucketId = (Integer) smc.getData(key, SubKeys.TIME_BUCKET_ID);
189         Integer updatedBucketId;
190
191         if (oldBucketId != null) {
192             //refresh mapping
193             updatedBucketId = sbMappingTimeoutService.refreshMapping(key, mappingData, oldBucketId);
194         } else {
195             updatedBucketId = sbMappingTimeoutService.addMapping(key, mappingData);
196         }
197
198         smc.addData(key, SubKeys.TIME_BUCKET_ID, updatedBucketId);
199     }
200
201     @Override
202     public MappingData addNegativeMapping(Eid key) {
203         MappingRecord mapping = buildNegativeMapping(key);
204         MappingData mappingData = new MappingData(mapping);
205         smc.addMapping(mapping.getEid(), mappingData);
206         dsbe.addMapping(DSBEInputUtil.toMapping(MappingOrigin.Southbound, mapping.getEid(), null, mappingData));
207         return mappingData;
208     }
209
210     private MappingRecord buildNegativeMapping(Eid eid) {
211         MappingRecordBuilder recordBuilder = new MappingRecordBuilder();
212         recordBuilder.setAuthoritative(false);
213         recordBuilder.setMapVersion((short) 0);
214         recordBuilder.setEid(eid);
215         if (eid.getAddressType().equals(Ipv4PrefixBinaryAfi.class)
216                 || eid.getAddressType().equals(Ipv6PrefixBinaryAfi.class)) {
217             Eid widestNegativePrefix = getWidestNegativePrefix(eid);
218             if (widestNegativePrefix != null) {
219                 recordBuilder.setEid(widestNegativePrefix);
220             }
221         }
222         recordBuilder.setAction(LispMessage.NEGATIVE_MAPPING_ACTION);
223         //if (getAuthenticationKey(eid) != null) {
224         //    recordBuilder.setRecordTtl(TTL_RLOC_TIMED_OUT);
225         //} else {
226         recordBuilder.setRecordTtl(TTL_NO_RLOC_KNOWN);
227         //}
228         return recordBuilder.build();
229     }
230
231     /*
232      * Since this method is only called when there is a hit in the southbound Map-Register cache, and that cache is
233      * not used when merge is on, it's OK to ignore the effects of timestamp changes on merging for now.
234      */
235     public void refreshMappingRegistration(Eid key, XtrId xtrId, Long timestamp) {
236
237         sbMappingTimeoutService.removeExpiredMappings();
238
239         if (timestamp == null) {
240             timestamp = System.currentTimeMillis();
241         }
242         MappingData mappingData = (MappingData) smc.getMapping(null, key);
243         if (mappingData != null) {
244             mappingData.setTimestamp(new Date(timestamp));
245             addOrRefreshMappingInTimeoutService(key, mappingData);
246         } else {
247             LOG.warn("Could not update timestamp for EID {}, no mapping found", LispAddressStringifier.getString(key));
248         }
249         if (mappingMerge && xtrId != null) {
250             MappingData xtrIdMappingData = (MappingData) smc.getMapping(key, xtrId);
251             if (xtrIdMappingData != null) {
252                 xtrIdMappingData.setTimestamp(new Date(timestamp));
253             } else {
254                 LOG.warn("Could not update timestamp for EID {} xTR-ID {}, no mapping found",
255                         LispAddressStringifier.getString(key), LispAddressStringifier.getString(xtrId));
256             }
257         }
258     }
259
260     private MappingData updateServicePathMappingRecord(MappingData mappingData, Eid eid) {
261         // keep properties of original record
262         MappingRecordBuilder recordBuilder = new MappingRecordBuilder(mappingData.getRecord());
263         recordBuilder.setLocatorRecord(new ArrayList<LocatorRecord>());
264
265         // there should only be one locator record
266         if (mappingData.getRecord().getLocatorRecord().size() != 1) {
267             LOG.warn("MappingRecord associated to ServicePath EID has more than one locator!");
268             return mappingData;
269         }
270
271         LocatorRecord locatorRecord = mappingData.getRecord().getLocatorRecord().get(0);
272         long serviceIndex = ((ServicePath) eid.getAddress()).getServicePath().getServiceIndex();
273         int index = LispAddressUtil.STARTING_SERVICE_INDEX - (int) serviceIndex;
274         Rloc rloc = locatorRecord.getRloc();
275         if (rloc.getAddress() instanceof Ipv4 || rloc.getAddress() instanceof Ipv6) {
276             if (index != 0) {
277                 LOG.warn("Service Index should be 255 for simple IP RLOCs!");
278             }
279             return mappingData;
280         } else if (rloc.getAddress() instanceof ExplicitLocatorPath) {
281             ExplicitLocatorPath elp = (ExplicitLocatorPath) rloc.getAddress();
282             List<Hop> hops = elp.getExplicitLocatorPath().getHop();
283
284             if (index < 0 || index > hops.size())  {
285                 LOG.warn("Service Index out of bounds!");
286                 return mappingData;
287             }
288
289             SimpleAddress nextHop = hops.get(index).getAddress();
290             LocatorRecordBuilder lrb = new LocatorRecordBuilder(locatorRecord);
291             lrb.setRloc(LispAddressUtil.toRloc(nextHop));
292             recordBuilder.getLocatorRecord().add(lrb.build());
293             return new MappingData(recordBuilder.build());
294         } else {
295             LOG.warn("Nothing to do with ServicePath mapping record");
296             return mappingData;
297         }
298     }
299
300     private MappingData handleMergedMapping(Eid key) {
301         List<MappingData> expiredMappingDataList = new ArrayList<>();
302         Set<IpAddressBinary> sourceRlocs = new HashSet<>();
303
304         MappingData mergedMappingData = MappingMergeUtil.mergeXtrIdMappings(smc.getAllXtrIdMappings(key),
305                 expiredMappingDataList, sourceRlocs);
306
307         for (MappingData mappingData : expiredMappingDataList) {
308             removeSbXtrIdSpecificMapping(key, mappingData.getXtrId(), mappingData);
309         }
310
311         if (mergedMappingData != null) {
312             smc.addMapping(key, mergedMappingData, sourceRlocs);
313             dsbe.addMapping(DSBEInputUtil.toMapping(MappingOrigin.Southbound, key, mergedMappingData));
314             addOrRefreshMappingInTimeoutService(key, mergedMappingData);
315         } else {
316             removeSbMapping(key, mergedMappingData);
317         }
318         return mergedMappingData;
319     }
320
321     @Override
322     public MappingData getMapping(Eid src, Eid dst) {
323         // NOTE: Currently we have two lookup algorithms implemented, which are configurable
324
325         if (ConfigIni.getInstance().getLookupPolicy() == IMappingService.LookupPolicy.NB_AND_SB) {
326             return getMappingNbSbIntersection(src, dst);
327         } else {
328             return getMappingNbFirst(src, dst);
329         }
330     }
331
332     @Override
333     public MappingData getMapping(Eid dst) {
334         return getMapping((Eid) null, dst);
335     }
336
337     @Override
338     public MappingData getMapping(Eid src, Eid dst, XtrId xtrId) {
339         // Note: If xtrId is null, we need to go through regular policy checking else Policy doesn't matter
340
341         if (xtrId == null) {
342             return getMapping(src, dst);
343         }
344
345         return getSbMappingWithExpiration(src, dst, xtrId);
346     }
347
348     @Override
349     public MappingData getMapping(MappingOrigin origin, Eid key) {
350         if (origin.equals(MappingOrigin.Southbound)) {
351             return getSbMappingWithExpiration(null, key, null);
352         }
353         return (MappingData) tableMap.get(origin).getMapping(null, key);
354     }
355
356     private MappingData getMappingNbFirst(Eid src, Eid dst) {
357
358         // Default lookup policy is northboundFirst
359         //lookupPolicy == NB_FIRST
360
361         MappingData nbMappingData = (MappingData) pmc.getMapping(src, dst);
362
363         if (nbMappingData == null) {
364             return getSbMappingWithExpiration(src, dst, null);
365         }
366         if (dst.getAddress() instanceof ServicePath) {
367             return updateServicePathMappingRecord(nbMappingData, dst);
368         }
369         return nbMappingData;
370     }
371
372     private MappingData getMappingNbSbIntersection(Eid src, Eid dst) {
373         //lookupPolicy == NB_AND_SB, we return intersection
374         //of NB and SB mappings, or NB mapping if intersection is empty.
375
376         MappingData nbMappingData = (MappingData) pmc.getMapping(src, dst);
377         if (nbMappingData == null) {
378             return nbMappingData;
379         }
380         // no intersection for Service Path mappings
381         if (dst.getAddress() instanceof ServicePath) {
382             return updateServicePathMappingRecord(nbMappingData, dst);
383         }
384         MappingData sbMappingData = getSbMappingWithExpiration(src, dst, null);
385         if (sbMappingData == null) {
386             return nbMappingData;
387         }
388         // both NB and SB mappings exist. Compute intersection of the mappings
389         return MappingMergeUtil.computeNbSbIntersection(nbMappingData, sbMappingData);
390     }
391
392     private MappingData getSbMappingWithExpiration(Eid src, Eid dst, XtrId xtrId) {
393         MappingData mappingData = (MappingData) smc.getMapping(dst, xtrId);
394         if (mappingData != null && MappingMergeUtil.mappingIsExpired(mappingData)) {
395             return handleSbExpiredMapping(dst, xtrId, mappingData);
396         } else {
397             return mappingData;
398         }
399     }
400
401     public MappingData handleSbExpiredMapping(Eid key, XtrId xtrId, MappingData mappingData) {
402         if (mappingMerge && mappingData.isMergeEnabled()) {
403             return handleMergedMapping(key);
404         }
405
406         if (xtrId != null) {
407             removeSbXtrIdSpecificMapping(key, xtrId, mappingData);
408         } else {
409             removeSbMapping(key, mappingData);
410         }
411         return null;
412     }
413
414     private void removeSbXtrIdSpecificMapping(Eid key, XtrId xtrId, MappingData mappingData) {
415         smc.removeMapping(key, xtrId);
416         dsbe.removeXtrIdMapping(DSBEInputUtil.toXtrIdMapping(mappingData));
417     }
418
419     @SuppressWarnings("unchecked")
420     private void removeSbMapping(Eid key, MappingData mappingData) {
421         if (mappingData != null && mappingData.getXtrId() != null) {
422             removeSbXtrIdSpecificMapping(key, mappingData.getXtrId(), mappingData);
423         }
424
425         removeFromSbTimeoutService(key);
426         Set<Subscriber> subscribers = (Set<Subscriber>) getData(MappingOrigin.Southbound, key, SubKeys.SUBSCRIBERS);
427         smc.removeMapping(key);
428         dsbe.removeMapping(DSBEInputUtil.toMapping(MappingOrigin.Southbound, key, mappingData));
429         notifyChange(mappingData, subscribers, null, MappingChange.Removed);
430     }
431
432     private void removeFromSbTimeoutService(Eid key) {
433         Integer bucketId = (Integer) smc.getData(key, SubKeys.TIME_BUCKET_ID);
434         if (bucketId != null) {
435             sbMappingTimeoutService.removeMappingFromTimeoutService(key, bucketId);
436         }
437     }
438
439     @Override
440     public Eid getWidestNegativePrefix(Eid key) {
441         if (!MaskUtil.isMaskable(key.getAddress())) {
442             LOG.warn("Widest negative prefix only makes sense for maskable addresses!");
443             return null;
444         }
445
446         // We assume that ILispMapCache#getWidestNegativeMapping() returns null for positive mappings, and 0/0
447         // for empty cache.
448         Eid nbPrefix = pmc.getWidestNegativeMapping(key);
449         if (nbPrefix == null) {
450             LOG.trace("getWidestNegativePrefix NB: positive mapping, returning null");
451             return null;
452         }
453         if (LOG.isTraceEnabled()) {
454             LOG.trace("getWidestNegativePrefix NB: {}", LispAddressStringifier.getString(nbPrefix));
455         }
456
457         Eid sbPrefix = smc.getWidestNegativeMapping(key);
458         if (sbPrefix == null) {
459             LOG.trace("getWidestNegativePrefix SB: positive mapping, returning null");
460             return null;
461         }
462         if (LOG.isTraceEnabled()) {
463             LOG.trace("getWidestNegativePrefix SB: {}", LispAddressStringifier.getString(sbPrefix));
464         }
465
466         // since prefixes overlap, just return the more specific (larger mask)
467         if (LispAddressUtil.getIpPrefixMask(nbPrefix) < LispAddressUtil.getIpPrefixMask(sbPrefix)) {
468             return sbPrefix;
469         } else {
470             return nbPrefix;
471         }
472     }
473
474     @Override
475     @SuppressWarnings("unchecked")
476     public void removeMapping(MappingOrigin origin, Eid key) {
477         Set<Subscriber> subscribers = null;
478         Set<Subscriber> dstSubscribers = null;
479         MappingData mapping = (MappingData) tableMap.get(origin).getMapping(null, key);
480
481         if (mapping != null) {
482             MappingData notificationMapping = mapping;
483             subscribers = (Set<Subscriber>) getData(MappingOrigin.Southbound, key, SubKeys.SUBSCRIBERS);
484             // For SrcDst LCAF also send SMRs to Dst prefix
485             if (key.getAddress() instanceof SourceDestKey) {
486                 Eid dstAddr = SourceDestKeyHelper.getDstBinary(key);
487                 dstSubscribers = (Set<Subscriber>) getData(MappingOrigin.Southbound, dstAddr, SubKeys.SUBSCRIBERS);
488                 if (!(mapping.getRecord().getEid().getAddress() instanceof SourceDestKey)) {
489                     notificationMapping = new MappingData(new MappingRecordBuilder().setEid(key).build());
490                 }
491             }
492             notifyChange(notificationMapping, subscribers, dstSubscribers, MappingChange.Removed);
493         }
494
495         if (origin == MappingOrigin.Northbound) {
496             removeData(MappingOrigin.Southbound, key, SubKeys.SUBSCRIBERS);
497         }
498
499         if (origin == MappingOrigin.Southbound) {
500             removeFromSbTimeoutService(key);
501             if (mapping != null && mapping.isPositive().or(false)) {
502                 mergeNegativePrefixes(key);
503             }
504         }
505         tableMap.get(origin).removeMapping(key);
506     }
507
508     private void notifyChange(MappingData mapping, Set<Subscriber> subscribers, Set<Subscriber> dstSubscribers,
509             MappingChange mappingChange) {
510         MappingChanged notification = MSNotificationInputUtil.toMappingChanged(mapping, subscribers, dstSubscribers,
511                 mappingChange);
512         try {
513             notificationPublishService.putNotification(notification);
514         } catch (InterruptedException e) {
515             LOG.warn("Notification publication interrupted!");
516         }
517     }
518
519
520     /*
521      * Merges adjacent negative prefixes and notifies their subscribers.
522      */
523     private void mergeNegativePrefixes(Eid eid) {
524         // If prefix sibling has a negative mapping, save its subscribers
525         Eid sibling = smc.getSiblingPrefix(eid);
526         MappingData mapping = (MappingData) smc.getMapping(null, sibling);
527         if (mapping != null && mapping.isNegative().or(false)) {
528             removeSbMapping(sibling, mapping);
529         } else {
530             return;
531         }
532
533         Eid currentNode = sibling;
534         Eid previousNode = sibling;
535         while ((currentNode = smc.getVirtualParentSiblingPrefix(currentNode)) != null) {
536             mapping = (MappingData) smc.getMapping(null, currentNode);
537             if (mapping != null && mapping.isNegative().or(false)) {
538                 removeSbMapping(currentNode, mapping);
539             } else {
540                 break;
541             }
542             previousNode = currentNode;
543         }
544         addNegativeMapping(getVirtualParent(previousNode));
545     }
546
547     private static Eid getVirtualParent(Eid eid) {
548         if (eid.getAddress() instanceof Ipv4PrefixBinary) {
549             Ipv4PrefixBinary prefix = (Ipv4PrefixBinary) eid.getAddress();
550             short parentPrefixLength = (short) (prefix.getIpv4MaskLength() - 1);
551             byte[] parentPrefix = MaskUtil.normalizeByteArray(prefix.getIpv4AddressBinary().getValue(),
552                     parentPrefixLength);
553             return LispAddressUtil.asIpv4PrefixBinaryEid(eid, parentPrefix, parentPrefixLength);
554         } else if (eid.getAddress() instanceof Ipv6PrefixBinary) {
555             Ipv6PrefixBinary prefix = (Ipv6PrefixBinary) eid.getAddress();
556             short parentPrefixLength = (short) (prefix.getIpv6MaskLength() - 1);
557             byte[] parentPrefix = MaskUtil.normalizeByteArray(prefix.getIpv6AddressBinary().getValue(),
558                     parentPrefixLength);
559             return LispAddressUtil.asIpv6PrefixBinaryEid(eid, parentPrefix, parentPrefixLength);
560         }
561         return null;
562     }
563
564     @Override
565     public void addAuthenticationKey(Eid key, MappingAuthkey authKey) {
566         LOG.debug("Adding authentication key '{}' with key-ID {} for {}", authKey.getKeyString(), authKey.getKeyType(),
567                 LispAddressStringifier.getString(key));
568         akdb.addAuthenticationKey(key, authKey);
569     }
570
571     @Override
572     public MappingAuthkey getAuthenticationKey(Eid key) {
573         if (LOG.isDebugEnabled()) {
574             LOG.debug("Retrieving authentication key for {}", LispAddressStringifier.getString(key));
575         }
576         return akdb.getAuthenticationKey(key);
577     }
578
579     @Override
580     public void removeAuthenticationKey(Eid key) {
581         if (LOG.isDebugEnabled()) {
582             LOG.debug("Removing authentication key for {}", LispAddressStringifier.getString(key));
583         }
584         akdb.removeAuthenticationKey(key);
585     }
586
587     @Override
588     public void addData(MappingOrigin origin, Eid key, String subKey, Object data) {
589         if (LOG.isDebugEnabled()) {
590             LOG.debug("Add data of {} for key {} and subkey {}", data.getClass(),
591                     LispAddressStringifier.getString(key), subKey);
592         }
593         tableMap.get(origin).addData(key, subKey, data);
594     }
595
596     @Override
597     public Object getData(MappingOrigin origin, Eid key, String subKey) {
598         if (LOG.isDebugEnabled()) {
599             LOG.debug("Retrieving data for key {} and subkey {}", LispAddressStringifier.getString(key), subKey);
600         }
601         return tableMap.get(origin).getData(key, subKey);
602     }
603
604     @Override
605     public void removeData(MappingOrigin origin, Eid key, String subKey) {
606         if (LOG.isDebugEnabled()) {
607             LOG.debug("Removing data for key {} and subkey {}", LispAddressStringifier.getString(key), subKey);
608         }
609         tableMap.get(origin).removeData(key, subKey);
610     }
611
612     @Override
613     public Eid getParentPrefix(Eid key) {
614         return smc.getParentPrefix(key);
615     }
616
617
618     /**
619      * Restore all mappings and keys from mdsal datastore.
620      */
621     private void restoreDaoFromDatastore() {
622         List<AuthenticationKey> authKeys = dsbe.getAllAuthenticationKeys();
623         List<Mapping> mappings = dsbe.getAllMappings(LogicalDatastoreType.CONFIGURATION);
624
625         /*
626          * XXX By default, the operational datastore is not persisted to disk, either at run-time, or on shutdown,
627          * so the following will have no effect (getLastUpdateTimestamp() will fail, since it's reading from
628          * the operational datastore, and even if it didn't getAllMappings() will fail anyway). According to rovarga it
629          * should be possible to turn on persistence for the operational datastore editing
630          * etc/opendaylight/karaf/05-clustering.xml, by setting <persistence>true</persistence>. At the time of writing
631          * the below code block that didn't seem to work though.
632          */
633         Long lastUpdateTimestamp = dsbe.getLastUpdateTimestamp();
634         if (lastUpdateTimestamp != null && System.currentTimeMillis() - lastUpdateTimestamp
635                 > ConfigIni.getInstance().getRegistrationValiditySb()) {
636             LOG.warn("Restore threshold passed, not restoring operational datastore into DAO");
637         } else {
638             mappings.addAll(dsbe.getAllMappings(LogicalDatastoreType.OPERATIONAL));
639         }
640         dsbe.removeLastUpdateTimestamp();
641
642         LOG.info("Restoring {} mappings and {} keys from datastore into DAO", mappings.size(), authKeys.size());
643
644         for (Mapping mapping : mappings) {
645             addMapping(mapping.getOrigin(), mapping.getMappingRecord().getEid(),
646                     new MappingData(mapping.getMappingRecord()));
647         }
648
649         for (AuthenticationKey authKey : authKeys) {
650             addAuthenticationKey(authKey.getEid(), authKey.getMappingAuthkey());
651         }
652     }
653
654     public void destroy() {
655         LOG.info("Mapping System is being destroyed!");
656         dsbe.saveLastUpdateTimestamp();
657     }
658
659     @Override
660     public String printMappings() {
661         final StringBuffer sb = new StringBuffer();
662         sb.append("Policy map-cache\n----------------\n");
663         sb.append(pmc.printMappings());
664         sb.append("\nSouthbound map-cache\n--------------------\n");
665         sb.append(smc.printMappings());
666         return sb.toString();
667     }
668
669     @Override
670     public String prettyPrintMappings() {
671         final StringBuffer sb = new StringBuffer();
672         sb.append("Policy map-cache\n----------------\n");
673         sb.append(pmc.prettyPrintMappings());
674         sb.append("\nSouthbound map-cache\n--------------------\n");
675         sb.append(smc.prettyPrintMappings());
676         return sb.toString();
677     }
678
679     @Override
680     public String printKeys() {
681         return akdb.printKeys();
682     }
683
684     @Override
685     public String prettyPrintKeys() {
686         return akdb.prettyPrintKeys();
687     }
688
689     public void cleanCaches() {
690         dao.removeAll();
691         buildMapCaches();
692     }
693
694     public void cleanSBMappings() {
695         smc = new SimpleMapCache(sdao);
696     }
697
698     @Override
699     public void setIsMaster(boolean isMaster) {
700         this.isMaster = isMaster;
701     }
702
703     @Override
704     public boolean isMaster() {
705         return isMaster;
706     }
707 }