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 {}: {}",
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.
332 public void refreshMappingRegistration(Eid key, XtrId xtrId, Long timestamp) {
334 sbMappingTimeoutService.removeExpiredMappings();
336 if (timestamp == null) {
337 timestamp = System.currentTimeMillis();
339 MappingData mappingData = (MappingData) smc.getMapping(null, key);
340 if (mappingData != null) {
341 mappingData.setTimestamp(new Date(timestamp));
342 addOrRefreshMappingInTimeoutService(key, mappingData);
344 LOG.warn("Could not update timestamp for EID {}, no mapping found", LispAddressStringifier.getString(key));
346 if (mappingMerge && xtrId != null) {
347 MappingData xtrIdMappingData = (MappingData) smc.getMapping(key, xtrId);
348 if (xtrIdMappingData != null) {
349 xtrIdMappingData.setTimestamp(new Date(timestamp));
351 LOG.warn("Could not update timestamp for EID {} xTR-ID {}, no mapping found",
352 LispAddressStringifier.getString(key), LispAddressStringifier.getString(xtrId));
357 private MappingData updateServicePathMappingRecord(MappingData mappingData, Eid eid) {
358 // keep properties of original record
359 MappingRecordBuilder recordBuilder = new MappingRecordBuilder(mappingData.getRecord());
360 recordBuilder.setLocatorRecord(new ArrayList<LocatorRecord>());
362 // there should only be one locator record
363 if (mappingData.getRecord().getLocatorRecord().size() != 1) {
364 LOG.warn("MappingRecord associated to ServicePath EID has more than one locator!");
368 LocatorRecord locatorRecord = mappingData.getRecord().getLocatorRecord().get(0);
369 long serviceIndex = ((ServicePath) eid.getAddress()).getServicePath().getServiceIndex();
370 int index = LispAddressUtil.STARTING_SERVICE_INDEX - (int) serviceIndex;
371 Rloc rloc = locatorRecord.getRloc();
372 if (rloc.getAddress() instanceof Ipv4 || rloc.getAddress() instanceof Ipv6) {
374 LOG.warn("Service Index should be 255 for simple IP RLOCs!");
377 } else if (rloc.getAddress() instanceof ExplicitLocatorPath) {
378 ExplicitLocatorPath elp = (ExplicitLocatorPath) rloc.getAddress();
379 List<Hop> hops = elp.getExplicitLocatorPath().getHop();
381 if (index < 0 || index > hops.size()) {
382 LOG.warn("Service Index out of bounds!");
386 SimpleAddress nextHop = hops.get(index).getAddress();
387 LocatorRecordBuilder lrb = new LocatorRecordBuilder(locatorRecord);
388 lrb.setRloc(LispAddressUtil.toRloc(nextHop));
389 recordBuilder.getLocatorRecord().add(lrb.build());
390 return new MappingData(recordBuilder.build());
392 LOG.warn("Nothing to do with ServicePath mapping record");
397 private MappingData handleMergedMapping(Eid key) {
398 LOG.trace("Merging mappings for EID {}", LispAddressStringifier.getString(key));
399 List<MappingData> expiredMappingDataList = new ArrayList<>();
400 Set<IpAddressBinary> sourceRlocs = new HashSet<>();
402 MappingData mergedMappingData = MappingMergeUtil.mergeXtrIdMappings(smc.getAllXtrIdMappings(key),
403 expiredMappingDataList, sourceRlocs);
405 for (MappingData mappingData : expiredMappingDataList) {
406 removeSbXtrIdSpecificMapping(key, mappingData.getXtrId(), mappingData);
409 if (mergedMappingData != null) {
410 smc.addMapping(key, mergedMappingData, sourceRlocs);
411 dsbe.addMapping(DSBEInputUtil.toMapping(MappingOrigin.Southbound, key, mergedMappingData));
412 addOrRefreshMappingInTimeoutService(key, mergedMappingData);
414 removeSbMapping(key, mergedMappingData);
416 return mergedMappingData;
420 public MappingData getMapping(Eid src, Eid dst) {
421 // NOTE: Currently we have two lookup algorithms implemented, which are configurable
422 IMappingService.LookupPolicy policy = ConfigIni.getInstance().getLookupPolicy();
423 LOG.debug("DAO: Looking up mapping for {}, source EID {} with policy {}",
424 LispAddressStringifier.getString(dst),
425 LispAddressStringifier.getString(src),
428 if (policy == IMappingService.LookupPolicy.NB_AND_SB) {
429 return getMappingNbSbIntersection(src, dst);
431 return getMappingNbFirst(src, dst);
436 public MappingData getMapping(Eid dst) {
437 return getMapping((Eid) null, dst);
441 public MappingData getMapping(Eid src, Eid dst, XtrId xtrId) {
442 // Note: If xtrId is null, we need to go through regular policy checking else Policy doesn't matter
445 return getMapping(src, dst);
448 return getSbMappingWithExpiration(src, dst, xtrId);
452 public MappingData getMapping(MappingOrigin origin, Eid key) {
453 if (origin.equals(MappingOrigin.Southbound)) {
454 return getSbMappingWithExpiration(null, key, null);
456 return (MappingData) tableMap.get(origin).getMapping(null, key);
459 private MappingData getMappingNbFirst(Eid src, Eid dst) {
461 // Default lookup policy is northboundFirst
462 //lookupPolicy == NB_FIRST
464 MappingData nbMappingData = (MappingData) pmc.getMapping(src, dst);
466 if (nbMappingData == null) {
467 return getSbMappingWithExpiration(src, dst, null);
469 if (dst.getAddress() instanceof ServicePath) {
470 return updateServicePathMappingRecord(nbMappingData, dst);
472 return nbMappingData;
475 private MappingData getMappingNbSbIntersection(Eid src, Eid dst) {
476 //lookupPolicy == NB_AND_SB, we return intersection
477 //of NB and SB mappings, or NB mapping if intersection is empty.
479 MappingData nbMappingData = (MappingData) pmc.getMapping(src, dst);
480 if (nbMappingData == null) {
481 return nbMappingData;
483 // no intersection for Service Path mappings
484 if (dst.getAddress() instanceof ServicePath) {
485 return updateServicePathMappingRecord(nbMappingData, dst);
487 MappingData sbMappingData = getSbMappingWithExpiration(src, dst, null);
488 if (sbMappingData == null) {
489 return nbMappingData;
491 // both NB and SB mappings exist. Compute intersection of the mappings
492 return MappingMergeUtil.computeNbSbIntersection(nbMappingData, sbMappingData);
495 private MappingData getSbMappingWithExpiration(Eid src, Eid dst, XtrId xtrId) {
496 MappingData mappingData = (MappingData) smc.getMapping(dst, xtrId);
497 while (mappingData != null && MappingMergeUtil.mappingIsExpired(mappingData)) {
498 // If the mappingData is expired, handleSbExpiredMapping() will run merge for it if merge is enabled,
499 // otherwise it will remove the expired mapping, returning null.
500 MappingData mergedMappingData = handleSbExpiredMapping(dst, xtrId, mappingData);
501 if (mergedMappingData != null) {
502 return mergedMappingData;
504 // If the expired mapping was removed, we look up the original query again
505 mappingData = (MappingData) smc.getMapping(dst, xtrId);
510 public MappingData handleSbExpiredMapping(Eid key, XtrId xtrId, MappingData mappingData) {
511 if (mappingMerge && mappingData.isMergeEnabled()) {
512 return handleMergedMapping(key);
516 removeSbXtrIdSpecificMapping(key, xtrId, mappingData);
518 removeSbMapping(key, mappingData);
523 private void removeSbXtrIdSpecificMapping(Eid key, XtrId xtrId, MappingData mappingData) {
524 if (LOG.isDebugEnabled()) {
525 LOG.debug("DAO: Removing southbound mapping for EID {}, xTR-ID {}",
526 LispAddressStringifier.getString(key),
527 LispAddressStringifier.getString(xtrId));
529 smc.removeMapping(key, xtrId);
530 dsbe.removeXtrIdMapping(DSBEInputUtil.toXtrIdMapping(mappingData));
533 private void removeSbMapping(Eid key, MappingData mappingData) {
534 if (mappingData != null && mappingData.getXtrId() != null) {
535 removeSbXtrIdSpecificMapping(key, mappingData.getXtrId(), mappingData);
538 removeFromSbTimeoutService(key);
539 final Set<Subscriber> subscribers = getSubscribers(key);
540 if (LOG.isDebugEnabled()) {
541 LOG.debug("DAO: Removing southbound mapping for EID {}", LispAddressStringifier.getString(key));
543 smc.removeMapping(key);
544 dsbe.removeMapping(DSBEInputUtil.toMapping(MappingOrigin.Southbound, key, mappingData));
545 publishNotification(mappingData.getRecord(), null, subscribers, null, MappingChange.Removed);
546 removeSubscribersConditionally(MappingOrigin.Southbound, key);
549 private void removeFromSbTimeoutService(Eid key) {
550 Integer bucketId = (Integer) smc.getData(key, SubKeys.TIME_BUCKET_ID);
551 if (bucketId != null) {
552 sbMappingTimeoutService.removeMappingFromTimeoutService(key, bucketId);
557 public Eid getWidestNegativePrefix(Eid key) {
558 if (!MaskUtil.isMaskable(key.getAddress())) {
559 LOG.warn("Widest negative prefix only makes sense for maskable addresses!");
563 // We assume that ILispMapCache#getWidestNegativeMapping() returns null for positive mappings, and 0/0
565 Eid nbPrefix = pmc.getWidestNegativeMapping(key);
566 if (nbPrefix == null) {
567 LOG.trace("getWidestNegativePrefix NB: positive mapping, returning null");
570 if (LOG.isTraceEnabled()) {
571 LOG.trace("getWidestNegativePrefix NB: {}", LispAddressStringifier.getString(nbPrefix));
574 Eid sbPrefix = smc.getWidestNegativeMapping(key);
575 if (sbPrefix == null) {
576 LOG.trace("getWidestNegativePrefix SB: positive mapping, returning null");
579 if (LOG.isTraceEnabled()) {
580 LOG.trace("getWidestNegativePrefix SB: {}", LispAddressStringifier.getString(sbPrefix));
583 // since prefixes overlap, just return the more specific (larger mask)
584 if (LispAddressUtil.getIpPrefixMask(nbPrefix) < LispAddressUtil.getIpPrefixMask(sbPrefix)) {
592 public Set<Eid> getSubtree(MappingOrigin origin, Eid key) {
593 if (!MaskUtil.isMaskable(key.getAddress())) {
594 LOG.warn("Child prefixes only make sense for maskable addresses!");
595 return Collections.emptySet();
598 return tableMap.get(origin).getSubtree(key);
602 public void removeMapping(MappingOrigin origin, Eid key) {
604 Set<Subscriber> subscribers = null;
605 Set<Subscriber> dstSubscribers = null;
606 MappingData mapping = (MappingData) tableMap.get(origin).getMapping(null, key);
608 if (LOG.isDebugEnabled()) {
609 LOG.debug("Removing mapping for EID {} from {}",
610 LispAddressStringifier.getString(key), origin);
612 if (LOG.isTraceEnabled() && mapping != null) {
613 LOG.trace(mapping.getString());
616 MappingRecord notificationMapping = null;
618 if (mapping != null) {
619 notificationMapping = mapping.getRecord();
620 subscribers = getSubscribers(key);
621 // For SrcDst LCAF also send SMRs to Dst prefix
622 if (key.getAddress() instanceof SourceDestKey) {
623 dstAddr = SourceDestKeyHelper.getDstBinary(key);
624 dstSubscribers = getSubscribers(dstAddr);
628 removeSubscribersConditionally(origin, key);
630 if (origin == MappingOrigin.Southbound) {
631 removeFromSbTimeoutService(key);
634 if (origin == MappingOrigin.Southbound && mapping != null && mapping.isPositive().or(false)) {
635 mergeNegativePrefixes(key);
637 // mergeNegativePrefixes() above removes the mapping, so addNegativeMapping() will work correctly
638 tableMap.get(origin).removeMapping(key);
641 if (notificationMapping != null) {
642 publishNotification(notificationMapping, key, subscribers, dstSubscribers, MappingChange.Removed);
643 notifyChildren(key, notificationMapping, MappingChange.Removed);
644 if (dstAddr != null) {
645 notifyChildren(dstAddr, notificationMapping, MappingChange.Removed);
650 public void notifyChange(Eid eid, MappingRecord mapping, MappingChange mappingChange) {
651 Set<Subscriber> subscribers = getSubscribers(eid);
653 Set<Subscriber> dstSubscribers = null;
654 // For SrcDst LCAF also send SMRs to Dst prefix
655 if (eid.getAddress() instanceof SourceDestKey) {
656 Eid dstAddr = SourceDestKeyHelper.getDstBinary(eid);
657 dstSubscribers = getSubscribers(dstAddr);
658 notifyChildren(dstAddr, mapping, mappingChange);
661 // No reason to send a notification when no subscribers exist
662 if (subscribers != null || dstSubscribers != null) {
663 publishNotification(mapping, eid, subscribers, dstSubscribers, mappingChange);
666 notifyChildren(eid, mapping, mappingChange);
669 private void notifyChildren(Eid eid, MappingRecord mapping, MappingChange mappingChange) {
670 // Update/created only happens for NB mappings. We assume no overlapping prefix support for NB mappings - so
671 // this NB mapping should not have any children. Both for NB first and NB&SB cases all subscribers for SB
672 // prefixes that are equal or more specific to this NB prefix have to be notified of the potential change.
673 // Each subscriber is notified for the prefix that it is currently subscribed to, and MS should return to them
674 // a Map-Reply with the same prefix and update mapping in cases of EID_INTERSECTION_RLOC_NB_FIRST which is a
675 // new option we are creating TODO
676 Set<Eid> childPrefixes = getSubtree(MappingOrigin.Southbound, eid);
677 if (childPrefixes == null || childPrefixes.isEmpty()) {
681 childPrefixes.remove(eid);
682 for (Eid prefix : childPrefixes) {
683 Set<Subscriber> subscribers = getSubscribers(prefix);
684 // No reason to send a notification when no subscribers exist
685 if (subscribers != null) {
686 publishNotification(mapping, prefix, subscribers, null, mappingChange);
691 private void publishNotification(MappingRecord mapping, Eid eid, Set<Subscriber> subscribers,
692 Set<Subscriber> dstSubscribers, MappingChange mappingChange) {
694 // The notifications are used for sending SMR.
695 notificationPublishService.putNotification(MSNotificationInputUtil.toMappingChanged(
696 mapping, eid, subscribers, dstSubscribers, mappingChange));
697 } catch (InterruptedException e) {
698 LOG.warn("Notification publication interrupted!");
703 * Merges adjacent negative prefixes and notifies their subscribers.
705 private void mergeNegativePrefixes(Eid eid) {
706 LOG.debug("Merging negative prefixes starting from EID {}", LispAddressStringifier.getString(eid));
708 // If we delete nodes while we walk up the radix trie the algorithm will give incorrect results, because
709 // removals rearrange relationships in the trie. So we save prefixes to be removed into a HashMap.
710 Map<Eid, MappingData> mergedMappings = new HashMap<>();
712 Eid currentNode = smc.getSiblingPrefix(eid);
713 MappingData mapping = (MappingData) smc.getMapping(null, currentNode);
714 if (mapping != null && mapping.isNegative().or(false)) {
715 mergedMappings.put(currentNode, mapping);
720 Eid previousNode = currentNode;
721 currentNode = smc.getVirtualParentSiblingPrefix(currentNode);
722 while (currentNode != null) {
723 mapping = (MappingData) smc.getMapping(null, currentNode);
724 if (mapping != null && mapping.isNegative().or(false)) {
725 mergedMappings.put(currentNode, mapping);
729 previousNode = currentNode;
730 currentNode = smc.getVirtualParentSiblingPrefix(previousNode);
733 for (Eid key : mergedMappings.keySet()) {
734 removeSbMapping(key, mergedMappings.get(key));
736 smc.removeMapping(eid);
738 addNegativeMapping(getVirtualParent(previousNode));
741 private static Eid getVirtualParent(Eid eid) {
742 if (eid.getAddress() instanceof Ipv4PrefixBinary) {
743 Ipv4PrefixBinary prefix = (Ipv4PrefixBinary) eid.getAddress();
744 short parentPrefixLength = (short) (prefix.getIpv4MaskLength() - 1);
745 byte[] parentPrefix = MaskUtil.normalizeByteArray(prefix.getIpv4AddressBinary().getValue(),
747 return LispAddressUtil.asIpv4PrefixBinaryEid(eid, parentPrefix, parentPrefixLength);
748 } else if (eid.getAddress() instanceof Ipv6PrefixBinary) {
749 Ipv6PrefixBinary prefix = (Ipv6PrefixBinary) eid.getAddress();
750 short parentPrefixLength = (short) (prefix.getIpv6MaskLength() - 1);
751 byte[] parentPrefix = MaskUtil.normalizeByteArray(prefix.getIpv6AddressBinary().getValue(),
753 return LispAddressUtil.asIpv6PrefixBinaryEid(eid, parentPrefix, parentPrefixLength);
759 public synchronized void subscribe(Subscriber subscriber, Eid subscribedEid) {
760 Set<Subscriber> subscribers = getSubscribers(subscribedEid);
761 if (subscribers == null) {
762 subscribers = Sets.newConcurrentHashSet();
763 } else if (subscribers.contains(subscriber)) {
764 // If there is an entry already for this subscriber, remove it, so that it gets the new timestamp
765 subscribers.remove(subscriber);
767 if (LOG.isDebugEnabled()) {
768 LOG.debug("Adding new subscriber {} for EID {}", subscriber.getString(),
769 LispAddressStringifier.getString(subscribedEid));
771 subscribers.add(subscriber);
772 addSubscribers(subscribedEid, subscribers);
775 private void addSubscribers(Eid address, Set<Subscriber> subscribers) {
776 LoggingUtil.logSubscribers(LOG, address, subscribers);
777 subscriberdb.put(address, subscribers);
781 public Set<Subscriber> getSubscribers(Eid address) {
782 if (LOG.isDebugEnabled()) {
783 LOG.debug("Retrieving subscribers for EID {}", LispAddressStringifier.getString(address));
786 Set<Subscriber> subscribers = subscriberdb.get(address);
787 LoggingUtil.logSubscribers(LOG, address, subscribers);
792 * Only remove subscribers if there is no exact match mapping in the map-cache other than the one specified by
793 * origin. Right now we only have two origins, but in case we will have more, we only need to update this method,
794 * not the callers. We use getData() instead of getMapping to do exact match instead of longest prefix match.
796 private void removeSubscribersConditionally(MappingOrigin origin, Eid address) {
797 if (origin == MappingOrigin.Southbound) {
798 if (pmc.getData(address, SubKeys.RECORD) == null) {
799 removeSubscribers(address);
801 } else if (origin == MappingOrigin.Northbound) {
802 if (smc.getData(address, SubKeys.RECORD) == null) {
803 removeSubscribers(address);
808 private void removeSubscribers(Eid address) {
809 if (LOG.isDebugEnabled()) {
810 LOG.debug("Removing subscribers for EID {}", LispAddressStringifier.getString(address));
812 subscriberdb.remove(address);
816 public void addAuthenticationKey(Eid key, MappingAuthkey authKey) {
817 LOG.debug("Adding authentication key '{}' with key-ID {} for {}", authKey.getKeyString(), authKey.getKeyType(),
818 LispAddressStringifier.getString(key));
819 akdb.addAuthenticationKey(key, authKey);
823 public MappingAuthkey getAuthenticationKey(Eid key) {
824 if (LOG.isDebugEnabled()) {
825 LOG.debug("Retrieving authentication key for {}", LispAddressStringifier.getString(key));
827 return akdb.getAuthenticationKey(key);
831 public void removeAuthenticationKey(Eid key) {
832 if (LOG.isDebugEnabled()) {
833 LOG.debug("Removing authentication key for {}", LispAddressStringifier.getString(key));
835 akdb.removeAuthenticationKey(key);
839 public void addData(MappingOrigin origin, Eid key, String subKey, Object data) {
840 if (LOG.isDebugEnabled()) {
841 LOG.debug("Add data of {} for key {} and subkey {}", data.getClass(),
842 LispAddressStringifier.getString(key), subKey);
844 tableMap.get(origin).addData(key, subKey, data);
848 public Object getData(MappingOrigin origin, Eid key, String subKey) {
849 if (LOG.isDebugEnabled()) {
850 LOG.debug("Retrieving data for key {} and subkey {}", LispAddressStringifier.getString(key), subKey);
852 return tableMap.get(origin).getData(key, subKey);
856 public void removeData(MappingOrigin origin, Eid key, String subKey) {
857 if (LOG.isDebugEnabled()) {
858 LOG.debug("Removing data for key {} and subkey {}", LispAddressStringifier.getString(key), subKey);
860 tableMap.get(origin).removeData(key, subKey);
864 public Eid getParentPrefix(Eid key) {
865 return smc.getParentPrefix(key);
870 * Restore all mappings and keys from mdsal datastore.
872 private void restoreDaoFromDatastore() {
873 List<AuthenticationKey> authKeys = dsbe.getAllAuthenticationKeys();
874 List<Mapping> mappings = dsbe.getAllMappings(LogicalDatastoreType.CONFIGURATION);
877 * XXX By default, the operational datastore is not persisted to disk, either at run-time, or on shutdown,
878 * so the following will have no effect (getLastUpdateTimestamp() will fail, since it's reading from
879 * the operational datastore, and even if it didn't getAllMappings() will fail anyway). According to rovarga it
880 * should be possible to turn on persistence for the operational datastore editing
881 * etc/opendaylight/karaf/05-clustering.xml, by setting <persistence>true</persistence>. At the time of writing
882 * the below code block that didn't seem to work though.
884 Long lastUpdateTimestamp = dsbe.getLastUpdateTimestamp();
885 if (lastUpdateTimestamp != null && System.currentTimeMillis() - lastUpdateTimestamp
886 > ConfigIni.getInstance().getRegistrationValiditySb()) {
887 LOG.warn("Restore threshold passed, not restoring operational datastore into DAO");
889 mappings.addAll(dsbe.getAllMappings(LogicalDatastoreType.OPERATIONAL));
891 dsbe.removeLastUpdateTimestamp();
893 LOG.info("Restoring {} mappings and {} keys from datastore into DAO", mappings.size(), authKeys.size());
895 for (Mapping mapping : mappings) {
896 addMapping(mapping.getOrigin(), mapping.getMappingRecord().getEid(),
897 new MappingData(mapping.getMappingRecord()));
900 for (AuthenticationKey authKey : authKeys) {
901 addAuthenticationKey(authKey.getEid(), authKey.getMappingAuthkey());
905 public void destroy() {
906 LOG.info("Mapping System is being destroyed!");
907 dsbe.saveLastUpdateTimestamp();
911 public String printMappings() {
912 sbMappingTimeoutService.removeExpiredMappings();
914 final StringBuilder sb = new StringBuilder();
915 sb.append("Policy map-cache\n----------------\n");
916 sb.append(pmc.printMappings());
917 sb.append("\nSouthbound map-cache\n--------------------\n");
918 sb.append(smc.printMappings());
919 return sb.toString();
923 public String prettyPrintMappings() {
924 sbMappingTimeoutService.removeExpiredMappings();
926 final StringBuilder sb = new StringBuilder();
927 sb.append("Policy map-cache\n----------------\n");
928 sb.append(pmc.prettyPrintMappings());
929 sb.append("\nSouthbound map-cache\n--------------------\n");
930 sb.append(smc.prettyPrintMappings());
931 sb.append("\nSubscribers\n-----------\n");
932 sb.append(prettyPrintSubscribers(subscriberdb));
933 return sb.toString();
936 private static String prettyPrintSubscribers(Map<Eid, Set<Subscriber>> subscribers) {
937 final StringBuilder sb = new StringBuilder();
938 for (Eid eid: subscribers.keySet()) {
940 sb.append(LispAddressStringifier.getString(eid));
942 sb.append(LispMapCacheStringifier.prettyPrintSubscriberSet(subscribers.get(eid), 4));
945 return sb.toString();
949 public String printKeys() {
950 return akdb.printKeys();
954 public String prettyPrintKeys() {
955 return akdb.prettyPrintKeys();
958 public void cleanCaches() {
960 subscriberdb.clear();
964 public void cleanSBMappings() {
965 smc = new SimpleMapCache(sdao);
969 public void setIsMaster(boolean isMaster) {
970 this.isMaster = isMaster;
974 public boolean isMaster() {