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