2 * Copyright (c) 2015, 2017 Cisco Systems, Inc. All rights reserved.
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
9 package org.opendaylight.lispflowmapping.implementation;
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;
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;
79 * The Mapping System coordinates caching of md-sal stored mappings and if so configured enables longest prefix match
82 * @author Florin Coras
83 * @author Lorand Jakab
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;
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;
103 private ISouthBoundMappingTimeoutService sbMappingTimeoutService;
105 public MappingSystem(ILispDAO dao, boolean iterateMask, NotificationPublishService nps, boolean mappingMerge) {
107 this.notificationPublishService = nps;
108 this.mappingMerge = mappingMerge;
111 sbMappingTimeoutService = new TimeBucketMappingTimeoutService(ConfigIni.getInstance()
112 .getNumberOfBucketsInTimeBucketWheel(), ConfigIni.getInstance().getRegistrationValiditySb(),
116 public void setDataStoreBackEnd(DataStoreBackEnd dataStoreBackEnd) {
117 this.dsbe = dataStoreBackEnd;
121 public void setMappingMerge(boolean mappingMerge) {
122 this.mappingMerge = mappingMerge;
126 public void setIterateMask(boolean iterate) {
127 LOG.error("Non-longest prefix match lookups are not properly supported, variable is set to true");
130 public void initialize() {
131 restoreDaoFromDatastore();
134 private void buildMapCaches() {
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
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);
152 public void updateMapping(MappingOrigin origin, Eid key, MappingData mappingData) {
153 addMapping(origin, key, mappingData, MappingChange.Updated);
157 public void addMapping(MappingOrigin origin, Eid key, MappingData mappingData) {
158 addMapping(origin, key, mappingData, MappingChange.Created);
161 private void addMapping(MappingOrigin origin, Eid key, MappingData mappingData, MappingChange changeType) {
163 sbMappingTimeoutService.removeExpiredMappings();
165 if (mappingData == null) {
166 LOG.warn("addMapping() called with null mapping, ignoring");
170 if (LOG.isDebugEnabled()) {
171 LOG.debug("DAO: Adding {} mapping for EID {}", origin, LispAddressStringifier.getString(key));
174 if (LOG.isTraceEnabled()) {
175 LOG.trace("mappingData = {}", mappingData.getString());
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));
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");
187 if (xtrId != null && mappingMerge) {
188 if (mappingData.isMergeEnabled()) {
189 smc.addMapping(key, xtrId, mappingData);
190 handleMergedMapping(key);
193 clearPresentXtrIdMappings(key);
194 smc.addMapping(key, xtrId, mappingData);
197 addOrRefreshMappingInTimeoutService(key, mappingData);
200 tableMap.get(origin).addMapping(key, mappingData);
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);
207 MappingRecord newMapping = getMappingRecord(getMapping(key));
209 handleAddMappingNotifications(origin, key, mappingData, oldMapping, newMapping, changeType);
212 private static MappingRecord getMappingRecord(MappingData mappingData) {
213 return (mappingData != null) ? mappingData.getRecord() : null;
216 @SuppressWarnings("unchecked")
217 private void clearPresentXtrIdMappings(Eid key) {
218 List<MappingData> allXtrMappingList = (List<MappingData>) (List<?>) smc.getAllXtrIdMappings(key);
220 if (((MappingData) smc.getMapping(key, (XtrId) null)).isMergeEnabled()) {
221 LOG.trace("Different xTRs have different merge configuration!");
224 for (MappingData mappingData : allXtrMappingList) {
225 removeSbXtrIdSpecificMapping(key, mappingData.getXtrId(), mappingData);
229 private void addOrRefreshMappingInTimeoutService(Eid key, MappingData mappingData) {
230 Integer oldBucketId = (Integer) smc.getData(key, SubKeys.TIME_BUCKET_ID);
231 Integer updatedBucketId;
233 if (oldBucketId != null) {
235 updatedBucketId = sbMappingTimeoutService.refreshMapping(key, mappingData, oldBucketId);
237 updatedBucketId = sbMappingTimeoutService.addMapping(key, mappingData);
240 smc.addData(key, SubKeys.TIME_BUCKET_ID, updatedBucketId);
243 private void handleSbNegativeMappings(Eid key) {
244 Set<Eid> childPrefixes = getSubtree(MappingOrigin.Southbound, key);
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);
260 for (Eid prefix : childPrefixes) {
261 handleSbNegativeMapping(prefix);
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);
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);
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);
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);
291 // If the new mapping has a different EID than what was just added (e.g., due to NB_AND_SB), notify those
293 if (newMapping != null && !newMapping.getEid().equals(key) && !newMapping.getEid().equals(dstKey)) {
294 notifyChange(newMapping.getEid(), newMapping, changeType);
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));
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);
323 recordBuilder.setAction(LispMessage.NEGATIVE_MAPPING_ACTION);
324 //if (getAuthenticationKey(eid) != null) {
325 // recordBuilder.setRecordTtl(TTL_RLOC_TIMED_OUT);
327 recordBuilder.setRecordTtl(TTL_NO_RLOC_KNOWN);
329 return recordBuilder.build();
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.
336 public void refreshMappingRegistration(Eid key, XtrId xtrId, Long timestamp) {
338 sbMappingTimeoutService.removeExpiredMappings();
340 if (timestamp == null) {
341 timestamp = System.currentTimeMillis();
343 MappingData mappingData = (MappingData) smc.getMapping(null, key);
344 if (mappingData != null) {
345 mappingData.setTimestamp(new Date(timestamp));
346 addOrRefreshMappingInTimeoutService(key, mappingData);
348 LOG.warn("Could not update timestamp for EID {}, no mapping found", LispAddressStringifier.getString(key));
350 if (mappingMerge && xtrId != null) {
351 MappingData xtrIdMappingData = (MappingData) smc.getMapping(key, xtrId);
352 if (xtrIdMappingData != null) {
353 xtrIdMappingData.setTimestamp(new Date(timestamp));
355 LOG.warn("Could not update timestamp for EID {} xTR-ID {}, no mapping found",
356 LispAddressStringifier.getString(key), LispAddressStringifier.getString(xtrId));
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>());
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!");
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) {
378 LOG.warn("Service Index should be 255 for simple IP RLOCs!");
381 } else if (rloc.getAddress() instanceof ExplicitLocatorPath) {
382 ExplicitLocatorPath elp = (ExplicitLocatorPath) rloc.getAddress();
383 List<Hop> hops = elp.getExplicitLocatorPath().getHop();
385 if (index < 0 || index > hops.size()) {
386 LOG.warn("Service Index out of bounds!");
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());
396 LOG.warn("Nothing to do with ServicePath mapping record");
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<>();
406 MappingData mergedMappingData = MappingMergeUtil.mergeXtrIdMappings(smc.getAllXtrIdMappings(key),
407 expiredMappingDataList, sourceRlocs);
409 for (MappingData mappingData : expiredMappingDataList) {
410 removeSbXtrIdSpecificMapping(key, mappingData.getXtrId(), mappingData);
413 if (mergedMappingData != null) {
414 smc.addMapping(key, mergedMappingData, sourceRlocs);
415 dsbe.addMapping(DSBEInputUtil.toMapping(MappingOrigin.Southbound, key, mergedMappingData));
416 addOrRefreshMappingInTimeoutService(key, mergedMappingData);
418 removeSbMapping(key, mergedMappingData);
420 return mergedMappingData;
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),
432 if (policy == IMappingService.LookupPolicy.NB_AND_SB) {
433 return getMappingNbSbIntersection(src, dst);
435 return getMappingNbFirst(src, dst);
440 public MappingData getMapping(Eid dst) {
441 return getMapping((Eid) null, dst);
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
449 return getMapping(src, dst);
452 return getSbMappingWithExpiration(src, dst, xtrId);
456 public MappingData getMapping(MappingOrigin origin, Eid key) {
457 if (origin.equals(MappingOrigin.Southbound)) {
458 return getSbMappingWithExpiration(null, key, null);
460 return (MappingData) tableMap.get(origin).getMapping(null, key);
463 private MappingData getMappingNbFirst(Eid src, Eid dst) {
465 // Default lookup policy is northboundFirst
466 //lookupPolicy == NB_FIRST
468 MappingData nbMappingData = (MappingData) pmc.getMapping(src, dst);
470 if (nbMappingData == null) {
471 return getSbMappingWithExpiration(src, dst, null);
473 if (dst.getAddress() instanceof ServicePath) {
474 return updateServicePathMappingRecord(nbMappingData, dst);
476 return nbMappingData;
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.
483 MappingData nbMappingData = (MappingData) pmc.getMapping(src, dst);
484 if (nbMappingData == null) {
485 return nbMappingData;
487 // no intersection for Service Path mappings
488 if (dst.getAddress() instanceof ServicePath) {
489 return updateServicePathMappingRecord(nbMappingData, dst);
491 MappingData sbMappingData = getSbMappingWithExpiration(src, dst, null);
492 if (sbMappingData == null) {
493 return nbMappingData;
495 // both NB and SB mappings exist. Compute intersection of the mappings
496 return MappingMergeUtil.computeNbSbIntersection(nbMappingData, sbMappingData);
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);
508 public MappingData handleSbExpiredMapping(Eid key, XtrId xtrId, MappingData mappingData) {
509 if (mappingMerge && mappingData.isMergeEnabled()) {
510 return handleMergedMapping(key);
514 removeSbXtrIdSpecificMapping(key, xtrId, mappingData);
516 removeSbMapping(key, mappingData);
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));
527 smc.removeMapping(key, xtrId);
528 dsbe.removeXtrIdMapping(DSBEInputUtil.toXtrIdMapping(mappingData));
531 private void removeSbMapping(Eid key, MappingData mappingData) {
532 if (mappingData != null && mappingData.getXtrId() != null) {
533 removeSbXtrIdSpecificMapping(key, mappingData.getXtrId(), mappingData);
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));
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);
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);
555 public Eid getWidestNegativePrefix(Eid key) {
556 if (!MaskUtil.isMaskable(key.getAddress())) {
557 LOG.warn("Widest negative prefix only makes sense for maskable addresses!");
561 // We assume that ILispMapCache#getWidestNegativeMapping() returns null for positive mappings, and 0/0
563 Eid nbPrefix = pmc.getWidestNegativeMapping(key);
564 if (nbPrefix == null) {
565 LOG.trace("getWidestNegativePrefix NB: positive mapping, returning null");
568 if (LOG.isTraceEnabled()) {
569 LOG.trace("getWidestNegativePrefix NB: {}", LispAddressStringifier.getString(nbPrefix));
572 Eid sbPrefix = smc.getWidestNegativeMapping(key);
573 if (sbPrefix == null) {
574 LOG.trace("getWidestNegativePrefix SB: positive mapping, returning null");
577 if (LOG.isTraceEnabled()) {
578 LOG.trace("getWidestNegativePrefix SB: {}", LispAddressStringifier.getString(sbPrefix));
581 // since prefixes overlap, just return the more specific (larger mask)
582 if (LispAddressUtil.getIpPrefixMask(nbPrefix) < LispAddressUtil.getIpPrefixMask(sbPrefix)) {
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();
596 return tableMap.get(origin).getSubtree(key);
600 public void removeMapping(MappingOrigin origin, Eid key) {
602 Set<Subscriber> subscribers = null;
603 Set<Subscriber> dstSubscribers = null;
604 MappingData mapping = (MappingData) tableMap.get(origin).getMapping(null, key);
606 if (LOG.isDebugEnabled()) {
607 LOG.debug("Removing mapping for EID {} from {}",
608 LispAddressStringifier.getString(key), origin);
610 if (LOG.isTraceEnabled() && mapping != null) {
611 LOG.trace(mapping.getString());
614 MappingRecord notificationMapping = null;
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);
626 removeSubscribersConditionally(origin, key);
628 if (origin == MappingOrigin.Southbound) {
629 removeFromSbTimeoutService(key);
632 if (origin == MappingOrigin.Southbound && mapping != null && mapping.isPositive().or(false)) {
633 mergeNegativePrefixes(key);
635 // mergeNegativePrefixes() above removes the mapping, so addNegativeMapping() will work correctly
636 tableMap.get(origin).removeMapping(key);
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);
648 public void notifyChange(Eid eid, MappingRecord mapping, MappingChange mappingChange) {
649 Set<Subscriber> subscribers = getSubscribers(eid);
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);
659 // No reason to send a notification when no subscribers exist
660 if (subscribers != null || dstSubscribers != null) {
661 publishNotification(mapping, eid, subscribers, dstSubscribers, mappingChange);
664 notifyChildren(eid, mapping, mappingChange);
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()) {
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);
689 private void publishNotification(MappingRecord mapping, Eid eid, Set<Subscriber> subscribers,
690 Set<Subscriber> dstSubscribers, MappingChange mappingChange) {
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!");
701 * Merges adjacent negative prefixes and notifies their subscribers.
703 private void mergeNegativePrefixes(Eid eid) {
704 LOG.debug("Merging negative prefixes starting from EID {}", LispAddressStringifier.getString(eid));
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<>();
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);
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);
727 previousNode = currentNode;
728 currentNode = smc.getVirtualParentSiblingPrefix(previousNode);
731 for (Eid key : mergedMappings.keySet()) {
732 removeSbMapping(key, mergedMappings.get(key));
734 smc.removeMapping(eid);
736 addNegativeMapping(getVirtualParent(previousNode));
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(),
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(),
751 return LispAddressUtil.asIpv6PrefixBinaryEid(eid, parentPrefix, parentPrefixLength);
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);
765 if (LOG.isDebugEnabled()) {
766 LOG.debug("Adding new subscriber {} for EID {}", subscriber.getString(),
767 LispAddressStringifier.getString(subscribedEid));
769 subscribers.add(subscriber);
770 addSubscribers(subscribedEid, subscribers);
773 private void addSubscribers(Eid address, Set<Subscriber> subscribers) {
774 LoggingUtil.logSubscribers(LOG, address, subscribers);
775 subscriberdb.put(address, subscribers);
779 public Set<Subscriber> getSubscribers(Eid address) {
780 if (LOG.isDebugEnabled()) {
781 LOG.debug("Retrieving subscribers for EID {}", LispAddressStringifier.getString(address));
784 Set<Subscriber> subscribers = subscriberdb.get(address);
785 LoggingUtil.logSubscribers(LOG, address, subscribers);
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.
794 private void removeSubscribersConditionally(MappingOrigin origin, Eid address) {
795 if (origin == MappingOrigin.Southbound) {
796 if (pmc.getData(address, SubKeys.RECORD) == null) {
797 removeSubscribers(address);
799 } else if (origin == MappingOrigin.Northbound) {
800 if (smc.getData(address, SubKeys.RECORD) == null) {
801 removeSubscribers(address);
806 private void removeSubscribers(Eid address) {
807 if (LOG.isDebugEnabled()) {
808 LOG.debug("Removing subscribers for EID {}", LispAddressStringifier.getString(address));
810 subscriberdb.remove(address);
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);
821 public MappingAuthkey getAuthenticationKey(Eid key) {
822 if (LOG.isDebugEnabled()) {
823 LOG.debug("Retrieving authentication key for {}", LispAddressStringifier.getString(key));
825 return akdb.getAuthenticationKey(key);
829 public void removeAuthenticationKey(Eid key) {
830 if (LOG.isDebugEnabled()) {
831 LOG.debug("Removing authentication key for {}", LispAddressStringifier.getString(key));
833 akdb.removeAuthenticationKey(key);
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);
842 tableMap.get(origin).addData(key, subKey, data);
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);
850 return tableMap.get(origin).getData(key, subKey);
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);
858 tableMap.get(origin).removeData(key, subKey);
862 public Eid getParentPrefix(Eid key) {
863 return smc.getParentPrefix(key);
868 * Restore all mappings and keys from mdsal datastore.
870 private void restoreDaoFromDatastore() {
871 List<AuthenticationKey> authKeys = dsbe.getAllAuthenticationKeys();
872 List<Mapping> mappings = dsbe.getAllMappings(LogicalDatastoreType.CONFIGURATION);
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.
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");
887 mappings.addAll(dsbe.getAllMappings(LogicalDatastoreType.OPERATIONAL));
889 dsbe.removeLastUpdateTimestamp();
891 LOG.info("Restoring {} mappings and {} keys from datastore into DAO", mappings.size(), authKeys.size());
893 for (Mapping mapping : mappings) {
894 addMapping(mapping.getOrigin(), mapping.getMappingRecord().getEid(),
895 new MappingData(mapping.getMappingRecord()));
898 for (AuthenticationKey authKey : authKeys) {
899 addAuthenticationKey(authKey.getEid(), authKey.getMappingAuthkey());
903 public void destroy() {
904 LOG.info("Mapping System is being destroyed!");
905 dsbe.saveLastUpdateTimestamp();
909 public String printMappings() {
910 sbMappingTimeoutService.removeExpiredMappings();
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();
921 public String prettyPrintMappings() {
922 sbMappingTimeoutService.removeExpiredMappings();
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();
934 private static String prettyPrintSubscribers(Map<Eid, Set<Subscriber>> subscribers) {
935 final StringBuilder sb = new StringBuilder();
936 for (Eid eid: subscribers.keySet()) {
938 sb.append(LispAddressStringifier.getString(eid));
940 sb.append(LispMapCacheStringifier.prettyPrintSubscriberSet(subscribers.get(eid), 4));
943 return sb.toString();
947 public String printKeys() {
948 return akdb.printKeys();
952 public String prettyPrintKeys() {
953 return akdb.prettyPrintKeys();
956 public void cleanCaches() {
958 subscriberdb.clear();
962 public void cleanSBMappings() {
963 smc = new SimpleMapCache(sdao);
967 public void setIsMaster(boolean isMaster) {
968 this.isMaster = isMaster;
972 public boolean isMaster() {