Move HashMapDb to its own bundle
[lispflowmapping.git] / mappingservice / implementation / src / main / java / org / opendaylight / lispflowmapping / implementation / lisp / MapServer.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 java.net.InetAddress;
12 import java.net.NetworkInterface;
13 import java.net.SocketException;
14 import java.util.ArrayList;
15 import java.util.Enumeration;
16 import java.util.HashMap;
17 import java.util.HashSet;
18 import java.util.List;
19 import java.util.Map;
20 import java.util.Random;
21 import java.util.Map.Entry;
22
23 import org.apache.commons.lang3.BooleanUtils;
24 import org.opendaylight.lispflowmapping.implementation.authentication.LispAuthenticationUtil;
25 import org.opendaylight.lispflowmapping.implementation.config.ConfigIni;
26 import org.opendaylight.lispflowmapping.implementation.dao.MappingServiceKeyUtil;
27 import org.opendaylight.lispflowmapping.implementation.util.DAOMappingUtil;
28 import org.opendaylight.lispflowmapping.implementation.util.LispAFIConvertor;
29 import org.opendaylight.lispflowmapping.implementation.util.MapNotifyBuilderHelper;
30 import org.opendaylight.lispflowmapping.inmemorydb.HashMapDb;
31 import org.opendaylight.lispflowmapping.interfaces.dao.ILispDAO;
32 import org.opendaylight.lispflowmapping.interfaces.dao.IMappingServiceKey;
33 import org.opendaylight.lispflowmapping.interfaces.dao.MappingEntry;
34 import org.opendaylight.lispflowmapping.interfaces.dao.MappingServiceRLOCGroup;
35 import org.opendaylight.lispflowmapping.interfaces.dao.MappingServiceSubscriberRLOC;
36 import org.opendaylight.lispflowmapping.interfaces.lisp.IMapNotifyHandler;
37 import org.opendaylight.lispflowmapping.interfaces.lisp.IMapServerAsync;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.LispAFIAddress;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.MapRegister;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.MapRequest;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.eidrecords.EidRecordBuilder;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.eidtolocatorrecords.EidToLocatorRecord;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.eidtolocatorrecords.EidToLocatorRecordBuilder;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.lispaddress.LispAddressContainer;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.lispaddress.lispaddresscontainer.Address;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.lispaddress.lispaddresscontainer.address.LcafKeyValue;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.lispaddress.lispaddresscontainer.address.LcafSourceDest;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.lispsimpleaddress.primitiveaddress.DistinguishedName;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.locatorrecords.LocatorRecord;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.mapnotifymessage.MapNotifyBuilder;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.maprequest.ItrRloc;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.maprequest.ItrRlocBuilder;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.maprequest.SourceEidBuilder;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.maprequestnotification.MapRequestBuilder;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
57
58 public class MapServer extends AbstractLispComponent implements IMapServerAsync {
59
60     protected static final Logger LOG = LoggerFactory.getLogger(MapServer.class);
61
62     private static final ConfigIni configIni = new ConfigIni();
63     private static final boolean overwriteConfig = configIni.mappingOverwriteIsSet();
64     private boolean overwrite;
65
66     public MapServer(ILispDAO dao) {
67         this(dao, overwriteConfig);
68     }
69
70     public MapServer(ILispDAO dao, boolean overwrite) {
71         this(dao, overwrite, true);
72     }
73
74     public MapServer(ILispDAO dao, boolean overwrite, boolean authenticate) {
75         this(dao, overwrite, authenticate, true);
76     }
77
78     public MapServer(ILispDAO dao, boolean overwrite, boolean authenticate, boolean iterateAuthenticationMask) {
79         super(dao, authenticate, iterateAuthenticationMask);
80         this.overwrite = overwrite;
81     }
82
83     private static InetAddress getLocalAddress() {
84         try {
85             Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
86             while (interfaces.hasMoreElements()) {
87                 NetworkInterface current = interfaces.nextElement();
88                 LOG.debug("Interface " + current.toString());
89                 if (!current.isUp() || current.isLoopback() || current.isVirtual())
90                     continue;
91                 Enumeration<InetAddress> addresses = current.getInetAddresses();
92                 while (addresses.hasMoreElements()) {
93                     InetAddress current_addr = addresses.nextElement();
94                     // Skip loopback and link local addresses
95                     if (current_addr.isLoopbackAddress() || current_addr.isLinkLocalAddress())
96                         continue;
97                     LOG.debug(current_addr.getHostAddress());
98                     return current_addr;
99                 }
100             }
101         } catch (SocketException se) {
102         }
103         return null;
104     }
105
106     private static MapRequest buildSMR(EidToLocatorRecord eidRecord) {
107         MapRequestBuilder builder = new MapRequestBuilder();
108         builder.setAuthoritative(false);
109         builder.setMapDataPresent(false);
110         builder.setPitr(false);
111         builder.setProbe(false);
112         builder.setSmr(true);
113         builder.setSmrInvoked(false);
114
115         builder.setEidRecord(new ArrayList<org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.eidrecords.EidRecord>());
116         LispAddressContainer container = eidRecord.getLispAddressContainer();
117         short mask = (short) eidRecord.getMaskLength();
118         builder.getEidRecord().add(new EidRecordBuilder().setMask(mask).setLispAddressContainer(container).build());
119
120         builder.setItrRloc(new ArrayList<ItrRloc>());
121         builder.getItrRloc().add(new ItrRlocBuilder().setLispAddressContainer(LispAFIConvertor.toContainer(getLocalAddress())).build());
122
123         builder.setMapReply(null);
124         builder.setNonce(new Random().nextLong());
125
126         // XXX For now we set source EID to queried EID...
127         builder.setSourceEid(new SourceEidBuilder().setLispAddressContainer(container).build());
128         return builder.build();
129     }
130
131     public void handleMapRegister(MapRegister mapRegister, boolean smr, IMapNotifyHandler callback) {
132         if (dao == null) {
133             LOG.warn("handleMapRegister called while dao is uninitialized");
134         } else {
135             boolean failed = false;
136             String password = null;
137             for (EidToLocatorRecord eidRecord : mapRegister.getEidToLocatorRecord()) {
138                 if (shouldAuthenticate()) {
139                     password = getPassword(eidRecord.getLispAddressContainer(), eidRecord.getMaskLength());
140                     if (!LispAuthenticationUtil.validate(mapRegister, password)) {
141                         LOG.warn("Authentication failed");
142                         failed = true;
143                         break;
144                     }
145                 }
146                 boolean mappingChanged = saveRlocs(eidRecord, smr);
147                 if (smr && mappingChanged) {
148                     sendSmrs(eidRecord, callback);
149                 }
150             }
151             if (!failed) {
152                 MapNotifyBuilder builder = new MapNotifyBuilder();
153                 if (BooleanUtils.isTrue(mapRegister.isWantMapNotify())) {
154                     LOG.trace("MapRegister wants MapNotify");
155                     MapNotifyBuilderHelper.setFromMapRegister(builder, mapRegister);
156                     if (shouldAuthenticate()) {
157                         builder.setAuthenticationData(LispAuthenticationUtil.createAuthenticationData(builder.build(), password));
158                     }
159                     callback.handleMapNotify(builder.build());
160                 }
161             }
162         }
163     }
164
165     public boolean saveRlocs(EidToLocatorRecord eidRecord, boolean checkForChanges) {
166         Map<String, MappingServiceRLOCGroup> rlocGroups = new HashMap<String, MappingServiceRLOCGroup>();
167         if (eidRecord.getLocatorRecord() != null) {
168             for (LocatorRecord locatorRecord : eidRecord.getLocatorRecord()) {
169                 String subkey = getAddressKey(locatorRecord.getLispAddressContainer().getAddress());
170                 if (!rlocGroups.containsKey(subkey)) {
171                     rlocGroups.put(subkey, new MappingServiceRLOCGroup(eidRecord.getRecordTtl(), eidRecord.getAction(), eidRecord.isAuthoritative()));
172                 }
173                 rlocGroups.get(subkey).addRecord(locatorRecord);
174             }
175         }
176         List<MappingEntry<MappingServiceRLOCGroup>> entries = new ArrayList<>();
177         for (String subkey : rlocGroups.keySet()) {
178             entries.add(new MappingEntry<>(subkey, rlocGroups.get(subkey)));
179         }
180
181         if (eidRecord.getLispAddressContainer().getAddress() instanceof LcafSourceDest) {
182             Entry<IMappingServiceKey, List<MappingServiceRLOCGroup>> oldMapping= null, newMapping = null;
183             LispAFIAddress srcAddr = getSrcForLcafSrcDst(eidRecord.getLispAddressContainer());
184             LispAFIAddress dstAddr = getDstForLcafSrcDst(eidRecord.getLispAddressContainer());
185             short srcMask = getSrcMaskForLcafSrcDst(eidRecord.getLispAddressContainer());
186             short dstMask = getDstMaskForLcafSrcDst(eidRecord.getLispAddressContainer());
187
188             if (checkForChanges) {
189                 oldMapping = DAOMappingUtil.getMappingExact(srcAddr, dstAddr, srcMask, dstMask, dao);
190             }
191             IMappingServiceKey dstKey = MappingServiceKeyUtil.generateMappingServiceKey(dstAddr, dstMask);
192             ILispDAO srcDstDao = (ILispDAO) dao.getSpecific(dstKey, LCAF_SRCDST_SUBKEY);
193             if (srcDstDao == null) {
194                 srcDstDao = new HashMapDb();
195                 dao.put(dstKey, new MappingEntry<>(LCAF_SRCDST_SUBKEY, srcDstDao));
196             }
197             IMappingServiceKey srcKey = MappingServiceKeyUtil.generateMappingServiceKey(srcAddr, srcMask);
198             srcDstDao.put(srcKey, entries.toArray(new MappingEntry[entries.size()]));
199             if (checkForChanges) {
200                 newMapping = DAOMappingUtil.getMappingExact(srcAddr, dstAddr, srcMask, dstMask, dao);
201                 if (!newMapping.getValue().equals(oldMapping.getValue())) {
202                     return true;
203                 }
204             }
205         } else {
206             List<MappingServiceRLOCGroup> oldLocators = null, newLocators = null;
207             if (checkForChanges) {
208                 oldLocators = DAOMappingUtil.getLocatorsByEidToLocatorRecord(eidRecord, dao, shouldIterateMask());
209             }
210             IMappingServiceKey key = MappingServiceKeyUtil.generateMappingServiceKey(eidRecord.getLispAddressContainer(),
211                     eidRecord.getMaskLength());
212             dao.put(key, entries.toArray(new MappingEntry[entries.size()]));
213             if (checkForChanges) {
214                 newLocators = DAOMappingUtil.getLocatorsByEidToLocatorRecord(eidRecord, dao, shouldIterateMask());
215                 if (!newLocators.equals(oldLocators)) {
216                     return true;
217                 }
218             }
219         }
220         return false;
221     }
222
223     private String getAddressKey(Address address) {
224         if (address instanceof LcafKeyValue) {
225             LcafKeyValue keyVal = (LcafKeyValue) address;
226             if (keyVal.getLcafKeyValueAddressAddr().getKey().getPrimitiveAddress() instanceof DistinguishedName) {
227                 return ((DistinguishedName) keyVal.getLcafKeyValueAddressAddr().getKey().getPrimitiveAddress()).getDistinguishedNameAddress().getDistinguishedName();
228             }
229         }
230         if (shouldOverwrite()) {
231             return ADDRESS_SUBKEY;
232         } else {
233             return String.valueOf(address.hashCode());
234         }
235     }
236
237     public String getAuthenticationKey(LispAddressContainer address, int maskLen) {
238         return getPassword(address, maskLen);
239     }
240
241     public void removeAuthenticationKey(LispAddressContainer address, int maskLen) {
242         if (address.getAddress() instanceof LcafSourceDest) {
243             ILispDAO srcDstDao = getSrcDstInnerDao(address, maskLen);
244             if (srcDstDao != null) {
245                 IMappingServiceKey srcKey = MappingServiceKeyUtil.generateMappingServiceKey(getSrcForLcafSrcDst(address),
246                         getSrcMaskForLcafSrcDst(address));
247                 srcDstDao.removeSpecific(srcKey, PASSWORD_SUBKEY);
248             }
249         } else {
250             IMappingServiceKey key = MappingServiceKeyUtil.generateMappingServiceKey(address, maskLen);
251             dao.removeSpecific(key, PASSWORD_SUBKEY);
252         }
253     }
254
255     public void addAuthenticationKey(LispAddressContainer address, int maskLen, String key) {
256         IMappingServiceKey mappingServiceKey = MappingServiceKeyUtil.generateMappingServiceKey(address, maskLen);
257         if (address.getAddress() instanceof LcafSourceDest) {
258             IMappingServiceKey srcKey = MappingServiceKeyUtil.generateMappingServiceKey(getSrcForLcafSrcDst(address),
259                     getSrcMaskForLcafSrcDst(address));
260             ILispDAO srcDstDao = getOrInstantiateSrcDstInnerDao(address, maskLen);
261             srcDstDao.put(srcKey, new MappingEntry<String>(PASSWORD_SUBKEY, key));
262         } else {
263             dao.put(mappingServiceKey, new MappingEntry<String>(PASSWORD_SUBKEY, key));
264         }
265     }
266
267     public void removeMapping(LispAddressContainer address, int maskLen, boolean smr, IMapNotifyHandler callback) {
268         Entry<IMappingServiceKey, List<MappingServiceRLOCGroup>> mapping;
269         ILispDAO db;
270         if (address.getAddress() instanceof LcafSourceDest) {
271             db = getSrcDstInnerDao(address, maskLen);
272             LispAFIAddress srcAddr = getSrcForLcafSrcDst(address);
273             short srcMask = getSrcMaskForLcafSrcDst(address);
274             mapping = DAOMappingUtil.getMappingForEid(srcAddr, srcMask, db);
275         } else {
276             db = dao;
277             mapping = DAOMappingUtil.getMappingForEid(LispAFIConvertor.toAFI(address), maskLen, db);
278         }
279         if (smr) {
280             HashSet<MappingServiceSubscriberRLOC> subscribers = getSubscribers(address, maskLen);
281             // mapping is removed before first SMR is sent to avoid inconsistent replies
282             removeMappingRlocs(mapping, db);
283             handleSmr(new EidToLocatorRecordBuilder().setLispAddressContainer(address).
284                     setMaskLength((short) maskLen).build(), subscribers, callback);
285             db.removeSpecific(mapping.getKey(), SUBSCRIBERS_SUBKEY);
286         } else {
287             removeMappingRlocs(mapping, db);
288             db.removeSpecific(mapping.getKey(), SUBSCRIBERS_SUBKEY);
289         }
290     }
291
292     private void removeMappingRlocs(Entry<IMappingServiceKey, List<MappingServiceRLOCGroup>> mapping, ILispDAO db) {
293         for (MappingServiceRLOCGroup group : mapping.getValue()) {
294             for (LocatorRecord record : group.getRecords()) {
295                 db.removeSpecific(mapping.getKey(), getAddressKey(record.getLispAddressContainer().getAddress()));
296             }
297         }
298     }
299
300     private void sendSmrs(EidToLocatorRecord record, IMapNotifyHandler callback) {
301         LispAddressContainer eid = record.getLispAddressContainer();
302         HashSet<MappingServiceSubscriberRLOC> subscribers;
303
304         subscribers = getSubscribers(eid, record.getMaskLength());
305         handleSmr(record, subscribers, callback);
306
307         // For SrcDst LCAF also send SMRs to Dst prefix
308         if (eid.getAddress() instanceof LcafSourceDest) {
309             LispAddressContainer dstAddr = LispAFIConvertor.toContainer(getDstForLcafSrcDst(eid));
310             short dstMask = getDstMaskForLcafSrcDst(eid);
311             subscribers = getSubscribers(dstAddr, dstMask);
312             EidToLocatorRecord newRecord = new EidToLocatorRecordBuilder().setAction(record.getAction()).
313                     setAuthoritative(record.isAuthoritative()).setLocatorRecord(record.getLocatorRecord()).
314                     setMapVersion(record.getMapVersion()).setRecordTtl(record.getRecordTtl()).
315                     setLispAddressContainer(dstAddr).setMaskLength(dstMask).build();
316             handleSmr(newRecord, subscribers, callback);
317         }
318     }
319
320     private void handleSmr(EidToLocatorRecord record, HashSet<MappingServiceSubscriberRLOC> subscribers,
321             IMapNotifyHandler callback) {
322         if (subscribers == null) {
323             return;
324         }
325         MapRequest mapRequest = buildSMR(record);
326         LOG.trace("Built SMR packet: " + mapRequest.toString());
327         for (MappingServiceSubscriberRLOC rloc : subscribers) {
328             if (rloc.timedOut()) {
329                 LOG.trace("Lazy removing expired subscriber entry " + rloc.toString());
330                 subscribers.remove(rloc);
331             } else {
332                 try {
333                     callback.handleSMR(mapRequest, rloc.getSrcRloc());
334                 } catch (Exception e) {
335                     LOG.error("Errors encountered while handling SMR:" + e.getStackTrace());
336                 }
337             }
338         }
339         IMappingServiceKey key = MappingServiceKeyUtil.generateMappingServiceKey(record.getLispAddressContainer(),
340                 record.getMaskLength());
341         dao.put(key, new MappingEntry<HashSet<MappingServiceSubscriberRLOC>>(SUBSCRIBERS_SUBKEY, subscribers));
342     }
343
344     public boolean shouldOverwrite() {
345         return overwrite;
346     }
347
348     public void setOverwrite(boolean overwrite) {
349         this.overwrite = overwrite;
350     }
351
352 }