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.lispflowmapping.config.ConfigIni;
23 import org.opendaylight.lispflowmapping.dsbackend.DataStoreBackEnd;
24 import org.opendaylight.lispflowmapping.implementation.timebucket.implementation.TimeBucketMappingTimeoutService;
25 import org.opendaylight.lispflowmapping.implementation.timebucket.interfaces.ISouthBoundMappingTimeoutService;
26 import org.opendaylight.lispflowmapping.implementation.util.DSBEInputUtil;
27 import org.opendaylight.lispflowmapping.implementation.util.LoggingUtil;
28 import org.opendaylight.lispflowmapping.implementation.util.MSNotificationInputUtil;
29 import org.opendaylight.lispflowmapping.implementation.util.MappingMergeUtil;
30 import org.opendaylight.lispflowmapping.interfaces.dao.ILispDAO;
31 import org.opendaylight.lispflowmapping.interfaces.dao.SubKeys;
32 import org.opendaylight.lispflowmapping.interfaces.dao.Subscriber;
33 import org.opendaylight.lispflowmapping.interfaces.mapcache.IAuthKeyDb;
34 import org.opendaylight.lispflowmapping.interfaces.mapcache.ILispMapCache;
35 import org.opendaylight.lispflowmapping.interfaces.mapcache.IMapCache;
36 import org.opendaylight.lispflowmapping.interfaces.mapcache.IMappingSystem;
37 import org.opendaylight.lispflowmapping.interfaces.mappingservice.IMappingService;
38 import org.opendaylight.lispflowmapping.lisp.type.LispMessage;
39 import org.opendaylight.lispflowmapping.lisp.type.MappingData;
40 import org.opendaylight.lispflowmapping.lisp.util.LispAddressStringifier;
41 import org.opendaylight.lispflowmapping.lisp.util.LispAddressUtil;
42 import org.opendaylight.lispflowmapping.lisp.util.MappingRecordUtil;
43 import org.opendaylight.lispflowmapping.lisp.util.MaskUtil;
44 import org.opendaylight.lispflowmapping.lisp.util.SourceDestKeyHelper;
45 import org.opendaylight.lispflowmapping.mapcache.AuthKeyDb;
46 import org.opendaylight.lispflowmapping.mapcache.MultiTableMapCache;
47 import org.opendaylight.lispflowmapping.mapcache.SimpleMapCache;
48 import org.opendaylight.lispflowmapping.mapcache.lisp.LispMapCacheStringifier;
49 import org.opendaylight.mdsal.binding.api.NotificationPublishService;
50 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
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 final NotificationPublishService notificationPublishService;
92 private boolean mappingMerge;
93 private final ILispDAO dao;
94 private ILispDAO sdao;
95 private ILispMapCache smc;
96 private IMapCache pmc;
97 private final 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 final 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 {}: {}",
247 LispAddressStringifier.getString(key),
248 LispAddressStringifier.getString(childPrefixes));
250 for (Eid prefix : childPrefixes) {
251 handleSbNegativeMapping(prefix);
254 Eid parentPrefix = smc.getCoveringLessSpecific(key);
255 LOG.trace("handleSbNegativeMappings(): parent prefix for EID {}: {}",
256 LispAddressStringifier.getString(key),
257 LispAddressStringifier.getString(parentPrefix));
258 handleSbNegativeMapping(parentPrefix);
261 private void handleSbNegativeMapping(Eid key) {
262 MappingData mappingData = getSbMappingWithExpiration(null, key, null);
263 if (mappingData != null && mappingData.isNegative().or(false)) {
264 removeSbMapping(mappingData.getRecord().getEid(), mappingData);
268 private void handleAddMappingNotifications(MappingOrigin origin, Eid key, MappingData mappingData,
269 MappingRecord oldMapping, MappingRecord newMapping,
270 MappingChange changeType) {
271 // Non-southbound origins are MD-SAL first, so they only get to call addMapping() if there is a change
272 // Southbound is different, so we need to check if there is a change in the mapping. This check takes into
273 // account policy as well
274 if (origin != MappingOrigin.Southbound || MappingRecordUtil.mappingChanged(oldMapping, newMapping)) {
275 notifyChange(key, mappingData.getRecord(), changeType);
278 // Since the above notifyChange() already notifies the dest part of source/dest addresses, we save the dest
279 // for the checks that we do afterwards
280 if (key.getAddress() instanceof SourceDestKey) {
281 dstKey = SourceDestKeyHelper.getDstBinary(key);
283 // If the old mapping had a different EID than what was just added, notify those subscribers too
284 if (oldMapping != null && !oldMapping.getEid().equals(key) && !oldMapping.getEid().equals(dstKey)) {
285 notifyChange(oldMapping.getEid(), oldMapping, changeType);
287 // If the new mapping has a different EID than what was just added (e.g., due to NB_AND_SB), notify those
289 if (newMapping != null && !newMapping.getEid().equals(key) && !newMapping.getEid().equals(dstKey)) {
290 notifyChange(newMapping.getEid(), newMapping, changeType);
297 public MappingData addNegativeMapping(Eid key) {
298 MappingRecord mapping = buildNegativeMapping(key);
299 MappingData mappingData = new MappingData(mapping);
300 LOG.debug("Adding negative mapping for EID {}", LispAddressStringifier.getString(mapping.getEid()));
301 LOG.trace(mappingData.getString());
302 smc.addMapping(mapping.getEid(), mappingData);
303 dsbe.addMapping(DSBEInputUtil.toMapping(MappingOrigin.Southbound, mapping.getEid(), null, mappingData));
307 private MappingRecord buildNegativeMapping(Eid eid) {
308 MappingRecordBuilder recordBuilder = new MappingRecordBuilder();
309 recordBuilder.setAuthoritative(false);
310 recordBuilder.setMapVersion((short) 0);
311 recordBuilder.setEid(eid);
312 if (eid.getAddressType().equals(Ipv4PrefixBinaryAfi.class)
313 || eid.getAddressType().equals(Ipv6PrefixBinaryAfi.class)) {
314 Eid widestNegativePrefix = getWidestNegativePrefix(eid);
315 if (widestNegativePrefix != null) {
316 recordBuilder.setEid(widestNegativePrefix);
319 recordBuilder.setAction(LispMessage.NEGATIVE_MAPPING_ACTION);
320 //if (getAuthenticationKey(eid) != null) {
321 // recordBuilder.setRecordTtl(TTL_RLOC_TIMED_OUT);
323 recordBuilder.setRecordTtl(TTL_NO_RLOC_KNOWN);
325 return recordBuilder.build();
329 * Since this method is only called when there is a hit in the southbound Map-Register cache, and that cache is
330 * not used when merge is on, it's OK to ignore the effects of timestamp changes on merging for now.
333 public void refreshMappingRegistration(Eid key, XtrId xtrId, Long timestamp) {
335 sbMappingTimeoutService.removeExpiredMappings();
337 if (timestamp == null) {
338 timestamp = System.currentTimeMillis();
340 MappingData mappingData = (MappingData) smc.getMapping(null, key);
341 if (mappingData != null) {
342 mappingData.setTimestamp(new Date(timestamp));
343 addOrRefreshMappingInTimeoutService(key, mappingData);
345 LOG.warn("Could not update timestamp for EID {}, no mapping found", LispAddressStringifier.getString(key));
347 if (mappingMerge && xtrId != null) {
348 MappingData xtrIdMappingData = (MappingData) smc.getMapping(key, xtrId);
349 if (xtrIdMappingData != null) {
350 xtrIdMappingData.setTimestamp(new Date(timestamp));
352 LOG.warn("Could not update timestamp for EID {} xTR-ID {}, no mapping found",
353 LispAddressStringifier.getString(key), LispAddressStringifier.getString(xtrId));
358 private MappingData updateServicePathMappingRecord(MappingData mappingData, Eid eid) {
359 // keep properties of original record
360 MappingRecordBuilder recordBuilder = new MappingRecordBuilder(mappingData.getRecord());
361 recordBuilder.setLocatorRecord(new ArrayList<LocatorRecord>());
363 // there should only be one locator record
364 if (mappingData.getRecord().getLocatorRecord().size() != 1) {
365 LOG.warn("MappingRecord associated to ServicePath EID has more than one locator!");
369 LocatorRecord locatorRecord = mappingData.getRecord().getLocatorRecord().get(0);
370 long serviceIndex = ((ServicePath) eid.getAddress()).getServicePath().getServiceIndex().toJava();
371 int index = LispAddressUtil.STARTING_SERVICE_INDEX - (int) serviceIndex;
372 Rloc rloc = locatorRecord.getRloc();
373 if (rloc.getAddress() instanceof Ipv4 || rloc.getAddress() instanceof Ipv6) {
375 LOG.warn("Service Index should be 255 for simple IP RLOCs!");
378 } else if (rloc.getAddress() instanceof ExplicitLocatorPath) {
379 ExplicitLocatorPath elp = (ExplicitLocatorPath) rloc.getAddress();
380 List<Hop> hops = elp.getExplicitLocatorPath().getHop();
382 if (index < 0 || index > hops.size()) {
383 LOG.warn("Service Index out of bounds!");
387 SimpleAddress nextHop = hops.get(index).getAddress();
388 LocatorRecordBuilder lrb = new LocatorRecordBuilder(locatorRecord);
389 lrb.setRloc(LispAddressUtil.toRloc(nextHop));
390 recordBuilder.getLocatorRecord().add(lrb.build());
391 return new MappingData(recordBuilder.build());
393 LOG.warn("Nothing to do with ServicePath mapping record");
398 private MappingData handleMergedMapping(Eid key) {
399 LOG.trace("Merging mappings for EID {}", LispAddressStringifier.getString(key));
400 List<MappingData> expiredMappingDataList = new ArrayList<>();
401 Set<IpAddressBinary> sourceRlocs = new HashSet<>();
403 MappingData mergedMappingData = MappingMergeUtil.mergeXtrIdMappings(smc.getAllXtrIdMappings(key),
404 expiredMappingDataList, sourceRlocs);
406 for (MappingData mappingData : expiredMappingDataList) {
407 removeSbXtrIdSpecificMapping(key, mappingData.getXtrId(), mappingData);
410 if (mergedMappingData != null) {
411 smc.addMapping(key, mergedMappingData, sourceRlocs);
412 dsbe.addMapping(DSBEInputUtil.toMapping(MappingOrigin.Southbound, key, mergedMappingData));
413 addOrRefreshMappingInTimeoutService(key, mergedMappingData);
415 removeSbMapping(key, mergedMappingData);
417 return mergedMappingData;
421 public MappingData getMapping(Eid src, Eid dst) {
422 // NOTE: Currently we have two lookup algorithms implemented, which are configurable
423 IMappingService.LookupPolicy policy = ConfigIni.getInstance().getLookupPolicy();
424 LOG.debug("DAO: Looking up mapping for {}, source EID {} with policy {}",
425 LispAddressStringifier.getString(dst),
426 LispAddressStringifier.getString(src),
429 if (policy == IMappingService.LookupPolicy.NB_AND_SB) {
430 return getMappingNbSbIntersection(src, dst);
432 return getMappingNbFirst(src, dst);
437 public MappingData getMapping(Eid dst) {
438 return getMapping((Eid) null, dst);
442 public MappingData getMapping(Eid src, Eid dst, XtrId xtrId) {
443 // Note: If xtrId is null, we need to go through regular policy checking else Policy doesn't matter
446 return getMapping(src, dst);
449 return getSbMappingWithExpiration(src, dst, xtrId);
453 public MappingData getMapping(MappingOrigin origin, Eid key) {
454 if (origin.equals(MappingOrigin.Southbound)) {
455 return getSbMappingWithExpiration(null, key, null);
457 return (MappingData) tableMap.get(origin).getMapping(null, key);
460 private MappingData getMappingNbFirst(Eid src, Eid dst) {
462 // Default lookup policy is northboundFirst
463 //lookupPolicy == NB_FIRST
465 MappingData nbMappingData = (MappingData) pmc.getMapping(src, dst);
467 if (nbMappingData == null) {
468 return getSbMappingWithExpiration(src, dst, null);
470 if (dst.getAddress() instanceof ServicePath) {
471 return updateServicePathMappingRecord(nbMappingData, dst);
473 return nbMappingData;
476 private MappingData getMappingNbSbIntersection(Eid src, Eid dst) {
477 //lookupPolicy == NB_AND_SB, we return intersection
478 //of NB and SB mappings, or NB mapping if intersection is empty.
480 MappingData nbMappingData = (MappingData) pmc.getMapping(src, dst);
481 if (nbMappingData == null) {
482 return nbMappingData;
484 // no intersection for Service Path mappings
485 if (dst.getAddress() instanceof ServicePath) {
486 return updateServicePathMappingRecord(nbMappingData, dst);
488 MappingData sbMappingData = getSbMappingWithExpiration(src, dst, null);
489 if (sbMappingData == null) {
490 return nbMappingData;
492 // both NB and SB mappings exist. Compute intersection of the mappings
493 return MappingMergeUtil.computeNbSbIntersection(nbMappingData, sbMappingData);
496 private MappingData getSbMappingWithExpiration(Eid src, Eid dst, XtrId xtrId) {
497 MappingData mappingData = (MappingData) smc.getMapping(dst, xtrId);
498 while (mappingData != null && MappingMergeUtil.mappingIsExpired(mappingData)) {
499 // If the mappingData is expired, handleSbExpiredMapping() will run merge for it if merge is enabled,
500 // otherwise it will remove the expired mapping, returning null.
501 MappingData mergedMappingData = handleSbExpiredMapping(dst, xtrId, mappingData);
502 if (mergedMappingData != null) {
503 return mergedMappingData;
505 // If the expired mapping was removed, we look up the original query again
506 mappingData = (MappingData) smc.getMapping(dst, xtrId);
511 public MappingData handleSbExpiredMapping(Eid key, XtrId xtrId, MappingData mappingData) {
512 if (mappingMerge && mappingData.isMergeEnabled()) {
513 return handleMergedMapping(key);
517 removeSbXtrIdSpecificMapping(key, xtrId, mappingData);
519 removeSbMapping(key, mappingData);
524 private void removeSbXtrIdSpecificMapping(Eid key, XtrId xtrId, MappingData mappingData) {
525 if (LOG.isDebugEnabled()) {
526 LOG.debug("DAO: Removing southbound mapping for EID {}, xTR-ID {}",
527 LispAddressStringifier.getString(key),
528 LispAddressStringifier.getString(xtrId));
530 smc.removeMapping(key, xtrId);
531 dsbe.removeXtrIdMapping(DSBEInputUtil.toXtrIdMapping(mappingData));
534 private void removeSbMapping(Eid key, MappingData mappingData) {
535 if (mappingData != null && mappingData.getXtrId() != null) {
536 removeSbXtrIdSpecificMapping(key, mappingData.getXtrId(), mappingData);
539 removeFromSbTimeoutService(key);
540 final Set<Subscriber> subscribers = getSubscribers(key);
541 if (LOG.isDebugEnabled()) {
542 LOG.debug("DAO: Removing southbound mapping for EID {}", LispAddressStringifier.getString(key));
544 smc.removeMapping(key);
545 dsbe.removeMapping(DSBEInputUtil.toMapping(MappingOrigin.Southbound, key, mappingData));
546 publishNotification(mappingData.getRecord(), null, subscribers, null, MappingChange.Removed);
547 removeSubscribersConditionally(MappingOrigin.Southbound, key);
550 private void removeFromSbTimeoutService(Eid key) {
551 Integer bucketId = (Integer) smc.getData(key, SubKeys.TIME_BUCKET_ID);
552 if (bucketId != null) {
553 sbMappingTimeoutService.removeMappingFromTimeoutService(key, bucketId);
558 public Eid getWidestNegativePrefix(Eid key) {
559 if (!MaskUtil.isMaskable(key.getAddress())) {
560 LOG.warn("Widest negative prefix only makes sense for maskable addresses!");
564 // We assume that ILispMapCache#getWidestNegativeMapping() returns null for positive mappings, and 0/0
566 Eid nbPrefix = pmc.getWidestNegativeMapping(key);
567 if (nbPrefix == null) {
568 LOG.trace("getWidestNegativePrefix NB: positive mapping, returning null");
571 if (LOG.isTraceEnabled()) {
572 LOG.trace("getWidestNegativePrefix NB: {}", LispAddressStringifier.getString(nbPrefix));
575 Eid sbPrefix = smc.getWidestNegativeMapping(key);
576 if (sbPrefix == null) {
577 LOG.trace("getWidestNegativePrefix SB: positive mapping, returning null");
580 if (LOG.isTraceEnabled()) {
581 LOG.trace("getWidestNegativePrefix SB: {}", LispAddressStringifier.getString(sbPrefix));
584 // since prefixes overlap, just return the more specific (larger mask)
585 if (LispAddressUtil.getIpPrefixMask(nbPrefix) < LispAddressUtil.getIpPrefixMask(sbPrefix)) {
593 public Set<Eid> getSubtree(MappingOrigin origin, Eid key) {
594 if (!MaskUtil.isMaskable(key.getAddress())) {
595 LOG.warn("Child prefixes only make sense for maskable addresses!");
596 return Collections.emptySet();
599 return tableMap.get(origin).getSubtree(key);
603 public void removeMapping(MappingOrigin origin, Eid key) {
605 Set<Subscriber> subscribers = null;
606 Set<Subscriber> dstSubscribers = null;
607 MappingData mapping = (MappingData) tableMap.get(origin).getMapping(null, key);
609 if (LOG.isDebugEnabled()) {
610 LOG.debug("Removing mapping for EID {} from {}",
611 LispAddressStringifier.getString(key), origin);
613 if (LOG.isTraceEnabled() && mapping != null) {
614 LOG.trace(mapping.getString());
617 MappingRecord notificationMapping = null;
619 if (mapping != null) {
620 notificationMapping = mapping.getRecord();
621 subscribers = getSubscribers(key);
622 // For SrcDst LCAF also send SMRs to Dst prefix
623 if (key.getAddress() instanceof SourceDestKey) {
624 dstAddr = SourceDestKeyHelper.getDstBinary(key);
625 dstSubscribers = getSubscribers(dstAddr);
629 removeSubscribersConditionally(origin, key);
631 if (origin == MappingOrigin.Southbound) {
632 removeFromSbTimeoutService(key);
635 if (origin == MappingOrigin.Southbound && mapping != null && mapping.isPositive().or(false)) {
636 mergeNegativePrefixes(key);
638 // mergeNegativePrefixes() above removes the mapping, so addNegativeMapping() will work correctly
639 tableMap.get(origin).removeMapping(key);
642 if (notificationMapping != null) {
643 publishNotification(notificationMapping, key, subscribers, dstSubscribers, MappingChange.Removed);
644 notifyChildren(key, notificationMapping, MappingChange.Removed);
645 if (dstAddr != null) {
646 notifyChildren(dstAddr, notificationMapping, MappingChange.Removed);
651 public void notifyChange(Eid eid, MappingRecord mapping, MappingChange mappingChange) {
652 Set<Subscriber> subscribers = getSubscribers(eid);
654 Set<Subscriber> dstSubscribers = null;
655 // For SrcDst LCAF also send SMRs to Dst prefix
656 if (eid.getAddress() instanceof SourceDestKey) {
657 Eid dstAddr = SourceDestKeyHelper.getDstBinary(eid);
658 dstSubscribers = getSubscribers(dstAddr);
659 notifyChildren(dstAddr, mapping, mappingChange);
662 // No reason to send a notification when no subscribers exist
663 if (subscribers != null || dstSubscribers != null) {
664 publishNotification(mapping, eid, subscribers, dstSubscribers, mappingChange);
667 notifyChildren(eid, mapping, mappingChange);
670 private void notifyChildren(Eid eid, MappingRecord mapping, MappingChange mappingChange) {
671 // Update/created only happens for NB mappings. We assume no overlapping prefix support for NB mappings - so
672 // this NB mapping should not have any children. Both for NB first and NB&SB cases all subscribers for SB
673 // prefixes that are equal or more specific to this NB prefix have to be notified of the potential change.
674 // Each subscriber is notified for the prefix that it is currently subscribed to, and MS should return to them
675 // a Map-Reply with the same prefix and update mapping in cases of EID_INTERSECTION_RLOC_NB_FIRST which is a
676 // new option we are creating TODO
677 Set<Eid> childPrefixes = getSubtree(MappingOrigin.Southbound, eid);
678 if (childPrefixes == null || childPrefixes.isEmpty()) {
682 childPrefixes.remove(eid);
683 for (Eid prefix : childPrefixes) {
684 Set<Subscriber> subscribers = getSubscribers(prefix);
685 // No reason to send a notification when no subscribers exist
686 if (subscribers != null) {
687 publishNotification(mapping, prefix, subscribers, null, mappingChange);
692 private void publishNotification(MappingRecord mapping, Eid eid, Set<Subscriber> subscribers,
693 Set<Subscriber> dstSubscribers, MappingChange mappingChange) {
695 // The notifications are used for sending SMR.
696 notificationPublishService.putNotification(MSNotificationInputUtil.toMappingChanged(
697 mapping, eid, subscribers, dstSubscribers, mappingChange));
698 } catch (InterruptedException e) {
699 LOG.warn("Notification publication interrupted!");
704 * Merges adjacent negative prefixes and notifies their subscribers.
706 private void mergeNegativePrefixes(Eid eid) {
707 LOG.debug("Merging negative prefixes starting from EID {}", LispAddressStringifier.getString(eid));
709 // If we delete nodes while we walk up the radix trie the algorithm will give incorrect results, because
710 // removals rearrange relationships in the trie. So we save prefixes to be removed into a HashMap.
711 Map<Eid, MappingData> mergedMappings = new HashMap<>();
713 Eid currentNode = smc.getSiblingPrefix(eid);
714 MappingData mapping = (MappingData) smc.getMapping(null, currentNode);
715 if (mapping != null && mapping.isNegative().or(false)) {
716 mergedMappings.put(currentNode, mapping);
721 Eid previousNode = currentNode;
722 currentNode = smc.getVirtualParentSiblingPrefix(currentNode);
723 while (currentNode != null) {
724 mapping = (MappingData) smc.getMapping(null, currentNode);
725 if (mapping != null && mapping.isNegative().or(false)) {
726 mergedMappings.put(currentNode, mapping);
730 previousNode = currentNode;
731 currentNode = smc.getVirtualParentSiblingPrefix(previousNode);
734 for (Eid key : mergedMappings.keySet()) {
735 removeSbMapping(key, mergedMappings.get(key));
737 smc.removeMapping(eid);
739 addNegativeMapping(getVirtualParent(previousNode));
742 private static Eid getVirtualParent(Eid eid) {
743 if (eid.getAddress() instanceof Ipv4PrefixBinary) {
744 Ipv4PrefixBinary prefix = (Ipv4PrefixBinary) eid.getAddress();
745 short parentPrefixLength = (short) (prefix.getIpv4MaskLength().toJava() - 1);
746 byte[] parentPrefix = MaskUtil.normalizeByteArray(prefix.getIpv4AddressBinary().getValue(),
748 return LispAddressUtil.asIpv4PrefixBinaryEid(eid, parentPrefix, parentPrefixLength);
749 } else if (eid.getAddress() instanceof Ipv6PrefixBinary) {
750 Ipv6PrefixBinary prefix = (Ipv6PrefixBinary) eid.getAddress();
751 short parentPrefixLength = (short) (prefix.getIpv6MaskLength().toJava() - 1);
752 byte[] parentPrefix = MaskUtil.normalizeByteArray(prefix.getIpv6AddressBinary().getValue(),
754 return LispAddressUtil.asIpv6PrefixBinaryEid(eid, parentPrefix, parentPrefixLength);
760 public synchronized void subscribe(Subscriber subscriber, Eid subscribedEid) {
761 Set<Subscriber> subscribers = getSubscribers(subscribedEid);
762 if (subscribers == null) {
763 subscribers = Sets.newConcurrentHashSet();
764 } else if (subscribers.contains(subscriber)) {
765 // If there is an entry already for this subscriber, remove it, so that it gets the new timestamp
766 subscribers.remove(subscriber);
768 if (LOG.isDebugEnabled()) {
769 LOG.debug("Adding new subscriber {} for EID {}", subscriber.getString(),
770 LispAddressStringifier.getString(subscribedEid));
772 subscribers.add(subscriber);
773 addSubscribers(subscribedEid, subscribers);
776 private void addSubscribers(Eid address, Set<Subscriber> subscribers) {
777 LoggingUtil.logSubscribers(LOG, address, subscribers);
778 subscriberdb.put(address, subscribers);
782 public Set<Subscriber> getSubscribers(Eid address) {
783 if (LOG.isDebugEnabled()) {
784 LOG.debug("Retrieving subscribers for EID {}", LispAddressStringifier.getString(address));
787 Set<Subscriber> subscribers = subscriberdb.get(address);
788 LoggingUtil.logSubscribers(LOG, address, subscribers);
793 * Only remove subscribers if there is no exact match mapping in the map-cache other than the one specified by
794 * origin. Right now we only have two origins, but in case we will have more, we only need to update this method,
795 * not the callers. We use getData() instead of getMapping to do exact match instead of longest prefix match.
797 private void removeSubscribersConditionally(MappingOrigin origin, Eid address) {
798 if (origin == MappingOrigin.Southbound) {
799 if (pmc.getData(address, SubKeys.RECORD) == null) {
800 removeSubscribers(address);
802 } else if (origin == MappingOrigin.Northbound) {
803 if (smc.getData(address, SubKeys.RECORD) == null) {
804 removeSubscribers(address);
809 private void removeSubscribers(Eid address) {
810 if (LOG.isDebugEnabled()) {
811 LOG.debug("Removing subscribers for EID {}", LispAddressStringifier.getString(address));
813 subscriberdb.remove(address);
817 public void addAuthenticationKey(Eid key, MappingAuthkey authKey) {
818 LOG.debug("Adding authentication key '{}' with key-ID {} for {}", authKey.getKeyString(), authKey.getKeyType(),
819 LispAddressStringifier.getString(key));
820 akdb.addAuthenticationKey(key, authKey);
824 public MappingAuthkey getAuthenticationKey(Eid key) {
825 if (LOG.isDebugEnabled()) {
826 LOG.debug("Retrieving authentication key for {}", LispAddressStringifier.getString(key));
828 return akdb.getAuthenticationKey(key);
832 public void removeAuthenticationKey(Eid key) {
833 if (LOG.isDebugEnabled()) {
834 LOG.debug("Removing authentication key for {}", LispAddressStringifier.getString(key));
836 akdb.removeAuthenticationKey(key);
840 public void addData(MappingOrigin origin, Eid key, String subKey, Object data) {
841 if (LOG.isDebugEnabled()) {
842 LOG.debug("Add data of {} for key {} and subkey {}", data.getClass(),
843 LispAddressStringifier.getString(key), subKey);
845 tableMap.get(origin).addData(key, subKey, data);
849 public Object getData(MappingOrigin origin, Eid key, String subKey) {
850 if (LOG.isDebugEnabled()) {
851 LOG.debug("Retrieving data for key {} and subkey {}", LispAddressStringifier.getString(key), subKey);
853 return tableMap.get(origin).getData(key, subKey);
857 public void removeData(MappingOrigin origin, Eid key, String subKey) {
858 if (LOG.isDebugEnabled()) {
859 LOG.debug("Removing data for key {} and subkey {}", LispAddressStringifier.getString(key), subKey);
861 tableMap.get(origin).removeData(key, subKey);
865 public Eid getParentPrefix(Eid key) {
866 return smc.getParentPrefix(key);
871 * Restore all mappings and keys from mdsal datastore.
873 private void restoreDaoFromDatastore() {
874 List<AuthenticationKey> authKeys = dsbe.getAllAuthenticationKeys();
875 List<Mapping> mappings = dsbe.getAllMappings(LogicalDatastoreType.CONFIGURATION);
878 * XXX By default, the operational datastore is not persisted to disk, either at run-time, or on shutdown,
879 * so the following will have no effect (getLastUpdateTimestamp() will fail, since it's reading from
880 * the operational datastore, and even if it didn't getAllMappings() will fail anyway). According to rovarga it
881 * should be possible to turn on persistence for the operational datastore editing
882 * etc/opendaylight/karaf/05-clustering.xml, by setting <persistence>true</persistence>. At the time of writing
883 * the below code block that didn't seem to work though.
885 Long lastUpdateTimestamp = dsbe.getLastUpdateTimestamp();
886 if (lastUpdateTimestamp != null && System.currentTimeMillis() - lastUpdateTimestamp
887 > ConfigIni.getInstance().getRegistrationValiditySb()) {
888 LOG.warn("Restore threshold passed, not restoring operational datastore into DAO");
890 mappings.addAll(dsbe.getAllMappings(LogicalDatastoreType.OPERATIONAL));
892 dsbe.removeLastUpdateTimestamp();
894 LOG.info("Restoring {} mappings and {} keys from datastore into DAO", mappings.size(), authKeys.size());
896 for (Mapping mapping : mappings) {
897 addMapping(mapping.getOrigin(), mapping.getMappingRecord().getEid(),
898 new MappingData(mapping.getMappingRecord()));
901 for (AuthenticationKey authKey : authKeys) {
902 addAuthenticationKey(authKey.getEid(), authKey.getMappingAuthkey());
906 public void destroy() {
907 LOG.info("Mapping System is being destroyed!");
908 dsbe.saveLastUpdateTimestamp();
912 public String printMappings() {
913 sbMappingTimeoutService.removeExpiredMappings();
915 final StringBuilder sb = new StringBuilder();
916 sb.append("Policy map-cache\n----------------\n");
917 sb.append(pmc.printMappings());
918 sb.append("\nSouthbound map-cache\n--------------------\n");
919 sb.append(smc.printMappings());
920 return sb.toString();
924 public String prettyPrintMappings() {
925 sbMappingTimeoutService.removeExpiredMappings();
927 final StringBuilder sb = new StringBuilder();
928 sb.append("Policy map-cache\n----------------\n");
929 sb.append(pmc.prettyPrintMappings());
930 sb.append("\nSouthbound map-cache\n--------------------\n");
931 sb.append(smc.prettyPrintMappings());
932 sb.append("\nSubscribers\n-----------\n");
933 sb.append(prettyPrintSubscribers(subscriberdb));
934 return sb.toString();
937 private static String prettyPrintSubscribers(Map<Eid, Set<Subscriber>> subscribers) {
938 final StringBuilder sb = new StringBuilder();
939 for (Eid eid: subscribers.keySet()) {
941 sb.append(LispAddressStringifier.getString(eid));
943 sb.append(LispMapCacheStringifier.prettyPrintSubscriberSet(subscribers.get(eid), 4));
946 return sb.toString();
950 public String printKeys() {
951 return akdb.printKeys();
955 public String prettyPrintKeys() {
956 return akdb.prettyPrintKeys();
959 public void cleanCaches() {
961 subscriberdb.clear();
965 public void cleanSBMappings() {
966 smc = new SimpleMapCache(sdao);
970 public void setIsMaster(boolean isMaster) {
971 this.isMaster = isMaster;
975 public boolean isMaster() {