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