/*
- * Copyright (c) 2014 Contextream, Inc. and others. All rights reserved.
+ * Copyright (c) 2014, 2017 Contextream, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
package org.opendaylight.lispflowmapping.implementation.lisp;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Maps;
+import com.google.common.util.concurrent.ThreadFactoryBuilder;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.Enumeration;
-import java.util.HashMap;
import java.util.HashSet;
+import java.util.Iterator;
import java.util.List;
import java.util.Map;
-import java.util.Random;
-import java.util.Map.Entry;
-
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.ThreadFactory;
+import java.util.concurrent.TimeUnit;
import org.apache.commons.lang3.BooleanUtils;
-import org.opendaylight.lispflowmapping.implementation.authentication.LispAuthenticationUtil;
-import org.opendaylight.lispflowmapping.implementation.config.ConfigIni;
-import org.opendaylight.lispflowmapping.implementation.dao.HashMapDb;
-import org.opendaylight.lispflowmapping.implementation.dao.MappingServiceKeyUtil;
-import org.opendaylight.lispflowmapping.implementation.util.DAOMappingUtil;
-import org.opendaylight.lispflowmapping.implementation.util.LispAFIConvertor;
-import org.opendaylight.lispflowmapping.implementation.util.MapNotifyBuilderHelper;
-import org.opendaylight.lispflowmapping.interfaces.dao.ILispDAO;
-import org.opendaylight.lispflowmapping.interfaces.dao.IMappingServiceKey;
-import org.opendaylight.lispflowmapping.interfaces.dao.MappingEntry;
-import org.opendaylight.lispflowmapping.interfaces.dao.MappingServiceRLOCGroup;
-import org.opendaylight.lispflowmapping.interfaces.dao.MappingServiceSubscriberRLOC;
+import org.opendaylight.controller.md.sal.binding.api.NotificationService;
+import org.opendaylight.lispflowmapping.config.ConfigIni;
+import org.opendaylight.lispflowmapping.implementation.util.LoggingUtil;
+import org.opendaylight.lispflowmapping.implementation.util.MSNotificationInputUtil;
+import org.opendaylight.lispflowmapping.interfaces.dao.SubKeys;
+import org.opendaylight.lispflowmapping.interfaces.dao.Subscriber;
import org.opendaylight.lispflowmapping.interfaces.lisp.IMapNotifyHandler;
import org.opendaylight.lispflowmapping.interfaces.lisp.IMapServerAsync;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.LispAFIAddress;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.MapRegister;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.MapRequest;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.eidrecords.EidRecordBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.eidtolocatorrecords.EidToLocatorRecord;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.eidtolocatorrecords.EidToLocatorRecordBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.lispaddress.LispAddressContainer;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.lispaddress.lispaddresscontainer.Address;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.lispaddress.lispaddresscontainer.address.LcafKeyValue;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.lispaddress.lispaddresscontainer.address.LcafSourceDest;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.lispsimpleaddress.primitiveaddress.DistinguishedName;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.locatorrecords.LocatorRecord;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.mapnotifymessage.MapNotifyBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.maprequest.ItrRloc;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.maprequest.ItrRlocBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.maprequest.SourceEidBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.maprequestnotification.MapRequestBuilder;
+import org.opendaylight.lispflowmapping.interfaces.lisp.ISmrNotificationListener;
+import org.opendaylight.lispflowmapping.interfaces.lisp.SmrEvent;
+import org.opendaylight.lispflowmapping.interfaces.mappingservice.IMappingService;
+import org.opendaylight.lispflowmapping.lisp.authentication.LispAuthenticationUtil;
+import org.opendaylight.lispflowmapping.lisp.type.LispMessage;
+import org.opendaylight.lispflowmapping.lisp.type.MappingData;
+import org.opendaylight.lispflowmapping.lisp.util.LispAddressStringifier;
+import org.opendaylight.lispflowmapping.lisp.util.LispAddressUtil;
+import org.opendaylight.lispflowmapping.lisp.util.MapNotifyBuilderHelper;
+import org.opendaylight.lispflowmapping.lisp.util.MapRequestUtil;
+import org.opendaylight.lispflowmapping.lisp.util.MappingRecordUtil;
+import org.opendaylight.lispflowmapping.lisp.util.SourceDestKeyHelper;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.SourceDestKey;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.inet.binary.types.rev160303.IpAddressBinary;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MapRegister;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.SiteId;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.eid.container.Eid;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.eid.list.EidItem;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.eid.list.EidItemBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapnotifymessage.MapNotifyBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.authkey.container.MappingAuthkey;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.record.container.MappingRecord;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.record.list.MappingRecordItem;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.record.list.MappingRecordItemBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.maprequestnotification.MapRequestBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.transport.address.TransportAddress;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.transport.address.TransportAddressBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.mappingservice.rev150906.MappingChanged;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.mappingservice.rev150906.MappingOrigin;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.mappingservice.rev150906.OdlMappingserviceListener;
+import org.opendaylight.yangtools.concepts.ListenerRegistration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class MapServer extends AbstractLispComponent implements IMapServerAsync {
+public class MapServer implements IMapServerAsync, OdlMappingserviceListener, ISmrNotificationListener {
protected static final Logger LOG = LoggerFactory.getLogger(MapServer.class);
-
- private static final ConfigIni configIni = new ConfigIni();
- private static final boolean overwriteConfig = configIni.mappingOverwriteIsSet();
- private boolean overwrite;
-
- public MapServer(ILispDAO dao) {
- this(dao, overwriteConfig);
+ private static final byte[] ALL_ZEROES_XTR_ID = new byte[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ,0};
+ private IMappingService mapService;
+ private boolean subscriptionService;
+ private IMapNotifyHandler notifyHandler;
+ private NotificationService notificationService;
+ private ListenerRegistration<MapServer> mapServerListenerRegistration;
+ private SmrScheduler scheduler;
+
+ public MapServer(IMappingService mapService, boolean subscriptionService,
+ IMapNotifyHandler notifyHandler, NotificationService notificationService) {
+ Preconditions.checkNotNull(mapService);
+ this.mapService = mapService;
+ this.subscriptionService = subscriptionService;
+ this.notifyHandler = notifyHandler;
+ this.notificationService = notificationService;
+ if (notificationService != null) {
+ notificationService.registerNotificationListener(this);
+ }
+ scheduler = new SmrScheduler();
}
- public MapServer(ILispDAO dao, boolean overwrite) {
- this(dao, overwrite, true);
+ @Override
+ public void setSubscriptionService(boolean subscriptionService) {
+ this.subscriptionService = subscriptionService;
}
- public MapServer(ILispDAO dao, boolean overwrite, boolean authenticate) {
- this(dao, overwrite, authenticate, true);
- }
+ @SuppressWarnings("unchecked")
+ public void handleMapRegister(MapRegister mapRegister) {
+ boolean mappingUpdated = false;
+ boolean oldMappingRemoved = false;
+ boolean merge = ConfigIni.getInstance().mappingMergeIsSet() && mapRegister.isMergeEnabled();
+ Set<Subscriber> subscribers = null;
+ MappingRecord oldMapping;
+
+ if (merge) {
+ if (!mapRegister.isXtrSiteIdPresent() || mapRegister.getXtrId() == null) {
+ LOG.error("Merge bit is set in Map-Register, but xTR-ID is not present. Will not merge.");
+ merge = false;
+ } else if (Arrays.equals(mapRegister.getXtrId().getValue(), ALL_ZEROES_XTR_ID)) {
+ LOG.warn("Merge bit is set in Map-Register, but xTR-ID is all zeroes.");
+ }
+ }
- public MapServer(ILispDAO dao, boolean overwrite, boolean authenticate, boolean iterateAuthenticationMask) {
- super(dao, authenticate, iterateAuthenticationMask);
- this.overwrite = overwrite;
- }
+ for (MappingRecordItem record : mapRegister.getMappingRecordItem()) {
+ MappingRecord mapping = record.getMappingRecord();
+ Eid eid = mapping.getEid();
+ MappingData mappingData = new MappingData(mapping, System.currentTimeMillis());
+ mappingData.setMergeEnabled(merge);
+ mappingData.setXtrId(mapRegister.getXtrId());
+
+ oldMapping = getMappingRecord(mapService.getMapping(MappingOrigin.Southbound, eid));
+ mapService.addMapping(MappingOrigin.Southbound, eid, getSiteId(mapRegister), mappingData);
+ if (oldMapping != null && MappingRecordUtil.isNegativeMapping(oldMapping)) {
+ mapService.removeMapping(MappingOrigin.Southbound, oldMapping.getEid());
+ oldMappingRemoved = true;
+ }
- private static InetAddress getLocalAddress() {
- try {
- Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
- while (interfaces.hasMoreElements()) {
- NetworkInterface current = interfaces.nextElement();
- LOG.debug("Interface " + current.toString());
- if (!current.isUp() || current.isLoopback() || current.isVirtual())
- continue;
- Enumeration<InetAddress> addresses = current.getInetAddresses();
- while (addresses.hasMoreElements()) {
- InetAddress current_addr = addresses.nextElement();
- // Skip loopback and link local addresses
- if (current_addr.isLoopbackAddress() || current_addr.isLinkLocalAddress())
- continue;
- LOG.debug(current_addr.getHostAddress());
- return current_addr;
+ if (subscriptionService) {
+ MappingRecord newMapping = merge
+ ? getMappingRecord(mapService.getMapping(MappingOrigin.Southbound, eid)) : mapping;
+
+ if (mappingChanged(oldMapping, newMapping)) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Mapping update occured for {} SMRs will be sent for its subscribers.",
+ LispAddressStringifier.getString(mapping.getEid()));
+ }
+ subscribers = getSubscribers(eid);
+ if (oldMapping != null && !oldMapping.getEid().equals(eid)) {
+ subscribers = addParentSubscribers(eid, subscribers);
+ }
+ LoggingUtil.logSubscribers(LOG, eid, subscribers);
+ handleSmr(eid, subscribers);
+ if (oldMapping != null && oldMappingRemoved && !oldMapping.getEid().equals(eid)) {
+ subscribers = getSubscribers(oldMapping.getEid());
+ LoggingUtil.logSubscribers(LOG, oldMapping.getEid(), subscribers);
+ handleSmr(oldMapping.getEid(), subscribers);
+ }
+ mappingUpdated = true;
}
}
- } catch (SocketException se) {
}
- return null;
- }
-
- private static MapRequest buildSMR(EidToLocatorRecord eidRecord) {
- MapRequestBuilder builder = new MapRequestBuilder();
- builder.setAuthoritative(false);
- builder.setMapDataPresent(false);
- builder.setPitr(false);
- builder.setProbe(false);
- builder.setSmr(true);
- builder.setSmrInvoked(false);
-
- builder.setEidRecord(new ArrayList<org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.eidrecords.EidRecord>());
- LispAddressContainer container = eidRecord.getLispAddressContainer();
- short mask = (short) eidRecord.getMaskLength();
- builder.getEidRecord().add(new EidRecordBuilder().setMask(mask).setLispAddressContainer(container).build());
-
- builder.setItrRloc(new ArrayList<ItrRloc>());
- builder.getItrRloc().add(new ItrRlocBuilder().setLispAddressContainer(LispAFIConvertor.toContainer(getLocalAddress())).build());
-
- builder.setMapReply(null);
- builder.setNonce(new Random().nextLong());
-
- // XXX For now we set source EID to queried EID...
- builder.setSourceEid(new SourceEidBuilder().setLispAddressContainer(container).build());
- return builder.build();
- }
-
- public void handleMapRegister(MapRegister mapRegister, boolean smr, IMapNotifyHandler callback) {
- if (dao == null) {
- LOG.warn("handleMapRegister called while dao is uninitialized");
- } else {
- boolean failed = false;
- String password = null;
- for (EidToLocatorRecord eidRecord : mapRegister.getEidToLocatorRecord()) {
- if (shouldAuthenticate()) {
- password = getPassword(eidRecord.getLispAddressContainer(), eidRecord.getMaskLength());
- if (!LispAuthenticationUtil.validate(mapRegister, password)) {
- LOG.warn("Authentication failed");
- failed = true;
- break;
+ if (BooleanUtils.isTrue(mapRegister.isWantMapNotify())) {
+ LOG.trace("MapRegister wants MapNotify");
+ MapNotifyBuilder builder = new MapNotifyBuilder();
+ List<TransportAddress> rlocs = null;
+ if (merge) {
+ Set<IpAddressBinary> notifyRlocs = new HashSet<IpAddressBinary>();
+ List<MappingRecordItem> mergedMappings = new ArrayList<MappingRecordItem>();
+ for (MappingRecordItem record : mapRegister.getMappingRecordItem()) {
+ MappingRecord mapping = record.getMappingRecord();
+ MappingRecord currentRecord = getMappingRecord(mapService.getMapping(MappingOrigin.Southbound,
+ mapping.getEid()));
+ mergedMappings.add(new MappingRecordItemBuilder().setMappingRecord(currentRecord).build());
+ Set<IpAddressBinary> sourceRlocs = (Set<IpAddressBinary>) mapService.getData(
+ MappingOrigin.Southbound, mapping.getEid(), SubKeys.SRC_RLOCS);
+ if (sourceRlocs != null) {
+ notifyRlocs.addAll(sourceRlocs);
}
}
- boolean mappingChanged = saveRlocs(eidRecord, smr);
- if (smr && mappingChanged) {
- sendSmrs(eidRecord, callback);
+ MapNotifyBuilderHelper.setFromMapRegisterAndMappingRecordItems(builder, mapRegister, mergedMappings);
+ // send map-notify to merge group only when mapping record is changed
+ if (mappingUpdated) {
+ rlocs = getTransportAddresses(notifyRlocs);
}
+ } else {
+ MapNotifyBuilderHelper.setFromMapRegister(builder, mapRegister);
}
- if (!failed) {
- MapNotifyBuilder builder = new MapNotifyBuilder();
- if (BooleanUtils.isTrue(mapRegister.isWantMapNotify())) {
- LOG.trace("MapRegister wants MapNotify");
- MapNotifyBuilderHelper.setFromMapRegister(builder, mapRegister);
- if (shouldAuthenticate()) {
- builder.setAuthenticationData(LispAuthenticationUtil.createAuthenticationData(builder.build(), password));
- }
- callback.handleMapNotify(builder.build());
+ List<MappingRecordItem> mappings = builder.getMappingRecordItem();
+ if (mappings != null && mappings.get(0) != null && mappings.get(0).getMappingRecord() != null
+ && mappings.get(0).getMappingRecord().getEid() != null) {
+ MappingAuthkey authkey = mapService.getAuthenticationKey(mappings.get(0).getMappingRecord().getEid());
+ if (authkey != null) {
+ builder.setAuthenticationData(LispAuthenticationUtil.createAuthenticationData(builder.build(),
+ authkey.getKeyString()));
}
}
+ notifyHandler.handleMapNotify(builder.build(), rlocs);
}
}
- public boolean saveRlocs(EidToLocatorRecord eidRecord, boolean checkForChanges) {
- Map<String, MappingServiceRLOCGroup> rlocGroups = new HashMap<String, MappingServiceRLOCGroup>();
- if (eidRecord.getLocatorRecord() != null) {
- for (LocatorRecord locatorRecord : eidRecord.getLocatorRecord()) {
- String subkey = getAddressKey(locatorRecord.getLispAddressContainer().getAddress());
- if (!rlocGroups.containsKey(subkey)) {
- rlocGroups.put(subkey, new MappingServiceRLOCGroup(eidRecord.getRecordTtl(), eidRecord.getAction(), eidRecord.isAuthoritative()));
- }
- rlocGroups.get(subkey).addRecord(locatorRecord);
- }
- }
- List<MappingEntry<MappingServiceRLOCGroup>> entries = new ArrayList<>();
- for (String subkey : rlocGroups.keySet()) {
- entries.add(new MappingEntry<>(subkey, rlocGroups.get(subkey)));
+ private static List<TransportAddress> getTransportAddresses(Set<IpAddressBinary> addresses) {
+ List<TransportAddress> rlocs = new ArrayList<TransportAddress>();
+ for (IpAddressBinary address : addresses) {
+ TransportAddressBuilder tab = new TransportAddressBuilder();
+ tab.setIpAddress(address);
+ tab.setPort(new PortNumber(LispMessage.PORT_NUM));
+ rlocs.add(tab.build());
}
+ return rlocs;
+ }
- if (eidRecord.getLispAddressContainer().getAddress() instanceof LcafSourceDest) {
- Entry<IMappingServiceKey, List<MappingServiceRLOCGroup>> oldMapping= null, newMapping = null;
- LispAFIAddress srcAddr = getSrcForLcafSrcDst(eidRecord.getLispAddressContainer());
- LispAFIAddress dstAddr = getDstForLcafSrcDst(eidRecord.getLispAddressContainer());
- short srcMask = getSrcMaskForLcafSrcDst(eidRecord.getLispAddressContainer());
- short dstMask = getDstMaskForLcafSrcDst(eidRecord.getLispAddressContainer());
+ private static SiteId getSiteId(MapRegister mapRegister) {
+ return (mapRegister.getSiteId() != null) ? new SiteId(mapRegister.getSiteId()) : null;
+ }
- if (checkForChanges) {
- oldMapping = DAOMappingUtil.getMappingExact(srcAddr, dstAddr, srcMask, dstMask, dao);
- }
- IMappingServiceKey dstKey = MappingServiceKeyUtil.generateMappingServiceKey(dstAddr, dstMask);
- ILispDAO srcDstDao = (ILispDAO) dao.getSpecific(dstKey, LCAF_SRCDST_SUBKEY);
- if (srcDstDao == null) {
- srcDstDao = new HashMapDb();
- dao.put(dstKey, new MappingEntry<>(LCAF_SRCDST_SUBKEY, srcDstDao));
- }
- IMappingServiceKey srcKey = MappingServiceKeyUtil.generateMappingServiceKey(srcAddr, srcMask);
- srcDstDao.put(srcKey, entries.toArray(new MappingEntry[entries.size()]));
- if (checkForChanges) {
- newMapping = DAOMappingUtil.getMappingExact(srcAddr, dstAddr, srcMask, dstMask, dao);
- if (!newMapping.getValue().equals(oldMapping.getValue())) {
- return true;
- }
- }
- } else {
- List<MappingServiceRLOCGroup> oldLocators = null, newLocators = null;
- if (checkForChanges) {
- oldLocators = DAOMappingUtil.getLocatorsByEidToLocatorRecord(eidRecord, dao, shouldIterateMask());
- }
- IMappingServiceKey key = MappingServiceKeyUtil.generateMappingServiceKey(eidRecord.getLispAddressContainer(),
- eidRecord.getMaskLength());
- dao.put(key, entries.toArray(new MappingEntry[entries.size()]));
- if (checkForChanges) {
- newLocators = DAOMappingUtil.getLocatorsByEidToLocatorRecord(eidRecord, dao, shouldIterateMask());
- if (!newLocators.equals(oldLocators)) {
- return true;
+ private static MappingRecord getMappingRecord(MappingData mappingData) {
+ return (mappingData != null) ? mappingData.getRecord() : null;
+ }
+
+ @Override
+ public void onMappingChanged(MappingChanged notification) {
+ LOG.trace("MappingChanged event of type: `{}'", notification.getChangeType());
+ if (subscriptionService) {
+ Eid eid = notification.getMappingRecord().getEid();
+ Set<Subscriber> subscribers = MSNotificationInputUtil.toSubscriberSet(notification.getSubscriberItem());
+ LoggingUtil.logSubscribers(LOG, eid, subscribers);
+ if (mapService.isMaster()) {
+ sendSmrs(eid, subscribers);
+ if (eid.getAddress() instanceof SourceDestKey) {
+ Set<Subscriber> dstSubscribers = MSNotificationInputUtil.toSubscriberSetFromDst(
+ notification.getDstSubscriberItem());
+ LoggingUtil.logSubscribers(LOG, SourceDestKeyHelper.getDstBinary(eid), dstSubscribers);
+ sendSmrs(SourceDestKeyHelper.getDstBinary(eid), dstSubscribers);
}
}
}
- return false;
}
- private String getAddressKey(Address address) {
- if (address instanceof LcafKeyValue) {
- LcafKeyValue keyVal = (LcafKeyValue) address;
- if (keyVal.getLcafKeyValueAddressAddr().getKey().getPrimitiveAddress() instanceof DistinguishedName) {
- return ((DistinguishedName) keyVal.getLcafKeyValueAddressAddr().getKey().getPrimitiveAddress()).getDistinguishedNameAddress().getDistinguishedName();
- }
- }
- if (shouldOverwrite()) {
- return ADDRESS_SUBKEY;
- } else {
- return String.valueOf(address.hashCode());
+ private static boolean mappingChanged(MappingRecord oldMapping, MappingRecord newMapping) {
+ // We only check for fields we care about
+ // XXX: This code needs to be checked and updated when the YANG model for MappingRecord is modified
+ Preconditions.checkNotNull(newMapping, "The new mapping should never be null");
+ if (oldMapping == null) {
+ LOG.trace("mappingChanged(): old mapping is null");
+ return true;
+ } else if (!Objects.equals(oldMapping.getEid(), newMapping.getEid())) {
+ LOG.trace("mappingChanged(): EID");
+ return true;
+ } else if (!Objects.equals(oldMapping.getLocatorRecord(), newMapping.getLocatorRecord())) {
+ LOG.trace("mappingChanged(): RLOC");
+ return true;
+ } else if (!Objects.equals(oldMapping.getAction(), newMapping.getAction())) {
+ LOG.trace("mappingChanged(): action");
+ return true;
+ } else if (!Objects.equals(oldMapping.getRecordTtl(), newMapping.getRecordTtl())) {
+ LOG.trace("mappingChanged(): TTL");
+ return true;
+ } else if (!Objects.equals(oldMapping.getMapVersion(), newMapping.getMapVersion())) {
+ LOG.trace("mappingChanged(): mapping version");
+ return true;
}
+ return false;
}
- public String getAuthenticationKey(LispAddressContainer address, int maskLen) {
- return getPassword(address, maskLen);
- }
+ private void handleSmr(Eid eid, Set<Subscriber> subscribers) {
+ sendSmrs(eid, subscribers);
- public void removeAuthenticationKey(LispAddressContainer address, int maskLen) {
- if (address.getAddress() instanceof LcafSourceDest) {
- ILispDAO srcDstDao = getSrcDstInnerDao(address, maskLen);
- if (srcDstDao != null) {
- IMappingServiceKey srcKey = MappingServiceKeyUtil.generateMappingServiceKey(getSrcForLcafSrcDst(address),
- getSrcMaskForLcafSrcDst(address));
- srcDstDao.removeSpecific(srcKey, PASSWORD_SUBKEY);
- }
- } else {
- IMappingServiceKey key = MappingServiceKeyUtil.generateMappingServiceKey(address, maskLen);
- dao.removeSpecific(key, PASSWORD_SUBKEY);
+ // For SrcDst LCAF also send SMRs to Dst prefix
+ if (eid.getAddress() instanceof SourceDestKey) {
+ Eid dstAddr = SourceDestKeyHelper.getDstBinary(eid);
+ Set<Subscriber> dstSubs = getSubscribers(dstAddr);
+ sendSmrs(dstAddr, dstSubs);
}
}
- public void addAuthenticationKey(LispAddressContainer address, int maskLen, String key) {
- IMappingServiceKey mappingServiceKey = MappingServiceKeyUtil.generateMappingServiceKey(address, maskLen);
- if (address.getAddress() instanceof LcafSourceDest) {
- IMappingServiceKey srcKey = MappingServiceKeyUtil.generateMappingServiceKey(getSrcForLcafSrcDst(address),
- getSrcMaskForLcafSrcDst(address));
- ILispDAO srcDstDao = getOrInstantiateSrcDstInnerDao(address, maskLen);
- srcDstDao.put(srcKey, new MappingEntry<String>(PASSWORD_SUBKEY, key));
- } else {
- dao.put(mappingServiceKey, new MappingEntry<String>(PASSWORD_SUBKEY, key));
+ private void sendSmrs(Eid eid, Set<Subscriber> subscribers) {
+ if (subscribers == null) {
+ return;
}
+ final MapRequestBuilder mrb = MapRequestUtil.prepareSMR(eid, LispAddressUtil.toRloc(getLocalAddress()));
+ LOG.trace("Built SMR packet: " + mrb.build().toString());
+
+ scheduler.scheduleSmrs(mrb, subscribers.iterator());
+ }
+
+ @SuppressWarnings("unchecked")
+ private Set<Subscriber> getSubscribers(Eid address) {
+ return (Set<Subscriber>) mapService.getData(MappingOrigin.Southbound, address, SubKeys.SUBSCRIBERS);
}
- public void removeMapping(LispAddressContainer address, int maskLen, boolean smr, IMapNotifyHandler callback) {
- Entry<IMappingServiceKey, List<MappingServiceRLOCGroup>> mapping;
- ILispDAO db;
- if (address.getAddress() instanceof LcafSourceDest) {
- db = getSrcDstInnerDao(address, maskLen);
- LispAFIAddress srcAddr = getSrcForLcafSrcDst(address);
- short srcMask = getSrcMaskForLcafSrcDst(address);
- mapping = DAOMappingUtil.getMappingForEid(srcAddr, srcMask, db);
- } else {
- db = dao;
- mapping = DAOMappingUtil.getMappingForEid(LispAFIConvertor.toAFI(address), maskLen, db);
+ private Set<Subscriber> addParentSubscribers(Eid eid, Set<Subscriber> subscribers) {
+ Eid parentPrefix = mapService.getParentPrefix(eid);
+ if (parentPrefix == null) {
+ return subscribers;
}
- if (smr) {
- HashSet<MappingServiceSubscriberRLOC> subscribers = getSubscribers(address, maskLen);
- // mapping is removed before first SMR is sent to avoid inconsistent replies
- removeMappingRlocs(mapping, db);
- handleSmr(new EidToLocatorRecordBuilder().setLispAddressContainer(address).
- setMaskLength((short) maskLen).build(), subscribers, callback);
- db.removeSpecific(mapping.getKey(), SUBSCRIBERS_SUBKEY);
- } else {
- removeMappingRlocs(mapping, db);
- db.removeSpecific(mapping.getKey(), SUBSCRIBERS_SUBKEY);
+
+ Set<Subscriber> parentSubscribers = getSubscribers(parentPrefix);
+ if (parentSubscribers != null) {
+ if (subscribers != null) {
+ subscribers.addAll(parentSubscribers);
+ } else {
+ subscribers = parentSubscribers;
+ }
}
+ return subscribers;
}
- private void removeMappingRlocs(Entry<IMappingServiceKey, List<MappingServiceRLOCGroup>> mapping, ILispDAO db) {
- for (MappingServiceRLOCGroup group : mapping.getValue()) {
- for (LocatorRecord record : group.getRecords()) {
- db.removeSpecific(mapping.getKey(), getAddressKey(record.getLispAddressContainer().getAddress()));
+ private void addSubscribers(Eid address, Set<Subscriber> subscribers) {
+ mapService.addData(MappingOrigin.Southbound, address, SubKeys.SUBSCRIBERS, subscribers);
+ }
+
+ private static InetAddress getLocalAddress() {
+ try {
+ Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
+ while (interfaces.hasMoreElements()) {
+ NetworkInterface current = interfaces.nextElement();
+ LOG.trace("Interface " + current.toString());
+ if (!current.isUp() || current.isLoopback() || current.isVirtual()) {
+ continue;
+ }
+ Enumeration<InetAddress> addresses = current.getInetAddresses();
+ while (addresses.hasMoreElements()) {
+ InetAddress currentAddr = addresses.nextElement();
+ // Skip loopback and link local addresses
+ if (currentAddr.isLoopbackAddress() || currentAddr.isLinkLocalAddress()) {
+ continue;
+ }
+ LOG.debug(currentAddr.getHostAddress());
+ return currentAddr;
+ }
}
+ } catch (SocketException se) {
+ LOG.debug("Caught socket exception", se);
}
+ return null;
}
- private void sendSmrs(EidToLocatorRecord record, IMapNotifyHandler callback) {
- LispAddressContainer eid = record.getLispAddressContainer();
- HashSet<MappingServiceSubscriberRLOC> subscribers;
+ @Override
+ public void onSmrInvokedReceived(SmrEvent event) {
+ scheduler.smrReceived(event);
+ }
- subscribers = getSubscribers(eid, record.getMaskLength());
- handleSmr(record, subscribers, callback);
+ /**
+ * Task scheduler is responsible for resending SMR messages to a subscriber (xTR)
+ * {@value ConfigIni#LISP_SMR_RETRY_COUNT} times, or until {@link ISmrNotificationListener#onSmrInvokedReceived}
+ * is triggered.
+ */
+ private class SmrScheduler {
+ final int cpuCores = Runtime.getRuntime().availableProcessors();
+ private final ThreadFactory threadFactory = new ThreadFactoryBuilder()
+ .setNameFormat("smr-executor-%d").build();
+ private final ScheduledExecutorService executor = Executors.newScheduledThreadPool(cpuCores * 2, threadFactory);
+ private final Map<Eid, Map<Subscriber, ScheduledFuture<?>>> eidFutureMap = Maps.newConcurrentMap();
+
+ void scheduleSmrs(MapRequestBuilder mrb, Iterator<Subscriber> subscribers) {
+ final Eid srcEid = mrb.getSourceEid().getEid();
+ cancelExistingFuturesForEid(srcEid);
+
+ final Map<Subscriber, ScheduledFuture<?>> subscriberFutureMap = Maps.newConcurrentMap();
+
+ // Using Iterator ensures that we don't get a ConcurrentModificationException when removing a Subscriber
+ // from a Set.
+ while (subscribers.hasNext()) {
+ Subscriber subscriber = subscribers.next();
+ if (subscriber.timedOut()) {
+ LOG.debug("Lazy removing expired subscriber entry " + subscriber.getString());
+ subscribers.remove();
+ } else {
+ final ScheduledFuture<?> future = executor.scheduleAtFixedRate(new CancellableRunnable(
+ mrb, subscriber), 0L, ConfigIni.getInstance().getSmrTimeout(), TimeUnit.MILLISECONDS);
+ subscriberFutureMap.put(subscriber, future);
+ }
+ }
- // For SrcDst LCAF also send SMRs to Dst prefix
- if (eid.getAddress() instanceof LcafSourceDest) {
- LispAddressContainer dstAddr = LispAFIConvertor.toContainer(getDstForLcafSrcDst(eid));
- short dstMask = getDstMaskForLcafSrcDst(eid);
- subscribers = getSubscribers(dstAddr, dstMask);
- EidToLocatorRecord newRecord = new EidToLocatorRecordBuilder().setAction(record.getAction()).
- setAuthoritative(record.isAuthoritative()).setLocatorRecord(record.getLocatorRecord()).
- setMapVersion(record.getMapVersion()).setRecordTtl(record.getRecordTtl()).
- setLispAddressContainer(dstAddr).setMaskLength(dstMask).build();
- handleSmr(newRecord, subscribers, callback);
+ if (subscriberFutureMap.isEmpty()) {
+ return;
+ }
+ eidFutureMap.put(srcEid, subscriberFutureMap);
}
- }
- private void handleSmr(EidToLocatorRecord record, HashSet<MappingServiceSubscriberRLOC> subscribers,
- IMapNotifyHandler callback) {
- if (subscribers == null) {
- return;
+ void smrReceived(SmrEvent event) {
+ final List<Subscriber> subscriberList = event.getSubscriberList();
+ for (Subscriber subscriber : subscriberList) {
+ LOG.trace("SMR-invoked event, EID {}, subscriber {}", LispAddressStringifier.getString(event.getEid()),
+ subscriber.getString());
+ final Map<Subscriber, ScheduledFuture<?>> subscriberFutureMap = eidFutureMap.get(event.getEid());
+ if (subscriberFutureMap != null) {
+ final ScheduledFuture<?> future = subscriberFutureMap.get(subscriber);
+ if (future != null && !future.isCancelled()) {
+ future.cancel(true);
+ LOG.debug("SMR-invoked MapRequest received, scheduled task for subscriber {}, EID {} with"
+ + " nonce {} has been cancelled", subscriber.getString(),
+ LispAddressStringifier.getString(event.getEid()), event.getNonce());
+ subscriberFutureMap.remove(subscriber);
+ }
+ if (subscriberFutureMap.isEmpty()) {
+ eidFutureMap.remove(event.getEid());
+ }
+ }
+ }
}
- MapRequest mapRequest = buildSMR(record);
- LOG.trace("Built SMR packet: " + mapRequest.toString());
- for (MappingServiceSubscriberRLOC rloc : subscribers) {
- if (rloc.timedOut()) {
- LOG.trace("Lazy removing expired subscriber entry " + rloc.toString());
- subscribers.remove(rloc);
- } else {
+
+ private void cancelExistingFuturesForEid(Eid eid) {
+ synchronized (eidFutureMap) {
+ if (eidFutureMap.containsKey(eid)) {
+ final Map<Subscriber, ScheduledFuture<?>> subscriberFutureMap = eidFutureMap.get(eid);
+ Iterator<Subscriber> oldSubscribers = subscriberFutureMap.keySet().iterator();
+ while (oldSubscribers.hasNext()) {
+ Subscriber subscriber = oldSubscribers.next();
+ ScheduledFuture<?> subscriberFuture = subscriberFutureMap.get(subscriber);
+ subscriberFuture.cancel(true);
+ }
+ eidFutureMap.remove(eid);
+ }
+ }
+ }
+
+ private final class CancellableRunnable implements Runnable {
+ private MapRequestBuilder mrb;
+ private Subscriber subscriber;
+ private int executionCount = 1;
+
+ CancellableRunnable(MapRequestBuilder mrb, Subscriber subscriber) {
+ this.mrb = mrb;
+ this.subscriber = subscriber;
+ }
+
+ @SuppressWarnings("checkstyle:IllegalCatch")
+ @Override
+ public void run() {
+ final Eid srcEid = mrb.getSourceEid().getEid();
+
try {
- callback.handleSMR(mapRequest, rloc.getSrcRloc());
+ // The address stored in the SMR's EID record is used as Source EID in the SMR-invoked
+ // Map-Request. To ensure consistent behavior it is set to the value used to originally request
+ // a given mapping.
+ if (executionCount <= ConfigIni.getInstance().getSmrRetryCount()) {
+ synchronized (mrb) {
+ mrb.setEidItem(new ArrayList<EidItem>());
+ mrb.getEidItem().add(new EidItemBuilder().setEid(subscriber.getSrcEid()).build());
+ notifyHandler.handleSMR(mrb.build(), subscriber.getSrcRloc());
+ if (LOG.isTraceEnabled()) {
+ LOG.trace("Attempt #{} to send SMR to subscriber {} for EID {}",
+ executionCount,
+ subscriber.getString(),
+ LispAddressStringifier.getString(mrb.getSourceEid().getEid()));
+ }
+ }
+ } else {
+ LOG.trace("Cancelling execution of a SMR Map-Request after {} failed attempts.",
+ executionCount - 1);
+ cancelAndRemove(subscriber, srcEid);
+ return;
+ }
} catch (Exception e) {
- LOG.error("Errors encountered while handling SMR:" + e.getStackTrace());
+ LOG.error("Errors encountered while handling SMR:", e);
+ cancelAndRemove(subscriber, srcEid);
+ return;
}
+ executionCount++;
}
- }
- IMappingServiceKey key = MappingServiceKeyUtil.generateMappingServiceKey(record.getLispAddressContainer(),
- record.getMaskLength());
- dao.put(key, new MappingEntry<HashSet<MappingServiceSubscriberRLOC>>(SUBSCRIBERS_SUBKEY, subscribers));
- }
- public boolean shouldOverwrite() {
- return overwrite;
- }
+ private void cancelAndRemove(Subscriber subscriber, Eid eid) {
+ final Map<Subscriber, ScheduledFuture<?>> subscriberFutureMap = eidFutureMap.get(eid);
+ if (subscriberFutureMap == null) {
+ LOG.warn("Couldn't find subscriber {} in SMR scheduler internal list", subscriber);
+ return;
+ }
- public void setOverwrite(boolean overwrite) {
- this.overwrite = overwrite;
+ if (subscriberFutureMap.containsKey(subscriber)) {
+ ScheduledFuture<?> eidFuture = subscriberFutureMap.get(subscriber);
+ subscriberFutureMap.remove(subscriber);
+ eidFuture.cancel(false);
+ }
+ if (subscriberFutureMap.isEmpty()) {
+ eidFutureMap.remove(eid);
+ }
+ }
+ }
}
-
}