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