Add virtual parent sibling prefix lookup methods
[lispflowmapping.git] / mappingservice / implementation / src / main / java / org / opendaylight / lispflowmapping / implementation / lisp / MapResolver.java
1 /*
2  * Copyright (c) 2014 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.Sets;
13 import java.util.ArrayList;
14 import java.util.List;
15 import java.util.Set;
16 import org.apache.commons.lang3.exception.ExceptionUtils;
17 import org.opendaylight.lispflowmapping.interfaces.dao.SubKeys;
18 import org.opendaylight.lispflowmapping.interfaces.dao.SubscriberRLOC;
19 import org.opendaylight.lispflowmapping.interfaces.lisp.IMapRequestResultHandler;
20 import org.opendaylight.lispflowmapping.interfaces.lisp.IMapResolverAsync;
21 import org.opendaylight.lispflowmapping.interfaces.lisp.ISmrNotificationListener;
22 import org.opendaylight.lispflowmapping.interfaces.lisp.SmrEvent;
23 import org.opendaylight.lispflowmapping.interfaces.mappingservice.IMappingService;
24 import org.opendaylight.lispflowmapping.lisp.type.MappingData;
25 import org.opendaylight.lispflowmapping.lisp.util.LispAddressStringifier;
26 import org.opendaylight.lispflowmapping.lisp.util.LispAddressUtil;
27 import org.opendaylight.lispflowmapping.lisp.util.SourceDestKeyHelper;
28 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.Ipv4Afi;
29 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.Ipv4PrefixAfi;
30 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.Ipv6Afi;
31 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.Ipv6PrefixAfi;
32 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.SimpleAddress;
33 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.SourceDestKeyLcaf;
34 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.Address;
35 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.ExplicitLocatorPath;
36 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.SourceDestKey;
37 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;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.inet.binary.types.rev160303.IpAddressBinary;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.binary.address.types.rev160504.Ipv4BinaryAfi;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.binary.address.types.rev160504.Ipv4PrefixBinaryAfi;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.binary.address.types.rev160504.Ipv6BinaryAfi;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.binary.address.types.rev160504.Ipv6PrefixBinaryAfi;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MapRequest;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.eid.container.Eid;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.eid.list.EidItem;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.locatorrecords.LocatorRecord;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.locatorrecords.LocatorRecordBuilder;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.record.container.MappingRecord;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.record.container.MappingRecord.Action;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.record.container.MappingRecordBuilder;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.record.list.MappingRecordItemBuilder;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapreplymessage.MapReplyBuilder;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.maprequest.ItrRloc;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.rloc.container.Rloc;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.mappingservice.rev150906.MappingOrigin;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
58
59 public class MapResolver implements IMapResolverAsync {
60     protected static final Logger LOG = LoggerFactory.getLogger(MapResolver.class);
61
62     private static final int TTL_RLOC_TIMED_OUT = 1;
63     private static final int TTL_NO_RLOC_KNOWN = 15;
64
65     private IMappingService mapService;
66     private boolean subscriptionService;
67     private String elpPolicy;
68     private IMapRequestResultHandler requestHandler;
69     private boolean authenticate = true;
70     private ISmrNotificationListener smrNotificationListener;
71
72     public MapResolver(IMappingService mapService, boolean smr, String elpPolicy,
73                        IMapRequestResultHandler requestHandler) {
74         Preconditions.checkNotNull(mapService);
75         this.subscriptionService = smr;
76         this.mapService = mapService;
77         this.elpPolicy = elpPolicy;
78         this.requestHandler = requestHandler;
79     }
80
81     public void handleMapRequest(MapRequest request) {
82         // SMRs and RLOC probes are directed towards xTRs and we're a Map-Resolver here, so ignore them
83         if (request.isSmr() != null && request.isSmr()) {
84             LOG.debug("Map-Resolver ignoring incoming SMR control message.");
85             return;
86         }
87         if (request.isProbe() != null && request.isProbe()) {
88             LOG.debug("Map-Resolver ignoring incoming RLOC probe control message.");
89             return;
90         }
91         if (request.isSmrInvoked()) {
92             LOG.debug("SMR-invoked request received.");
93             for (EidItem eidItem : request.getEidItem()) {
94                 final SmrEvent event = new SmrEvent(LispAddressUtil.addressBinariesFromItrRlocs(request.getItrRloc()),
95                         eidItem.getEid(), request.getNonce());
96                 smrNotificationListener.onSmrInvokedReceived(event);
97             }
98         }
99         Eid srcEid = null;
100         if (request.getSourceEid() != null) {
101             srcEid = request.getSourceEid().getEid();
102         }
103         MapReplyBuilder replyBuilder = new MapReplyBuilder();
104         replyBuilder.setEchoNonceEnabled(false);
105         replyBuilder.setProbe(false);
106         replyBuilder.setSecurityEnabled(false);
107         replyBuilder.setNonce(request.getNonce());
108         replyBuilder.setMappingRecordItem(new ArrayList<>());
109         List<ItrRloc> itrRlocs = request.getItrRloc();
110         final IpAddressBinary sourceRloc = request.getSourceRloc();
111
112         for (EidItem eidRecord : request.getEidItem()) {
113             MappingData mappingData = mapService.getMapping(srcEid, eidRecord.getEid());
114             MappingRecord mapping;
115             if (mappingData != null) {
116                 mapping = mappingData.getRecord();
117                 if (itrRlocs != null && itrRlocs.size() != 0) {
118                     if (subscriptionService) {
119                         final Rloc resolvedRloc = resolveRloc(itrRlocs, sourceRloc);
120                         updateSubscribers(resolvedRloc, eidRecord.getEid(), mapping.getEid(),
121                                 srcEid, mapping.getRecordTtl());
122                     }
123                     mapping = updateLocators(mapping, itrRlocs);
124                 }
125                 mapping = fixIfNotSDRequest(mapping, eidRecord.getEid());
126             } else {
127                 mapping = getNegativeMapping(eidRecord.getEid());
128             }
129             replyBuilder.getMappingRecordItem().add(new MappingRecordItemBuilder().setMappingRecord(mapping).build());
130         }
131         requestHandler.handleMapReply(replyBuilder.build());
132     }
133
134     private static boolean isEqualIpVersion(IpAddressBinary srcRloc, Rloc rloc) {
135         if (srcRloc.getIpv4AddressBinary() != null) {
136             if (rloc.getAddressType() == Ipv4Afi.class
137                     || rloc.getAddressType() == Ipv4BinaryAfi.class
138                     || rloc.getAddressType() == Ipv4PrefixAfi.class
139                     || rloc.getAddressType() == Ipv4PrefixBinaryAfi.class) {
140                 return true;
141             }
142         } else if (rloc.getAddressType() == Ipv6Afi.class
143                 || rloc.getAddressType() == Ipv6BinaryAfi.class
144                 || rloc.getAddressType() == Ipv6PrefixAfi.class
145                 || rloc.getAddressType() == Ipv6PrefixBinaryAfi.class) {
146             return true;
147         }
148         return false;
149     }
150
151     private Rloc resolveRloc(List<ItrRloc> itrRlocList, IpAddressBinary srcRloc) {
152         if (srcRloc == null) {
153             return itrRlocList.get(0).getRloc();
154         }
155         byte[] srcRlocByte;
156         if (srcRloc.getIpv4AddressBinary() != null) {
157             srcRlocByte = srcRloc.getIpv4AddressBinary().getValue();
158         } else {
159             srcRlocByte = srcRloc.getIpv6AddressBinary().getValue();
160         }
161
162         Rloc equalIpvRloc = null;
163         for (ItrRloc itrRloc : itrRlocList) {
164             final Rloc rloc = itrRloc.getRloc();
165             final byte[] itrRlocByte = LispAddressUtil.ipAddressToByteArray(rloc.getAddress());
166
167             // return an Rloc equal to the source Rloc
168             if (itrRlocByte != null && LispAddressUtil.compareIpAddressByteArrays(srcRlocByte, itrRlocByte) == 0) {
169                 return rloc;
170             }
171             // else lookup the first Rloc with identical Ip version
172             if (equalIpvRloc == null && isEqualIpVersion(srcRloc, rloc)) {
173                 equalIpvRloc = rloc;
174             }
175         }
176         if (equalIpvRloc != null) {
177             return equalIpvRloc;
178         } else {
179             // if none of the above, return the first Rloc
180             return itrRlocList.get(0).getRloc();
181         }
182     }
183
184     private MappingRecord getNegativeMapping(Eid eid) {
185         MappingRecordBuilder recordBuilder = new MappingRecordBuilder();
186         recordBuilder.setAuthoritative(false);
187         recordBuilder.setMapVersion((short) 0);
188         recordBuilder.setEid(eid);
189         if (eid.getAddressType().equals(Ipv4PrefixBinaryAfi.class)
190                 || eid.getAddressType().equals(Ipv6PrefixBinaryAfi.class)) {
191             Eid widestNegativePrefix = mapService.getWidestNegativePrefix(eid);
192             if (widestNegativePrefix != null) {
193                 recordBuilder.setEid(widestNegativePrefix);
194             }
195         }
196         recordBuilder.setAction(Action.NativelyForward);
197         if (authenticate && mapService.getAuthenticationKey(eid) != null) {
198             recordBuilder.setRecordTtl(TTL_RLOC_TIMED_OUT);
199         } else {
200             recordBuilder.setRecordTtl(TTL_NO_RLOC_KNOWN);
201         }
202         return recordBuilder.build();
203     }
204
205     private void updateSubscribers(Rloc itrRloc, Eid reqEid, Eid mapEid, Eid srcEid, Integer recordTtl) {
206         SubscriberRLOC subscriberRloc = new SubscriberRLOC(itrRloc, srcEid,
207                 SubscriberRLOC.recordTtlToSubscriberTime(recordTtl));
208         Eid subscribedEid = mapEid;
209
210         // If the eid in the matched mapping is SourceDest and the requested eid IS NOT then we subscribe itrRloc only
211         // to dst from the src/dst since that what's been requested. Note though that any updates to to the src/dst
212         // mapping will be pushed to dst as well (see sendSMRs in MapServer)
213         if (mapEid.getAddressType().equals(SourceDestKeyLcaf.class)
214                 && !reqEid.getAddressType().equals(SourceDestKeyLcaf.class)) {
215             subscribedEid = SourceDestKeyHelper.getDstBinary(mapEid);
216         }
217
218         Set<SubscriberRLOC> subscribers = getSubscribers(subscribedEid);
219         if (subscribers == null) {
220             subscribers = Sets.newConcurrentHashSet();
221         } else if (subscribers.contains(subscriberRloc)) {
222             // If there is an entry already for this subscriberRloc, remove it, so that it gets the new
223             // timestamp
224             subscribers.remove(subscriberRloc);
225         }
226         if (LOG.isTraceEnabled()) {
227             LOG.trace("Adding new subscriber: " + LispAddressStringifier.getString(subscriberRloc.getSrcRloc()));
228         }
229         subscribers.add(subscriberRloc);
230         addSubscribers(subscribedEid, subscribers);
231     }
232
233     // Fixes mapping if request was for simple dst EID but the matched mapping is a SourceDest
234     private MappingRecord fixIfNotSDRequest(MappingRecord mapping, Eid dstEid) {
235         if (mapping.getEid().getAddress() instanceof SourceDestKey
236                 && !(dstEid.getAddress() instanceof SourceDestKey)) {
237             return new MappingRecordBuilder(mapping).setEid(
238                     SourceDestKeyHelper.getDstBinary(mapping.getEid())).build();
239         }
240         return mapping;
241     }
242
243     private boolean locatorsNeedFixing(List<LocatorRecord> locatorRecords) {
244         // no locators - no fixing needed ;)
245         if (locatorRecords == null) {
246             return false;
247         }
248
249         for (LocatorRecord record : locatorRecords) {
250             if (record.getRloc().getAddress() instanceof ExplicitLocatorPath) {
251                 return true;
252             }
253         }
254         return false;
255     }
256
257     // Process locators according to configured policy
258     private MappingRecord updateLocators(MappingRecord mapping, List<ItrRloc> itrRlocs) {
259         // no fixing if elpPolicy is default
260         if (elpPolicy.equalsIgnoreCase("default")) {
261             return mapping;
262         }
263
264         List<LocatorRecord> locatorRecords = mapping.getLocatorRecord();
265
266         // if no updated is needed, just return the mapping
267         if (!locatorsNeedFixing(locatorRecords)) {
268             return mapping;
269         }
270
271         MappingRecordBuilder recordBuilder = new MappingRecordBuilder(mapping);
272         recordBuilder.setLocatorRecord(new ArrayList<LocatorRecord>());
273         try {
274             for (LocatorRecord record : locatorRecords) {
275                 Rloc container = record.getRloc();
276
277                 // For non-ELP RLOCs, or when ELP policy is default, or itrRlocs is null, just add the locator and be
278                 // done
279                 if ((!(container.getAddress() instanceof ExplicitLocatorPath))
280                         || elpPolicy.equalsIgnoreCase("default") || itrRlocs == null) {
281                     recordBuilder.getLocatorRecord().add(
282                             new LocatorRecordBuilder().setLocalLocator(record.isLocalLocator())
283                                     .setRlocProbed(record.isRlocProbed()).setWeight(record.getWeight())
284                                     .setPriority(record.getPriority()).setMulticastWeight(record.getMulticastWeight())
285                                     .setMulticastPriority(record.getMulticastPriority()).setRouted(record.isRouted())
286                                     .setRloc(container).setLocatorId(record.getLocatorId()).build());
287                     continue;
288                 }
289
290                 ExplicitLocatorPath teAddress = ((ExplicitLocatorPath) container.getAddress());
291                 SimpleAddress nextHop = getNextELPHop(teAddress, itrRlocs);
292                 if (nextHop != null) {
293                     java.lang.Short priority = record.getPriority();
294                     if (elpPolicy.equalsIgnoreCase("both")) {
295                         recordBuilder.getLocatorRecord().add(
296                                 new LocatorRecordBuilder().setLocalLocator(record.isLocalLocator())
297                                         .setRlocProbed(record.isRlocProbed()).setWeight(record.getWeight())
298                                         .setPriority(record.getPriority())
299                                         .setMulticastWeight(record.getMulticastWeight())
300                                         .setMulticastPriority(record.getMulticastPriority())
301                                         .setRouted(record.isRouted()).setRloc(container)
302                                         .setLocatorId(record.getLocatorId()).build());
303                         // Make the priority of the added simple locator lower so that ELP is used by default if
304                         // the xTR understands ELP. Exclude 255, since that means don't use for unicast forwarding
305                         // XXX Complex cases like several ELPs with different priorities are not handled
306                         if (priority != 254 || priority != 255) {
307                             priority++;
308                         }
309                     }
310                     // Build and add the simple RLOC
311                     recordBuilder.getLocatorRecord().add(
312                             new LocatorRecordBuilder().setLocalLocator(record.isLocalLocator())
313                                     .setRlocProbed(record.isRlocProbed()).setWeight(record.getWeight())
314                                     .setPriority(priority).setMulticastWeight(record.getMulticastWeight())
315                                     .setMulticastPriority(record.getMulticastPriority()).setRouted(record.isRouted())
316                                     .setRloc(LispAddressUtil.toRloc(nextHop))
317                                     .setLocatorId(record.getLocatorId()).build());
318                 }
319             }
320         } catch (ClassCastException cce) {
321             LOG.error("Class Cast Exception while building EidToLocatorRecord: {}", ExceptionUtils.getStackTrace(cce));
322         }
323
324         return recordBuilder.build();
325     }
326
327     private SimpleAddress getNextELPHop(ExplicitLocatorPath elp, List<ItrRloc> itrRlocs) {
328         SimpleAddress nextHop = null;
329         List<Hop> hops = elp.getExplicitLocatorPath().getHop();
330
331         if (hops != null && hops.size() > 0) {
332             // By default we return the first hop
333             nextHop = hops.get(0).getAddress();
334             for (Hop hop : hops) {
335                 Address hopAddress = LispAddressUtil.addressFromSimpleAddress(hop.getAddress());
336                 for (ItrRloc itrRloc : itrRlocs) {
337                     if (itrRloc.getRloc().getAddress().equals(hopAddress)) {
338                         int iterator = hops.indexOf(hop);
339                         if (iterator < hops.size() - 1) {
340                             nextHop = hops.get(iterator + 1).getAddress();
341                             return nextHop;
342                         }
343                     }
344                 }
345             }
346         }
347
348         return nextHop;
349     }
350
351     @SuppressWarnings("unchecked")
352     private Set<SubscriberRLOC> getSubscribers(Eid address) {
353         return (Set<SubscriberRLOC>) mapService.getData(MappingOrigin.Southbound, address, SubKeys.SUBSCRIBERS);
354     }
355
356     private void addSubscribers(Eid address, Set<SubscriberRLOC> subscribers) {
357         mapService.addData(MappingOrigin.Southbound, address, SubKeys.SUBSCRIBERS, subscribers);
358     }
359
360     @Override
361     public void setSubscriptionService(boolean smr) {
362         subscriptionService = smr;
363     }
364
365     @Override
366     public void setElpPolicy(String elpPolicy) {
367         this.elpPolicy = elpPolicy;
368     }
369
370     @Override
371     public void setShouldAuthenticate(boolean shouldAuthenticate) {
372         this.authenticate = shouldAuthenticate;
373     }
374
375     @Override
376     public void setSmrNotificationListener(ISmrNotificationListener smrNotificationListener) {
377         this.smrNotificationListener = smrNotificationListener;
378     }
379 }