Bug 3380: Fix MD-SAL prefix overwriting
[lispflowmapping.git] / mappingservice / implementation / src / main / java / org / opendaylight / lispflowmapping / implementation / LispMappingService.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;
10
11 import java.util.List;
12
13 import org.apache.commons.lang3.tuple.MutablePair;
14 import org.apache.commons.lang3.tuple.Pair;
15 import org.eclipse.osgi.framework.console.CommandInterpreter;
16 import org.eclipse.osgi.framework.console.CommandProvider;
17 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
18 import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
19 import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.ProviderContext;
20 import org.opendaylight.controller.sal.binding.api.BindingAwareProvider;
21 import org.opendaylight.controller.sal.binding.api.NotificationListener;
22 import org.opendaylight.controller.sal.binding.api.NotificationService;
23 import org.opendaylight.lispflowmapping.implementation.config.ConfigIni;
24 import org.opendaylight.lispflowmapping.implementation.dao.HashMapDb;
25 import org.opendaylight.lispflowmapping.implementation.dao.MappingServiceKey;
26 import org.opendaylight.lispflowmapping.implementation.dao.MappingServiceKeyUtil;
27 import org.opendaylight.lispflowmapping.implementation.dao.MappingServiceNoMaskKey;
28 import org.opendaylight.lispflowmapping.implementation.lisp.MapResolver;
29 import org.opendaylight.lispflowmapping.implementation.lisp.MapServer;
30 import org.opendaylight.lispflowmapping.implementation.mdsal.AuthenticationKeyDataListener;
31 import org.opendaylight.lispflowmapping.implementation.mdsal.DataStoreBackEnd;
32 import org.opendaylight.lispflowmapping.implementation.mdsal.MappingDataListener;
33 import org.opendaylight.lispflowmapping.implementation.serializer.LispMessage;
34 import org.opendaylight.lispflowmapping.implementation.util.LispAFIConvertor;
35 import org.opendaylight.lispflowmapping.implementation.util.LispAddressStringifier;
36 import org.opendaylight.lispflowmapping.implementation.util.LispNotificationHelper;
37 import org.opendaylight.lispflowmapping.interfaces.dao.ILispDAO;
38 import org.opendaylight.lispflowmapping.interfaces.dao.ILispTypeConverter;
39 import org.opendaylight.lispflowmapping.interfaces.dao.IRowVisitor;
40 import org.opendaylight.lispflowmapping.interfaces.lisp.IFlowMapping;
41 import org.opendaylight.lispflowmapping.interfaces.lisp.IFlowMappingShell;
42 import org.opendaylight.lispflowmapping.interfaces.lisp.IMapNotifyHandler;
43 import org.opendaylight.lispflowmapping.interfaces.lisp.IMapRequestResultHandler;
44 import org.opendaylight.lispflowmapping.interfaces.lisp.IMapResolverAsync;
45 import org.opendaylight.lispflowmapping.interfaces.lisp.IMapServerAsync;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.AddMapping;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.LfmControlPlaneService;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.MapNotify;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.MapRegister;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.MapReply;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.MapRequest;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.RequestMapping;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.SendMapNotifyInputBuilder;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.SendMapReplyInputBuilder;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.SendMapRequestInputBuilder;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.lispaddress.LispAddressContainer;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.lispaddress.lispaddresscontainer.address.ipv4.Ipv4AddressBuilder;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.mapnotifymessage.MapNotifyBuilder;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.mapreplymessage.MapReplyBuilder;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.maprequestmessage.MapRequestBuilder;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.transportaddress.TransportAddress;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.transportaddress.TransportAddressBuilder;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.mapping.database.rev150314.db.instance.Mapping;
64 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Address;
65 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv6Address;
66 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.PortNumber;
67 import org.opendaylight.yangtools.yang.binding.Notification;
68 import org.osgi.framework.BundleContext;
69 import org.osgi.framework.FrameworkUtil;
70 import org.slf4j.Logger;
71 import org.slf4j.LoggerFactory;
72
73 public class LispMappingService implements CommandProvider, IFlowMapping, IFlowMappingShell, BindingAwareProvider,
74         IMapRequestResultHandler, IMapNotifyHandler {
75     protected static final Logger LOG = LoggerFactory.getLogger(LispMappingService.class);
76
77     private static final ConfigIni configIni = new ConfigIni();
78     private AuthenticationKeyDataListener keyListener;
79     private MappingDataListener mappingListener;
80     private ILispDAO lispDao = null;
81     private IMapResolverAsync mapResolver;
82     private IMapServerAsync mapServer;
83     private volatile boolean shouldIterateMask;
84     private volatile boolean shouldAuthenticate;
85     private volatile boolean smr = configIni.smrIsSet();
86     private ThreadLocal<MapReply> tlsMapReply = new ThreadLocal<MapReply>();
87     private ThreadLocal<MapNotify> tlsMapNotify = new ThreadLocal<MapNotify>();
88     private ThreadLocal<Pair<MapRequest, TransportAddress>> tlsMapRequest = new ThreadLocal<Pair<MapRequest, TransportAddress>>();
89
90     private LfmControlPlaneService lispSB = null;
91
92     private ProviderContext session;
93
94     private DataStoreBackEnd dsbe;
95     private NotificationService notificationService;
96     private static LispMappingService lfmService = null;
97
98     class LispIpv4AddressInMemoryConverter implements ILispTypeConverter<Ipv4Address, Integer> {
99     }
100
101     class LispIpv6AddressInMemoryConverter implements ILispTypeConverter<Ipv6Address, Integer> {
102     }
103
104     class MappingServiceKeyConvertor implements ILispTypeConverter<MappingServiceKey, Integer> {
105     }
106
107     class MappingServiceNoMaskKeyConvertor implements ILispTypeConverter<MappingServiceNoMaskKey, Integer> {
108     }
109
110     public static LispMappingService getLispMappingService() {
111         return lfmService;
112     }
113
114     void setBindingAwareBroker(BindingAwareBroker bindingAwareBroker) {
115         LOG.debug("BindingAwareBroker set!");
116         BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass()).getBundleContext();
117         bindingAwareBroker.registerProvider(this, bundleContext);
118
119         // For the time being we initialize variables here. But once we remove the activator, these should
120         // be moved to the constructor.
121         lfmService = this;
122         setLispDao(new HashMapDb());
123     }
124
125     void unsetBindingAwareBroker(BindingAwareBroker bindingAwareBroker) {
126         LOG.debug("BindingAwareBroker was unset in LispMappingService");
127         lfmService = null;
128     }
129
130     public void basicInit(ILispDAO dao) {
131         lispDao = dao;
132         mapResolver = new MapResolver(dao);
133         mapServer = new MapServer(dao);
134     }
135
136     void setLispDao(ILispDAO dao) {
137         LOG.trace("LispDAO set in LispMappingService");
138         basicInit(dao);
139     }
140
141     void unsetLispDao(ILispDAO dao) {
142         LOG.trace("LispDAO was unset in LispMappingService");
143         mapServer = null;
144         mapResolver = null;
145         lispDao = null;
146     }
147
148     public void init() {
149         try {
150             registerWithOSGIConsole();
151             LOG.info("LISP (RFC6830) Mapping Service init finished");
152         } catch (Exception e) {
153             LOG.error(e.getStackTrace().toString());
154         }
155     }
156
157     private void registerWithOSGIConsole() {
158         BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass()).getBundleContext();
159         bundleContext.registerService(CommandProvider.class.getName(), this, null);
160     }
161
162     public void destroy() {
163         LOG.info("LISP (RFC6830) Mapping Service is destroyed!");
164         mapResolver = null;
165         mapServer = null;
166         closeDataListeners();
167     }
168
169     public void _removeEid(final CommandInterpreter ci) {
170         LispAddressContainer eid = LispAFIConvertor.getIPContainer(ci.nextArgument());
171         lispDao.remove(MappingServiceKeyUtil.generateMappingServiceKey(eid));
172     }
173
174     public void _dumpAll(final CommandInterpreter ci) {
175         ci.print(printMappings());
176     }
177
178     public String printMappings() {
179         final StringBuffer sb = new StringBuffer();
180         sb.append("EID\tRLOCs\n");
181         lispDao.getAll(new IRowVisitor() {
182             String lastKey = "";
183
184             public void visitRow(Object keyId, String valueKey, Object value) {
185                 String key = keyId.getClass().getSimpleName() + "#" + keyId;
186                 if (!lastKey.equals(key)) {
187                     sb.append("\n" + key + "\t");
188                 }
189                 sb.append(valueKey + "=" + value + "\t");
190                 lastKey = key;
191             }
192         });
193         sb.append("\n");
194         return sb.toString();
195     }
196
197     public void _setShouldOverwriteRlocs(final CommandInterpreter ci) {
198         try {
199             boolean shouldOverwriteRloc = Boolean.parseBoolean(ci.nextArgument());
200             setOverwrite(shouldOverwriteRloc);
201         } catch (Exception e) {
202             ci.println("Bad Usage!!");
203         }
204
205     }
206
207     public void _addDefaultPassword(final CommandInterpreter ci) {
208         addDefaultKeyIPv4();
209     }
210
211     public void addDefaultKeyIPv4() {
212         LispAddressContainer address = LispAFIConvertor.toContainer(
213                 new Ipv4AddressBuilder().setIpv4Address(new Ipv4Address("0.0.0.0")).build());
214         addAuthenticationKey(address, 0, "password");
215     }
216
217     public String getHelp() {
218         StringBuffer help = new StringBuffer();
219         help.append("---LISP Mapping Service---\n");
220         help.append("\t dumpAll                               - Dump all current EID -> RLOC mappings\n");
221         help.append("\t removeEid <EID>                       - Remove a single EID (/32 or /128)\n");
222         help.append("\t setShouldOverwriteRlocs <true|false>  - Set the map server's behavior regarding existing RLOCs\n");
223         help.append("\t addDefaultPassword                    - Add \"password\" as default password for IPv4 EIDs");
224         return help.toString();
225     }
226
227     public MapReply handleMapRequest(MapRequest request) {
228         return handleMapRequest(request, smr);
229     }
230
231     public MapReply handleMapRequest(MapRequest request, boolean smr) {
232         LOG.debug("DAO: Retrieving mapping for {}",
233                 LispAddressStringifier.getString(request.getEidRecord().get(0).getLispAddressContainer(),
234                 request.getEidRecord().get(0).getMask()));
235
236         tlsMapReply.set(null);
237         tlsMapRequest.set(null);
238         mapResolver.handleMapRequest(request, smr, this);
239         // After this invocation we assume that the thread local is filled with
240         // the reply
241         if (tlsMapRequest.get() != null) {
242             SendMapRequestInputBuilder smrib = new SendMapRequestInputBuilder();
243             new MapRequestBuilder(tlsMapRequest.get().getLeft());
244             smrib.setMapRequest(new MapRequestBuilder(tlsMapRequest.get().getLeft()).build());
245             smrib.setTransportAddress(tlsMapRequest.get().getRight());
246             getLispSB().sendMapRequest(smrib.build());
247             return null;
248         } else {
249             return tlsMapReply.get();
250         }
251
252     }
253
254     public MapNotify handleMapRegister(MapRegister mapRegister) {
255         return handleMapRegister(mapRegister, smr);
256     }
257
258     public MapNotify handleMapRegister(MapRegister mapRegister, boolean smr) {
259         LOG.debug("DAO: Adding mapping for {}",
260                 LispAddressStringifier.getString(mapRegister.getEidToLocatorRecord().get(0).getLispAddressContainer(),
261                 mapRegister.getEidToLocatorRecord().get(0).getMaskLength()));
262
263         tlsMapNotify.set(null);
264         mapServer.handleMapRegister(mapRegister, smr, this);
265         // After this invocation we assume that the thread local is filled with
266         // the reply
267         return tlsMapNotify.get();
268     }
269
270     public String getAuthenticationKey(LispAddressContainer address, int maskLen) {
271         LOG.debug("DAO: Retrieving authentication key for {}", LispAddressStringifier.getString(address, maskLen));
272         return mapServer.getAuthenticationKey(address, maskLen);
273     }
274
275     public void removeAuthenticationKey(LispAddressContainer address, int maskLen) {
276         LOG.debug("DAO: Removing authentication key for {}", LispAddressStringifier.getString(address, maskLen));
277         mapServer.removeAuthenticationKey(address, maskLen);
278     }
279
280     public void addAuthenticationKey(LispAddressContainer address, int maskLen, String key) {
281         LOG.debug("DAO: Adding authentication key '{}' for {}", key,
282                 LispAddressStringifier.getString(address, maskLen));
283         mapServer.addAuthenticationKey(address, maskLen, key);
284     }
285
286     public void removeMapping(LispAddressContainer address, int maskLen) {
287         LOG.debug("DAO: Removing mapping for {}", LispAddressStringifier.getString(address, maskLen));
288         mapServer.removeMapping(address, maskLen, smr, this);
289     }
290
291     public boolean shouldIterateMask() {
292         return this.shouldIterateMask;
293     }
294
295     public boolean shouldUseSmr() {
296         return this.smr;
297     }
298
299     public void setShouldUseSmr(boolean smr) {
300         this.smr = smr;
301     }
302
303     public void setShouldIterateMask(boolean shouldIterateMask) {
304         this.shouldIterateMask = shouldIterateMask;
305         this.mapResolver.setShouldIterateMask(shouldIterateMask);
306         this.mapServer.setShouldIterateMask(shouldIterateMask);
307     }
308
309     public void setShouldAuthenticate(boolean shouldAuthenticate) {
310         this.shouldAuthenticate = shouldAuthenticate;
311         this.mapResolver.setShouldAuthenticate(shouldAuthenticate);
312         this.mapServer.setShouldAuthenticate(shouldAuthenticate);
313     }
314
315     public boolean shouldAuthenticate() {
316         return shouldAuthenticate;
317     }
318
319     @Override
320     public void onSessionInitiated(ProviderContext session) {
321         LOG.info("Lisp Consumer session initialized!");
322         notificationService = session.getSALService(NotificationService.class);
323         dsbe = new DataStoreBackEnd(session.getSALService(DataBroker.class));
324         registerNotificationListener(AddMapping.class, new MapRegisterNotificationHandler());
325         registerNotificationListener(RequestMapping.class, new MapRequestNotificationHandler());
326         registerDataListeners(session.getSALService(DataBroker.class));
327         this.session = session;
328     }
329
330     private void registerDataListeners(DataBroker broker) {
331         keyListener = new AuthenticationKeyDataListener(broker, this);
332         mappingListener = new MappingDataListener(broker, this);
333     }
334
335     private void closeDataListeners() {
336         keyListener.closeDataChangeListener();
337         mappingListener.closeDataChangeListener();
338     }
339
340     public <T extends Notification> void registerNotificationListener(Class<T> notificationType, NotificationListener<T> listener) {
341         notificationService.registerNotificationListener(notificationType, listener);
342     }
343
344     private class MapRegisterNotificationHandler implements NotificationListener<AddMapping> {
345
346         @Override
347         public void onNotification(AddMapping mapRegisterNotification) {
348             MapNotify mapNotify = handleMapRegister(mapRegisterNotification.getMapRegister(), smr);
349             if (mapNotify != null) {
350                 TransportAddressBuilder tab = new TransportAddressBuilder();
351                 tab.setIpAddress(mapRegisterNotification.getTransportAddress().getIpAddress());
352                 tab.setPort(new PortNumber(LispMessage.PORT_NUM));
353                 SendMapNotifyInputBuilder smnib = new SendMapNotifyInputBuilder();
354                 smnib.setMapNotify(new MapNotifyBuilder(mapNotify).build());
355                 smnib.setTransportAddress(tab.build());
356                 getLispSB().sendMapNotify(smnib.build());
357             } else {
358                 LOG.warn("got null map notify");
359             }
360
361             List<Mapping> mappings = LispNotificationHelper.getMapping(mapRegisterNotification);
362             for (Mapping mapping : mappings) {
363                 dsbe.updateMapping(mapping);
364             }
365         }
366     }
367
368     private class MapRequestNotificationHandler implements NotificationListener<RequestMapping> {
369
370         @Override
371         public void onNotification(RequestMapping mapRequestNotification) {
372             MapReply mapReply = handleMapRequest(mapRequestNotification.getMapRequest());
373             if (mapReply != null) {
374                 SendMapReplyInputBuilder smrib = new SendMapReplyInputBuilder();
375                 smrib.setMapReply((new MapReplyBuilder(mapReply).build()));
376                 smrib.setTransportAddress(mapRequestNotification.getTransportAddress());
377                 getLispSB().sendMapReply(smrib.build());
378             } else {
379                 LOG.warn("got null map reply");
380             }
381         }
382     }
383
384     private LfmControlPlaneService getLispSB() {
385         if (lispSB == null) {
386             lispSB = session.getRpcService(LfmControlPlaneService.class);
387         }
388         return lispSB;
389     }
390
391     public void handleMapReply(MapReply reply) {
392         tlsMapReply.set(reply);
393     }
394
395     public void handleMapNotify(MapNotify notify) {
396         tlsMapNotify.set(notify);
397     }
398
399     public void handleSMR(MapRequest smr, LispAddressContainer subscriber) {
400         LOG.debug("Sending SMR to " + subscriber.toString());
401         SendMapRequestInputBuilder smrib = new SendMapRequestInputBuilder();
402         smrib.setMapRequest(new MapRequestBuilder(smr).build());
403         smrib.setTransportAddress(LispNotificationHelper.getTransportAddressFromContainer(subscriber));
404         getLispSB().sendMapRequest(smrib.build());
405
406     }
407
408     @Override
409     public void handleNonProxyMapRequest(MapRequest mapRequest, TransportAddress transportAddress) {
410         tlsMapRequest.set(new MutablePair<MapRequest, TransportAddress>(mapRequest, transportAddress));
411     }
412
413     @Override
414     public void clean() {
415         lispDao.removeAll();
416     }
417
418     @Override
419     public boolean shouldOverwrite() {
420         return mapServer.shouldOverwrite();
421     }
422
423     @Override
424     public void setOverwrite(boolean overwrite) {
425         mapServer.setOverwrite(overwrite);
426     }
427 }