Bug 9116: SMR children of a prefix too
[lispflowmapping.git] / mappingservice / implementation / src / main / java / org / opendaylight / lispflowmapping / implementation / lisp / MapServer.java
1 /*
2  * Copyright (c) 2014, 2017 Contextream, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8
9 package org.opendaylight.lispflowmapping.implementation.lisp;
10
11 import com.google.common.base.Preconditions;
12 import com.google.common.collect.Maps;
13 import com.google.common.collect.Sets;
14 import com.google.common.util.concurrent.ThreadFactoryBuilder;
15 import java.net.InetAddress;
16 import java.net.NetworkInterface;
17 import java.net.SocketException;
18 import java.util.ArrayList;
19 import java.util.Arrays;
20 import java.util.Enumeration;
21 import java.util.HashSet;
22 import java.util.Iterator;
23 import java.util.List;
24 import java.util.Map;
25 import java.util.Objects;
26 import java.util.Set;
27 import java.util.concurrent.Executors;
28 import java.util.concurrent.ScheduledExecutorService;
29 import java.util.concurrent.ScheduledFuture;
30 import java.util.concurrent.ThreadFactory;
31 import java.util.concurrent.TimeUnit;
32 import org.apache.commons.lang3.BooleanUtils;
33 import org.opendaylight.controller.md.sal.binding.api.NotificationService;
34 import org.opendaylight.lispflowmapping.config.ConfigIni;
35 import org.opendaylight.lispflowmapping.implementation.util.LoggingUtil;
36 import org.opendaylight.lispflowmapping.implementation.util.MSNotificationInputUtil;
37 import org.opendaylight.lispflowmapping.interfaces.dao.SubKeys;
38 import org.opendaylight.lispflowmapping.interfaces.dao.Subscriber;
39 import org.opendaylight.lispflowmapping.interfaces.lisp.IMapNotifyHandler;
40 import org.opendaylight.lispflowmapping.interfaces.lisp.IMapServerAsync;
41 import org.opendaylight.lispflowmapping.interfaces.lisp.ISmrNotificationListener;
42 import org.opendaylight.lispflowmapping.interfaces.lisp.SmrEvent;
43 import org.opendaylight.lispflowmapping.interfaces.mappingservice.IMappingService;
44 import org.opendaylight.lispflowmapping.lisp.authentication.LispAuthenticationUtil;
45 import org.opendaylight.lispflowmapping.lisp.type.LispMessage;
46 import org.opendaylight.lispflowmapping.lisp.type.MappingData;
47 import org.opendaylight.lispflowmapping.lisp.util.LispAddressStringifier;
48 import org.opendaylight.lispflowmapping.lisp.util.LispAddressUtil;
49 import org.opendaylight.lispflowmapping.lisp.util.MapNotifyBuilderHelper;
50 import org.opendaylight.lispflowmapping.lisp.util.MapRequestUtil;
51 import org.opendaylight.lispflowmapping.lisp.util.MappingRecordUtil;
52 import org.opendaylight.lispflowmapping.lisp.util.MaskUtil;
53 import org.opendaylight.lispflowmapping.lisp.util.SourceDestKeyHelper;
54 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber;
55 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.Address;
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.opendaylight.lfm.inet.binary.types.rev160303.IpAddressBinary;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.binary.address.types.rev160504.augmented.lisp.address.address.Ipv4PrefixBinary;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.binary.address.types.rev160504.augmented.lisp.address.address.Ipv4PrefixBinaryBuilder;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.binary.address.types.rev160504.augmented.lisp.address.address.Ipv6PrefixBinary;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.binary.address.types.rev160504.augmented.lisp.address.address.Ipv6PrefixBinaryBuilder;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MapRegister;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.SiteId;
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.eid.container.EidBuilder;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.eid.list.EidItem;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.eid.list.EidItemBuilder;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapnotifymessage.MapNotifyBuilder;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.authkey.container.MappingAuthkey;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.record.container.MappingRecord;
71 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.record.list.MappingRecordItem;
72 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.record.list.MappingRecordItemBuilder;
73 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.maprequestnotification.MapRequestBuilder;
74 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.transport.address.TransportAddress;
75 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.transport.address.TransportAddressBuilder;
76 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.mappingservice.rev150906.MappingChanged;
77 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.mappingservice.rev150906.MappingOrigin;
78 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.mappingservice.rev150906.OdlMappingserviceListener;
79 import org.opendaylight.yangtools.concepts.ListenerRegistration;
80 import org.slf4j.Logger;
81 import org.slf4j.LoggerFactory;
82
83 public class MapServer implements IMapServerAsync, OdlMappingserviceListener, ISmrNotificationListener {
84
85     private static final Logger LOG = LoggerFactory.getLogger(MapServer.class);
86     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};
87     private IMappingService mapService;
88     private boolean subscriptionService;
89     private IMapNotifyHandler notifyHandler;
90     private NotificationService notificationService;
91     private ListenerRegistration<MapServer> mapServerListenerRegistration;
92     private SmrScheduler scheduler;
93
94     public MapServer(IMappingService mapService, boolean subscriptionService,
95                      IMapNotifyHandler notifyHandler, NotificationService notificationService) {
96         Preconditions.checkNotNull(mapService);
97         this.mapService = mapService;
98         this.subscriptionService = subscriptionService;
99         this.notifyHandler = notifyHandler;
100         this.notificationService = notificationService;
101         if (notificationService != null) {
102             notificationService.registerNotificationListener(this);
103         }
104         scheduler = new SmrScheduler();
105     }
106
107     @Override
108     public void setSubscriptionService(boolean subscriptionService) {
109         this.subscriptionService = subscriptionService;
110     }
111
112     @SuppressWarnings("unchecked")
113     public void handleMapRegister(MapRegister mapRegister) {
114         boolean mappingUpdated = false;
115         boolean merge = ConfigIni.getInstance().mappingMergeIsSet() && mapRegister.isMergeEnabled();
116         Set<Subscriber> subscribers = Sets.newConcurrentHashSet();
117         MappingRecord oldMapping;
118
119         if (merge) {
120             if (!mapRegister.isXtrSiteIdPresent() || mapRegister.getXtrId() == null) {
121                 LOG.error("Merge bit is set in Map-Register, but xTR-ID is not present. Will not merge.");
122                 merge = false;
123             } else if (Arrays.equals(mapRegister.getXtrId().getValue(), ALL_ZEROES_XTR_ID)) {
124                 LOG.warn("Merge bit is set in Map-Register, but xTR-ID is all zeroes.");
125             }
126         }
127
128         for (MappingRecordItem record : mapRegister.getMappingRecordItem()) {
129             MappingRecord mapping = record.getMappingRecord();
130             Eid eid = mapping.getEid();
131             MappingData mappingData = new MappingData(mapping, System.currentTimeMillis());
132             mappingData.setMergeEnabled(merge);
133             mappingData.setXtrId(mapRegister.getXtrId());
134
135             oldMapping = getMappingRecord(mapService.getMapping(MappingOrigin.Southbound, eid));
136             mapService.addMapping(MappingOrigin.Southbound, eid, getSiteId(mapRegister), mappingData);
137             if (oldMapping != null
138                     && MappingRecordUtil.isNegativeMapping(oldMapping)
139                     && !oldMapping.getEid().equals(eid)) {
140                 if (subscriptionService) {
141                     // Here we save the subscribers of the OLD mapping before removing. We will add to this set the
142                     // subscribers of the NEW mapping below (since the EIDs are different, the result of
143                     // mappingChanged() will be true, and then send an SMR to all subscribers with the EID of the NEW
144                     // mapping only.
145                     Set<Subscriber> oldMappingSubscribers = mapService.getSubscribers(oldMapping.getEid());
146                     if (oldMappingSubscribers != null) {
147                         subscribers.addAll(oldMappingSubscribers);
148                         LoggingUtil.logSubscribers(LOG, oldMapping.getEid(), subscribers);
149                     }
150                 }
151                 mapService.removeMapping(MappingOrigin.Southbound, oldMapping.getEid());
152             }
153
154             if (subscriptionService) {
155                 MappingRecord newMapping = merge
156                         ? getMappingRecord(mapService.getMapping(MappingOrigin.Southbound, eid)) : mapping;
157
158                 if (mappingChanged(oldMapping, newMapping)) {
159                     if (LOG.isDebugEnabled()) {
160                         LOG.debug("Mapping update occured for {} SMRs will be sent for its subscribers.",
161                                 LispAddressStringifier.getString(eid));
162                     }
163                     Set<Subscriber> newMappingSubscribers = mapService.getSubscribers(eid);
164                     if (oldMapping != null && !oldMapping.getEid().equals(eid)) {
165                         newMappingSubscribers = addParentSubscribers(eid, newMappingSubscribers);
166                     }
167                     if (newMappingSubscribers != null) {
168                         subscribers.addAll(newMappingSubscribers);
169                         LoggingUtil.logSubscribers(LOG, eid, subscribers);
170                     }
171                     handleSmr(eid, subscribers);
172                     mappingUpdated = true;
173                 }
174             }
175         }
176         if (BooleanUtils.isTrue(mapRegister.isWantMapNotify())) {
177             LOG.trace("MapRegister wants MapNotify");
178             MapNotifyBuilder builder = new MapNotifyBuilder();
179             List<TransportAddress> rlocs = null;
180             if (merge) {
181                 Set<IpAddressBinary> notifyRlocs = new HashSet<IpAddressBinary>();
182                 List<MappingRecordItem> mergedMappings = new ArrayList<MappingRecordItem>();
183                 for (MappingRecordItem record : mapRegister.getMappingRecordItem()) {
184                     MappingRecord mapping = record.getMappingRecord();
185                     MappingRecord currentRecord = getMappingRecord(mapService.getMapping(MappingOrigin.Southbound,
186                             mapping.getEid()));
187                     mergedMappings.add(new MappingRecordItemBuilder().setMappingRecord(currentRecord).build());
188                     Set<IpAddressBinary> sourceRlocs = (Set<IpAddressBinary>) mapService.getData(
189                             MappingOrigin.Southbound, mapping.getEid(), SubKeys.SRC_RLOCS);
190                     if (sourceRlocs != null) {
191                         notifyRlocs.addAll(sourceRlocs);
192                     }
193                 }
194                 MapNotifyBuilderHelper.setFromMapRegisterAndMappingRecordItems(builder, mapRegister, mergedMappings);
195                 // send map-notify to merge group only when mapping record is changed
196                 if (mappingUpdated) {
197                     rlocs = getTransportAddresses(notifyRlocs);
198                 }
199             } else {
200                 MapNotifyBuilderHelper.setFromMapRegister(builder, mapRegister);
201             }
202             List<MappingRecordItem> mappings = builder.getMappingRecordItem();
203             if (mappings != null && mappings.get(0) != null && mappings.get(0).getMappingRecord() != null
204                     && mappings.get(0).getMappingRecord().getEid() != null) {
205                 MappingAuthkey authkey = mapService.getAuthenticationKey(mappings.get(0).getMappingRecord().getEid());
206                 if (authkey != null) {
207                     builder.setAuthenticationData(LispAuthenticationUtil.createAuthenticationData(builder.build(),
208                             authkey.getKeyString()));
209                 }
210             }
211             notifyHandler.handleMapNotify(builder.build(), rlocs);
212         }
213     }
214
215     private static List<TransportAddress> getTransportAddresses(Set<IpAddressBinary> addresses) {
216         List<TransportAddress> rlocs = new ArrayList<TransportAddress>();
217         for (IpAddressBinary address : addresses) {
218             TransportAddressBuilder tab = new TransportAddressBuilder();
219             tab.setIpAddress(address);
220             tab.setPort(new PortNumber(LispMessage.PORT_NUM));
221             rlocs.add(tab.build());
222         }
223         return rlocs;
224     }
225
226     private static SiteId getSiteId(MapRegister mapRegister) {
227         return (mapRegister.getSiteId() != null) ? new SiteId(mapRegister.getSiteId()) : null;
228     }
229
230     private static MappingRecord getMappingRecord(MappingData mappingData) {
231         return (mappingData != null) ? mappingData.getRecord() : null;
232     }
233
234     @Override
235     public void onMappingChanged(MappingChanged notification) {
236         LOG.trace("MappingChanged event of type: `{}'", notification.getChangeType());
237         if (subscriptionService) {
238             Eid eid = notification.getEid();
239             if (eid == null) {
240                 eid = notification.getMappingRecord().getEid();
241             }
242             Set<Subscriber> subscribers = MSNotificationInputUtil.toSubscriberSet(notification.getSubscriberItem());
243             LoggingUtil.logSubscribers(LOG, eid, subscribers);
244             if (mapService.isMaster()) {
245                 sendSmrs(eid, subscribers);
246                 if (eid.getAddress() instanceof SourceDestKey) {
247                     Set<Subscriber> dstSubscribers = MSNotificationInputUtil.toSubscriberSetFromDst(
248                             notification.getDstSubscriberItem());
249                     LoggingUtil.logSubscribers(LOG, SourceDestKeyHelper.getDstBinary(eid), dstSubscribers);
250                     sendSmrs(SourceDestKeyHelper.getDstBinary(eid), dstSubscribers);
251                 }
252             }
253         }
254     }
255
256     private static boolean mappingChanged(MappingRecord oldMapping, MappingRecord newMapping) {
257         // We only check for fields we care about
258         // XXX: This code needs to be checked and updated when the YANG model for MappingRecord is modified
259         Preconditions.checkNotNull(newMapping, "The new mapping should never be null");
260         if (oldMapping == null) {
261             LOG.trace("mappingChanged(): old mapping is null");
262             return true;
263         } else if (!Objects.equals(oldMapping.getEid(), newMapping.getEid())) {
264             LOG.trace("mappingChanged(): EID");
265             return true;
266         } else if (!Objects.equals(oldMapping.getLocatorRecord(), newMapping.getLocatorRecord())) {
267             LOG.trace("mappingChanged(): RLOC");
268             return true;
269         } else if (!Objects.equals(oldMapping.getAction(), newMapping.getAction())) {
270             LOG.trace("mappingChanged(): action");
271             return true;
272         } else if (!Objects.equals(oldMapping.getRecordTtl(), newMapping.getRecordTtl())) {
273             LOG.trace("mappingChanged(): TTL");
274             return true;
275         } else if (!Objects.equals(oldMapping.getMapVersion(), newMapping.getMapVersion())) {
276             LOG.trace("mappingChanged(): mapping version");
277             return true;
278         }
279         return false;
280     }
281
282     private void handleSmr(Eid eid, Set<Subscriber> subscribers) {
283         sendSmrs(eid, subscribers);
284
285         // For SrcDst LCAF also send SMRs to Dst prefix
286         if (eid.getAddress() instanceof SourceDestKey) {
287             Eid dstAddr = SourceDestKeyHelper.getDstBinary(eid);
288             Set<Subscriber> dstSubs = mapService.getSubscribers(dstAddr);
289             sendSmrs(dstAddr, dstSubs);
290         }
291     }
292
293     private void sendSmrs(Eid eid, Set<Subscriber> subscribers) {
294         if (subscribers == null) {
295             return;
296         }
297         final MapRequestBuilder mrb = MapRequestUtil.prepareSMR(eid, LispAddressUtil.toRloc(getLocalAddress()));
298         LOG.trace("Built SMR packet: " + mrb.build().toString());
299
300         scheduler.scheduleSmrs(mrb, subscribers.iterator());
301     }
302
303     private Set<Subscriber> addParentSubscribers(Eid eid, Set<Subscriber> subscribers) {
304         Eid parentPrefix = mapService.getParentPrefix(eid);
305         if (parentPrefix == null) {
306             return subscribers;
307         }
308
309         Set<Subscriber> parentSubscribers = mapService.getSubscribers(parentPrefix);
310         if (parentSubscribers != null) {
311             if (subscribers != null) {
312                 subscribers.addAll(parentSubscribers);
313             } else {
314                 subscribers = parentSubscribers;
315             }
316         }
317         return subscribers;
318     }
319
320     private static InetAddress getLocalAddress() {
321         try {
322             Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
323             while (interfaces.hasMoreElements()) {
324                 NetworkInterface current = interfaces.nextElement();
325                 LOG.trace("Interface " + current.toString());
326                 if (!current.isUp() || current.isLoopback() || current.isVirtual()) {
327                     continue;
328                 }
329                 Enumeration<InetAddress> addresses = current.getInetAddresses();
330                 while (addresses.hasMoreElements()) {
331                     InetAddress currentAddr = addresses.nextElement();
332                     // Skip loopback and link local addresses
333                     if (currentAddr.isLoopbackAddress() || currentAddr.isLinkLocalAddress()) {
334                         continue;
335                     }
336                     LOG.debug(currentAddr.getHostAddress());
337                     return currentAddr;
338                 }
339             }
340         } catch (SocketException se) {
341             LOG.debug("Caught socket exception", se);
342         }
343         return null;
344     }
345
346     @Override
347     public void onSmrInvokedReceived(SmrEvent event) {
348         scheduler.smrReceived(event);
349     }
350
351     /**
352      * Task scheduler is responsible for resending SMR messages to a subscriber (xTR)
353      * {@value ConfigIni#LISP_SMR_RETRY_COUNT} times, or until {@link ISmrNotificationListener#onSmrInvokedReceived}
354      * is triggered.
355      */
356     private class SmrScheduler {
357         final int cpuCores = Runtime.getRuntime().availableProcessors();
358         private final ThreadFactory threadFactory = new ThreadFactoryBuilder()
359                 .setNameFormat("smr-executor-%d").build();
360         private final ScheduledExecutorService executor = Executors.newScheduledThreadPool(cpuCores * 2, threadFactory);
361         private final Map<Eid, Map<Subscriber, ScheduledFuture<?>>> eidFutureMap = Maps.newConcurrentMap();
362
363         void scheduleSmrs(MapRequestBuilder mrb, Iterator<Subscriber> subscribers) {
364             final Eid srcEid = fixSrcEidMask(mrb.getSourceEid().getEid());
365             cancelExistingFuturesForEid(srcEid);
366
367             final Map<Subscriber, ScheduledFuture<?>> subscriberFutureMap = Maps.newConcurrentMap();
368
369             // Using Iterator ensures that we don't get a ConcurrentModificationException when removing a Subscriber
370             // from a Set.
371             while (subscribers.hasNext()) {
372                 Subscriber subscriber = subscribers.next();
373                 if (subscriber.timedOut()) {
374                     LOG.debug("Lazy removing expired subscriber entry " + subscriber.getString());
375                     subscribers.remove();
376                 } else {
377                     final ScheduledFuture<?> future = executor.scheduleAtFixedRate(new CancellableRunnable(
378                             mrb, subscriber), 0L, ConfigIni.getInstance().getSmrTimeout(), TimeUnit.MILLISECONDS);
379                     subscriberFutureMap.put(subscriber, future);
380                 }
381             }
382
383             if (subscriberFutureMap.isEmpty()) {
384                 return;
385             }
386             eidFutureMap.put(srcEid, subscriberFutureMap);
387         }
388
389         void smrReceived(SmrEvent event) {
390             final List<Subscriber> subscriberList = event.getSubscriberList();
391             for (Subscriber subscriber : subscriberList) {
392                 if (LOG.isTraceEnabled()) {
393                     LOG.trace("SMR-invoked event, EID {}, subscriber {}",
394                             LispAddressStringifier.getString(event.getEid()),
395                             subscriber.getString());
396                     LOG.trace("eidFutureMap: {}", eidFutureMap);
397                 }
398                 final Map<Subscriber, ScheduledFuture<?>> subscriberFutureMap = eidFutureMap.get(event.getEid());
399                 if (subscriberFutureMap != null) {
400                     final ScheduledFuture<?> future = subscriberFutureMap.get(subscriber);
401                     if (future != null && !future.isCancelled()) {
402                         future.cancel(true);
403                         if (LOG.isDebugEnabled()) {
404                             LOG.debug("SMR-invoked MapRequest received, scheduled task for subscriber {}, EID {} with"
405                                     + " nonce {} has been cancelled", subscriber.getString(),
406                                     LispAddressStringifier.getString(event.getEid()), event.getNonce());
407                         }
408                         subscriberFutureMap.remove(subscriber);
409                     } else {
410                         if (future == null) {
411                             LOG.trace("No outstanding SMR tasks for EID {}, subscriber {}",
412                                     LispAddressStringifier.getString(event.getEid()), subscriber.getString());
413                         } else {
414                             LOG.trace("Future {} is cancelled", future);
415                         }
416                     }
417                     if (subscriberFutureMap.isEmpty()) {
418                         eidFutureMap.remove(event.getEid());
419                     }
420                 } else {
421                     if (LOG.isTraceEnabled()) {
422                         LOG.trace("No outstanding SMR tasks for EID {}",
423                                 LispAddressStringifier.getString(event.getEid()));
424                     }
425                 }
426             }
427         }
428
429         private void cancelExistingFuturesForEid(Eid eid) {
430             synchronized (eidFutureMap) {
431                 if (eidFutureMap.containsKey(eid)) {
432                     final Map<Subscriber, ScheduledFuture<?>> subscriberFutureMap = eidFutureMap.get(eid);
433                     Iterator<Subscriber> oldSubscribers = subscriberFutureMap.keySet().iterator();
434                     while (oldSubscribers.hasNext()) {
435                         Subscriber subscriber = oldSubscribers.next();
436                         ScheduledFuture<?> subscriberFuture = subscriberFutureMap.get(subscriber);
437                         subscriberFuture.cancel(true);
438                     }
439                     eidFutureMap.remove(eid);
440                 }
441             }
442         }
443
444         /*
445          * See https://bugs.opendaylight.org/show_bug.cgi?id=8469#c1 why this is necessary.
446          *
447          * TL;DR  The sourceEid field in the MapRequestBuilder object will be serialized to a packet on the wire, and
448          * a Map-Request can't store the prefix length in the source EID.
449          *
450          * Since we store all prefixes as binary internally, we only care about and fix those address types.
451          */
452         private Eid fixSrcEidMask(Eid eid) {
453             Address address = eid.getAddress();
454             if (address instanceof Ipv4PrefixBinary) {
455                 return new EidBuilder(eid).setAddress(new Ipv4PrefixBinaryBuilder((Ipv4PrefixBinary) address)
456                         .setIpv4MaskLength(MaskUtil.IPV4_MAX_MASK).build()).build();
457             } else if (address instanceof Ipv6PrefixBinary) {
458                 return new EidBuilder(eid).setAddress(new Ipv6PrefixBinaryBuilder((Ipv6PrefixBinary) address)
459                         .setIpv6MaskLength(MaskUtil.IPV6_MAX_MASK).build()).build();
460             }
461             return eid;
462         }
463
464         private final class CancellableRunnable implements Runnable {
465             private MapRequestBuilder mrb;
466             private Subscriber subscriber;
467             private int executionCount = 1;
468
469             CancellableRunnable(MapRequestBuilder mrb, Subscriber subscriber) {
470                 this.mrb = mrb;
471                 this.subscriber = subscriber;
472             }
473
474             @SuppressWarnings("checkstyle:IllegalCatch")
475             @Override
476             public void run() {
477                 final Eid srcEid = mrb.getSourceEid().getEid();
478
479                 try {
480                     // The address stored in the SMR's EID record is used as Source EID in the SMR-invoked
481                     // Map-Request. To ensure consistent behavior it is set to the value used to originally request
482                     // a given mapping.
483                     if (executionCount <= ConfigIni.getInstance().getSmrRetryCount()) {
484                         synchronized (mrb) {
485                             mrb.setEidItem(new ArrayList<EidItem>());
486                             mrb.getEidItem().add(new EidItemBuilder().setEid(subscriber.getSrcEid()).build());
487                             notifyHandler.handleSMR(mrb.build(), subscriber.getSrcRloc());
488                             if (LOG.isTraceEnabled()) {
489                                 LOG.trace("Attempt #{} to send SMR to subscriber {} for EID {}",
490                                         executionCount,
491                                         subscriber.getString(),
492                                         LispAddressStringifier.getString(mrb.getSourceEid().getEid()));
493                             }
494                         }
495                     } else {
496                         LOG.trace("Cancelling execution of a SMR Map-Request after {} failed attempts.",
497                                 executionCount - 1);
498                         cancelAndRemove(subscriber, srcEid);
499                         return;
500                     }
501                 } catch (Exception e) {
502                     LOG.error("Errors encountered while handling SMR:", e);
503                     cancelAndRemove(subscriber, srcEid);
504                     return;
505                 }
506                 executionCount++;
507             }
508
509             private void cancelAndRemove(Subscriber sub, Eid eid) {
510                 final Map<Subscriber, ScheduledFuture<?>> subscriberFutureMap = eidFutureMap.get(eid);
511                 if (subscriberFutureMap == null) {
512                     LOG.warn("Couldn't find subscriber {} in SMR scheduler internal list", sub);
513                     return;
514                 }
515
516                 if (subscriberFutureMap.containsKey(sub)) {
517                     ScheduledFuture<?> eidFuture = subscriberFutureMap.get(sub);
518                     subscriberFutureMap.remove(sub);
519                     eidFuture.cancel(false);
520                 }
521                 if (subscriberFutureMap.isEmpty()) {
522                     eidFutureMap.remove(eid);
523                 }
524             }
525         }
526     }
527 }