cb3b85cf983df3f076821da249a2d92c43cf6e76
[lispflowmapping.git] / mappingservice / implementation / src / main / java / org / opendaylight / lispflowmapping / implementation / MappingSystem.java
1 /*
2  * Copyright (c) 2015 Cisco Systems, Inc.  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;
10
11 import java.util.ArrayList;
12 import java.util.Date;
13 import java.util.EnumMap;
14 import java.util.HashSet;
15 import java.util.List;
16 import java.util.Set;
17
18 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
19 import org.opendaylight.lispflowmapping.config.ConfigIni;
20 import org.opendaylight.lispflowmapping.dsbackend.DataStoreBackEnd;
21 import org.opendaylight.lispflowmapping.implementation.util.DSBEInputUtil;
22 import org.opendaylight.lispflowmapping.implementation.util.MappingMergeUtil;
23 import org.opendaylight.lispflowmapping.interfaces.dao.ILispDAO;
24 import org.opendaylight.lispflowmapping.interfaces.mapcache.IAuthKeyDb;
25 import org.opendaylight.lispflowmapping.interfaces.mapcache.ILispMapCache;
26 import org.opendaylight.lispflowmapping.interfaces.mapcache.IMapCache;
27 import org.opendaylight.lispflowmapping.interfaces.mapcache.IMappingSystem;
28 import org.opendaylight.lispflowmapping.interfaces.mappingservice.IMappingService;
29 import org.opendaylight.lispflowmapping.lisp.type.MappingData;
30 import org.opendaylight.lispflowmapping.lisp.util.LispAddressStringifier;
31 import org.opendaylight.lispflowmapping.lisp.util.LispAddressUtil;
32 import org.opendaylight.lispflowmapping.mapcache.AuthKeyDb;
33 import org.opendaylight.lispflowmapping.mapcache.MultiTableMapCache;
34 import org.opendaylight.lispflowmapping.mapcache.SimpleMapCache;
35 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.SimpleAddress;
36 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.ExplicitLocatorPath;
37 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.Ipv4;
38 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.Ipv6;
39 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.ServicePath;
40 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;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.inet.binary.types.rev160303.IpAddressBinary;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.SiteId;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.XtrId;
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.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.authkey.container.MappingAuthkey;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.record.container.MappingRecordBuilder;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.rloc.container.Rloc;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.mappingservice.rev150906.MappingOrigin;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.mappingservice.rev150906.db.instance.AuthenticationKey;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.mappingservice.rev150906.db.instance.Mapping;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
55
56 /**
57  * The Mapping System coordinates caching of md-sal stored mappings and if so configured enables longest prefix match
58  * mapping lookups.
59  *
60  * @author Florin Coras
61  *
62  */
63 public class MappingSystem implements IMappingSystem {
64     private static final Logger LOG = LoggerFactory.getLogger(MappingSystem.class);
65     private static final String AUTH_KEY_TABLE = "authentication";
66     private boolean notificationService;
67     private boolean mappingMerge;
68     private ILispDAO dao;
69     private ILispDAO sdao;
70     private ILispMapCache smc;
71     private IMapCache pmc;
72     private IAuthKeyDb akdb;
73     private final EnumMap<MappingOrigin, IMapCache> tableMap = new EnumMap<>(MappingOrigin.class);
74     private DataStoreBackEnd dsbe;
75     private boolean isMaster = false;
76
77     public MappingSystem(ILispDAO dao, boolean iterateMask, boolean notifications, boolean mappingMerge) {
78         this.dao = dao;
79         this.notificationService = notifications;
80         this.mappingMerge = mappingMerge;
81         buildMapCaches();
82     }
83
84     public void setDataStoreBackEnd(DataStoreBackEnd dsbe) {
85         this.dsbe = dsbe;
86     }
87
88     @Override
89     public void setMappingMerge(boolean mappingMerge) {
90         this.mappingMerge = mappingMerge;
91     }
92
93     @Override
94     public void setIterateMask(boolean iterate) {
95         LOG.error("Non-longest prefix match lookups are not properly supported, variable is set to true");
96     }
97
98     public void initialize() {
99         restoreDaoFromDatastore();
100     }
101
102     private void buildMapCaches() {
103         /*
104          * There exists a direct relationship between MappingOrigins and the tables that are part of the MappingSystem.
105          * Therefore, if a new origin is added, probably a new table should be instantiated here as well. Here we
106          * instantiate a SimpleMapCache for southbound originated LISP mappings and a MultiTableMapCache for northbound
107          * originated mappings. Use of FlatMapCache would be possible when no longest prefix match is needed at all,
108          * but that option is no longer supported in the code, since it was never tested and may lead to unexpected
109          * results.
110          */
111         sdao = dao.putTable(MappingOrigin.Southbound.toString());
112         pmc = new MultiTableMapCache(dao.putTable(MappingOrigin.Northbound.toString()));
113         smc = new SimpleMapCache(sdao);
114         akdb = new AuthKeyDb(dao.putTable(AUTH_KEY_TABLE));
115         tableMap.put(MappingOrigin.Northbound, pmc);
116         tableMap.put(MappingOrigin.Southbound, smc);
117     }
118
119     public void addMapping(MappingOrigin origin, Eid key, MappingData mappingData) {
120         if (mappingData == null) {
121             LOG.warn("addMapping() called with null mapping, ignoring");
122             return;
123         }
124
125         if (origin == MappingOrigin.Southbound) {
126             XtrId xtrId = mappingData.getXtrId();
127             if (xtrId == null && mappingMerge && mappingData.isMergeEnabled()) {
128                 LOG.warn("addMapping() called will null xTR-ID in MappingRecord, while merge is set, ignoring");
129                 return;
130             }
131             if (xtrId != null && mappingMerge) {
132                 if (mappingData.isMergeEnabled()) {
133                     smc.addMapping(key, xtrId, mappingData);
134                     mergeMappings(key);
135                     return;
136                 } else {
137                     clearPresentXtrIdMappings(key);
138                     smc.addMapping(key, xtrId, mappingData);
139                 }
140             }
141         }
142
143         tableMap.get(origin).addMapping(key, mappingData);
144     }
145
146     private void clearPresentXtrIdMappings(Eid key) {
147         List<MappingData> allXtrMappingList = (List<MappingData>) (List<?>) smc.getAllXtrIdMappings(key);
148
149         if (((MappingData) smc.getMapping(key, (XtrId) null)).isMergeEnabled()) {
150             LOG.trace("Different xTRs have different merge configuration!");
151         }
152
153         for (MappingData mappingData : allXtrMappingList) {
154             smc.removeMapping(key, mappingData.getXtrId());
155             dsbe.removeXtrIdMapping(DSBEInputUtil.toXtrIdMapping(mappingData));
156         }
157     }
158
159     /*
160      * Since this method is only called when there is a hit in the southbound Map-Register cache, and that cache is
161      * not used when merge is on, it's OK to ignore the effects of timestamp changes on merging for now.
162      */
163     public void refreshMappingRegistration(Eid key, XtrId xtrId, Long timestamp) {
164         if (timestamp == null) {
165             timestamp = System.currentTimeMillis();
166         }
167         MappingData mappingData = (MappingData) smc.getMapping(null, key);
168         if (mappingData != null) {
169             mappingData.setTimestamp(new Date(timestamp));
170         } else {
171             LOG.warn("Could not update timestamp for EID {}, no mapping found", LispAddressStringifier.getString(key));
172         }
173         if (xtrId != null) {
174             MappingData xtrIdMappingData = (MappingData) smc.getMapping(key, xtrId);
175             if (xtrIdMappingData != null) {
176                 xtrIdMappingData.setTimestamp(new Date(timestamp));
177             } else {
178                 LOG.warn("Could not update timestamp for EID {} xTR-ID {}, no mapping found",
179                         LispAddressStringifier.getString(key), LispAddressStringifier.getString(xtrId));
180             }
181         }
182     }
183
184     private MappingData updateServicePathMappingRecord(MappingData mappingData, Eid eid) {
185         // keep properties of original record
186         MappingRecordBuilder recordBuilder = new MappingRecordBuilder(mappingData.getRecord());
187         recordBuilder.setLocatorRecord(new ArrayList<LocatorRecord>());
188
189         // there should only be one locator record
190         if (mappingData.getRecord().getLocatorRecord().size() != 1) {
191             LOG.warn("MappingRecord associated to ServicePath EID has more than one locator!");
192             return mappingData;
193         }
194
195         LocatorRecord locatorRecord = mappingData.getRecord().getLocatorRecord().get(0);
196         long serviceIndex = ((ServicePath) eid.getAddress()).getServicePath().getServiceIndex();
197         int index = LispAddressUtil.STARTING_SERVICE_INDEX - (int) serviceIndex;
198         Rloc rloc = locatorRecord.getRloc();
199         if (rloc.getAddress() instanceof Ipv4 || rloc.getAddress() instanceof Ipv6) {
200             if (index != 0) {
201                 LOG.warn("Service Index should be 255 for simple IP RLOCs!");
202             }
203             return mappingData;
204         } else if (rloc.getAddress() instanceof ExplicitLocatorPath) {
205             ExplicitLocatorPath elp = (ExplicitLocatorPath) rloc.getAddress();
206             List<Hop> hops = elp.getExplicitLocatorPath().getHop();
207
208             if (index < 0 || index > hops.size())  {
209                 LOG.warn("Service Index out of bounds!");
210                 return mappingData;
211             }
212
213             SimpleAddress nextHop = hops.get(index).getAddress();
214             LocatorRecordBuilder lrb = new LocatorRecordBuilder(locatorRecord);
215             lrb.setRloc(LispAddressUtil.toRloc(nextHop));
216             recordBuilder.getLocatorRecord().add(lrb.build());
217             return new MappingData(recordBuilder.build());
218         } else {
219             LOG.warn("Nothing to do with ServicePath mapping record");
220             return mappingData;
221         }
222     }
223
224     private MappingData mergeMappings(Eid key) {
225         List<XtrId> expiredMappings = new ArrayList<>();
226         Set<IpAddressBinary> sourceRlocs = new HashSet<>();
227         MappingData mergedMappingData = MappingMergeUtil.mergeXtrIdMappings(smc.getAllXtrIdMappings(key),
228                 expiredMappings, sourceRlocs);
229         smc.removeXtrIdMappings(key, expiredMappings);
230         for (XtrId xtrId : expiredMappings) {
231             dsbe.removeXtrIdMapping(DSBEInputUtil.toXtrIdMapping(xtrId));
232         }
233         if (mergedMappingData != null) {
234             smc.addMapping(key, mergedMappingData, sourceRlocs);
235             dsbe.addMapping(DSBEInputUtil.toMapping(MappingOrigin.Southbound, key,
236                     mergedMappingData.getRecord().getSiteId(), mergedMappingData));
237         } else {
238             smc.removeMapping(key);
239             dsbe.removeMapping(DSBEInputUtil.toMapping(MappingOrigin.Southbound, key));
240         }
241         return mergedMappingData;
242     }
243
244     @Override
245     public MappingData getMapping(Eid src, Eid dst) {
246         // NOTE: Currently we have two lookup algorithms implemented, which are configurable
247
248         if (ConfigIni.getInstance().getLookupPolicy() == IMappingService.LookupPolicy.NB_AND_SB) {
249             return getMappingNbSbIntersection(src, dst);
250         } else {
251             return getMappingNbFirst(src, dst);
252         }
253     }
254
255     @Override
256     public MappingData getMapping(Eid dst) {
257         return getMapping((Eid) null, dst);
258     }
259
260     @Override
261     public MappingData getMapping(Eid src, Eid dst, XtrId xtrId) {
262         // Note: If xtrId is null, we need to go through regular policy checking else Policy doesn't matter
263
264         if (xtrId == null) {
265             return getMapping(src, dst);
266         }
267
268         return getSbMappingWithExpiration(src, dst, xtrId);
269     }
270
271     @Override
272     public MappingData getMapping(MappingOrigin origin, Eid key) {
273         if (origin.equals(MappingOrigin.Southbound)) {
274             return getSbMappingWithExpiration(null, key, null);
275         }
276         return (MappingData) tableMap.get(origin).getMapping(null, key);
277     }
278
279     private MappingData getMappingNbFirst(Eid src, Eid dst) {
280
281         // Default lookup policy is northboundFirst
282         //lookupPolicy == NB_FIRST
283
284         MappingData nbMappingData = (MappingData) pmc.getMapping(src, dst);
285
286         if (nbMappingData == null) {
287             return getSbMappingWithExpiration(src, dst, null);
288         }
289         if (dst.getAddress() instanceof ServicePath) {
290             return updateServicePathMappingRecord(nbMappingData, dst);
291         }
292         return nbMappingData;
293     }
294
295     private MappingData getMappingNbSbIntersection(Eid src, Eid dst) {
296         //lookupPolicy == NB_AND_SB, we return intersection
297         //of NB and SB mappings, or NB mapping if intersection is empty.
298
299         MappingData nbMappingData = (MappingData) pmc.getMapping(src, dst);
300         if (nbMappingData == null) {
301             return nbMappingData;
302         }
303         // no intersection for Service Path mappings
304         if (dst.getAddress() instanceof ServicePath) {
305             return updateServicePathMappingRecord(nbMappingData, dst);
306         }
307         MappingData sbMappingData = getSbMappingWithExpiration(src, dst, null);
308         if (sbMappingData == null) {
309             return nbMappingData;
310         }
311         // both NB and SB mappings exist. Compute intersection of the mappings
312         return MappingMergeUtil.computeNbSbIntersection(nbMappingData, sbMappingData);
313     }
314
315     private MappingData getSbMappingWithExpiration(Eid src, Eid dst, XtrId xtrId) {
316         MappingData mappingData = (MappingData) smc.getMapping(dst, xtrId);
317         if (mappingData != null && MappingMergeUtil.mappingIsExpired(mappingData)) {
318             return removeExpiredMapping(dst, xtrId, mappingData);
319         } else {
320             return mappingData;
321         }
322     }
323
324     /*
325      * This private method either removes the main mapping ONLY, or the xTR-ID mapping ONLY, based on xtrId being
326      * null or non-null. Caller functions should take care of removing both when necessary.
327      */
328     private MappingData removeExpiredMapping(Eid key, XtrId xtrId, MappingData mappingData) {
329         if (mappingMerge && mappingData.isMergeEnabled()) {
330             return mergeMappings(key);
331         }
332         if (xtrId == null) {
333             smc.removeMapping(key);
334             dsbe.removeMapping(DSBEInputUtil.toMapping(MappingOrigin.Southbound, mappingData.getRecord().getEid(),
335                     new SiteId(mappingData.getRecord().getSiteId()), mappingData));
336         } else {
337             smc.removeMapping(key, xtrId);
338             dsbe.removeXtrIdMapping(DSBEInputUtil.toXtrIdMapping(mappingData));
339         }
340         return null;
341     }
342
343     @Override
344     public Eid getWidestNegativePrefix(Eid key) {
345         Eid nbPrefix = pmc.getWidestNegativeMapping(key);
346         if (nbPrefix == null) {
347             return null;
348         }
349
350         Eid sbPrefix = smc.getWidestNegativeMapping(key);
351         if (sbPrefix == null) {
352             return null;
353         }
354
355         // since prefixes overlap, just return the more specific (larger mask)
356         if (LispAddressUtil.getIpPrefixMask(nbPrefix) < LispAddressUtil.getIpPrefixMask(sbPrefix)) {
357             return sbPrefix;
358         } else {
359             return nbPrefix;
360         }
361     }
362
363     @Override
364     public void removeMapping(MappingOrigin origin, Eid key) {
365         tableMap.get(origin).removeMapping(key);
366         if (notificationService) {
367             // TODO
368         }
369     }
370
371     @Override
372     public void addAuthenticationKey(Eid key, MappingAuthkey authKey) {
373         LOG.debug("Adding authentication key '{}' with key-ID {} for {}", authKey.getKeyString(), authKey.getKeyType(),
374                 LispAddressStringifier.getString(key));
375         akdb.addAuthenticationKey(key, authKey);
376     }
377
378     @Override
379     public MappingAuthkey getAuthenticationKey(Eid key) {
380         if (LOG.isDebugEnabled()) {
381             LOG.debug("Retrieving authentication key for {}", LispAddressStringifier.getString(key));
382         }
383         return akdb.getAuthenticationKey(key);
384     }
385
386     @Override
387     public void removeAuthenticationKey(Eid key) {
388         if (LOG.isDebugEnabled()) {
389             LOG.debug("Removing authentication key for {}", LispAddressStringifier.getString(key));
390         }
391         akdb.removeAuthenticationKey(key);
392     }
393
394     @Override
395     public void addData(MappingOrigin origin, Eid key, String subKey, Object data) {
396         if (LOG.isDebugEnabled()) {
397             LOG.debug("Add data of class {} for key {} and subkey {}", data.getClass(),
398                     LispAddressStringifier.getString(key), subKey);
399         }
400         tableMap.get(origin).addData(key, subKey, data);
401     }
402
403     @Override
404     public Object getData(MappingOrigin origin, Eid key, String subKey) {
405         if (LOG.isDebugEnabled()) {
406             LOG.debug("Retrieving data for key {} and subkey {}", LispAddressStringifier.getString(key), subKey);
407         }
408         return tableMap.get(origin).getData(key, subKey);
409     }
410
411     @Override
412     public void removeData(MappingOrigin origin, Eid key, String subKey) {
413         if (LOG.isDebugEnabled()) {
414             LOG.debug("Removing data for key {} and subkey {}", LispAddressStringifier.getString(key), subKey);
415         }
416         tableMap.get(origin).removeData(key, subKey);
417     }
418
419     @Override
420     public Eid getParentPrefix(Eid key) {
421         return smc.getParentPrefix(key);
422     }
423
424
425     /**
426      * Restore all mappings and keys from mdsal datastore.
427      */
428     private void restoreDaoFromDatastore() {
429         List<AuthenticationKey> authKeys = dsbe.getAllAuthenticationKeys();
430         List<Mapping> mappings = dsbe.getAllMappings(LogicalDatastoreType.CONFIGURATION);
431
432         /*
433          * XXX By default, the operational datastore is not persisted to disk, either at run-time, or on shutdown,
434          * so the following will have no effect (getLastUpdateTimestamp() will fail, since it's reading from
435          * the operational datastore, and even if it didn't getAllMappings() will fail anyway). According to rovarga it
436          * should be possible to turn on persistence for the operational datastore editing
437          * etc/opendaylight/karaf/05-clustering.xml, by setting <persistence>true</persistence>. At the time of writing
438          * the below code block that didn't seem to work though.
439          */
440         Long lastUpdateTimestamp = dsbe.getLastUpdateTimestamp();
441         if (lastUpdateTimestamp != null && System.currentTimeMillis() - lastUpdateTimestamp
442                 > ConfigIni.getInstance().getRegistrationValiditySb()) {
443             LOG.warn("Restore threshold passed, not restoring operational datastore into DAO");
444         } else {
445             mappings.addAll(dsbe.getAllMappings(LogicalDatastoreType.OPERATIONAL));
446         }
447         dsbe.removeLastUpdateTimestamp();
448
449         LOG.info("Restoring {} mappings and {} keys from datastore into DAO", mappings.size(), authKeys.size());
450
451         for (Mapping mapping : mappings) {
452             addMapping(mapping.getOrigin(), mapping.getMappingRecord().getEid(),
453                     new MappingData(mapping.getMappingRecord()));
454         }
455
456         for (AuthenticationKey authKey : authKeys) {
457             addAuthenticationKey(authKey.getEid(), authKey.getMappingAuthkey());
458         }
459     }
460
461     public void destroy() {
462         LOG.info("Mapping System is being destroyed!");
463         dsbe.saveLastUpdateTimestamp();
464     }
465
466     @Override
467     public String printMappings() {
468         final StringBuffer sb = new StringBuffer();
469         sb.append("PolicyMapCache\n--------------\n");
470         sb.append(pmc.printMappings());
471         sb.append("SbMapCache\n----------\n");
472         sb.append(smc.printMappings());
473         return sb.toString();
474     }
475
476     @Override
477     public String printKeys() {
478         return akdb.printKeys();
479     }
480
481     public void cleanCaches() {
482         dao.removeAll();
483         buildMapCaches();
484     }
485
486     /*
487      * XXX  Mappings and keys should be separated for this to work properly, as is it will remove northbound originated
488      * authentication keys too, since they are currently stored in smc.
489      */
490     public void cleanSBMappings() {
491         smc = new SimpleMapCache(sdao);
492     }
493
494     @Override
495     public void setIsMaster(boolean isMaster) {
496         this.isMaster = isMaster;
497     }
498
499     @Override
500     public boolean isMaster() {
501         return isMaster;
502     }
503 }