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