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