7305a610ece0f510a4c41e3e3678b95368dc7329
[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         unsetLispDao(lispDao);
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         unsetLispDao(lispDao);
167         closeDataListeners();
168     }
169
170     public void _removeEid(final CommandInterpreter ci) {
171         LispAddressContainer eid = LispAFIConvertor.getIPContainer(ci.nextArgument());
172         lispDao.remove(MappingServiceKeyUtil.generateMappingServiceKey(eid));
173     }
174
175     public void _dumpAll(final CommandInterpreter ci) {
176         ci.print(printMappings());
177     }
178
179     public String printMappings() {
180         final StringBuffer sb = new StringBuffer();
181         sb.append("EID\tRLOCs\n");
182         lispDao.getAll(new IRowVisitor() {
183             String lastKey = "";
184
185             public void visitRow(Object keyId, String valueKey, Object value) {
186                 String key = keyId.getClass().getSimpleName() + "#" + keyId;
187                 if (!lastKey.equals(key)) {
188                     sb.append("\n" + key + "\t");
189                 }
190                 sb.append(valueKey + "=" + value + "\t");
191                 lastKey = key;
192             }
193         });
194         sb.append("\n");
195         return sb.toString();
196     }
197
198     public void _setShouldOverwriteRlocs(final CommandInterpreter ci) {
199         try {
200             boolean shouldOverwriteRloc = Boolean.parseBoolean(ci.nextArgument());
201             setOverwrite(shouldOverwriteRloc);
202         } catch (Exception e) {
203             ci.println("Bad Usage!!");
204         }
205
206     }
207
208     public void _addDefaultPassword(final CommandInterpreter ci) {
209         addDefaultKeyIPv4();
210     }
211
212     public void addDefaultKeyIPv4() {
213         LispAddressContainer address = LispAFIConvertor.toContainer(
214                 new Ipv4AddressBuilder().setIpv4Address(new Ipv4Address("0.0.0.0")).build());
215         addAuthenticationKey(address, 0, "password");
216     }
217
218     public String getHelp() {
219         StringBuffer help = new StringBuffer();
220         help.append("---LISP Mapping Service---\n");
221         help.append("\t dumpAll                               - Dump all current EID -> RLOC mappings\n");
222         help.append("\t removeEid <EID>                       - Remove a single EID (/32 or /128)\n");
223         help.append("\t setShouldOverwriteRlocs <true|false>  - Set the map server's behavior regarding existing RLOCs\n");
224         help.append("\t addDefaultPassword                    - Add \"password\" as default password for IPv4 EIDs");
225         return help.toString();
226     }
227
228     public MapReply handleMapRequest(MapRequest request) {
229         return handleMapRequest(request, smr);
230     }
231
232     public MapReply handleMapRequest(MapRequest request, boolean smr) {
233         LOG.debug("DAO: Retrieving mapping for {}/{}",
234                 LispAFIConvertor.toString(request.getEidRecord().get(0).getLispAddressContainer()),
235                 request.getEidRecord().get(0).getMask());
236
237         tlsMapReply.set(null);
238         tlsMapRequest.set(null);
239         mapResolver.handleMapRequest(request, smr, this);
240         // After this invocation we assume that the thread local is filled with
241         // the reply
242         if (tlsMapRequest.get() != null) {
243             SendMapRequestInputBuilder smrib = new SendMapRequestInputBuilder();
244             new MapRequestBuilder(tlsMapRequest.get().getLeft());
245             smrib.setMapRequest(new MapRequestBuilder(tlsMapRequest.get().getLeft()).build());
246             smrib.setTransportAddress(tlsMapRequest.get().getRight());
247             getLispSB().sendMapRequest(smrib.build());
248             return null;
249         } else {
250             return tlsMapReply.get();
251         }
252
253     }
254
255     public MapNotify handleMapRegister(MapRegister mapRegister) {
256         return handleMapRegister(mapRegister, smr);
257     }
258
259     public MapNotify handleMapRegister(MapRegister mapRegister, boolean smr) {
260         LOG.debug("DAO: Adding mapping for {}/{}",
261                 LispAFIConvertor.toString(mapRegister.getEidToLocatorRecord().get(0).getLispAddressContainer()),
262                 mapRegister.getEidToLocatorRecord().get(0).getMaskLength());
263
264         tlsMapNotify.set(null);
265         mapServer.handleMapRegister(mapRegister, smr, this);
266         // After this invocation we assume that the thread local is filled with
267         // the reply
268         return tlsMapNotify.get();
269     }
270
271     public String getAuthenticationKey(LispAddressContainer address, int maskLen) {
272         LOG.debug("DAO: Retrieving authentication key for {}/{}", LispAFIConvertor.toString(address), maskLen);
273         return mapServer.getAuthenticationKey(address, maskLen);
274     }
275
276     public void removeAuthenticationKey(LispAddressContainer address, int maskLen) {
277         LOG.debug("DAO: Removing authentication key for {}/{}", LispAFIConvertor.toString(address), maskLen);
278         mapServer.removeAuthenticationKey(address, maskLen);
279     }
280
281     public void addAuthenticationKey(LispAddressContainer address, int maskLen, String key) {
282         LOG.debug("DAO: Adding authentication key '{}' for {}/{}", key, LispAFIConvertor.toString(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 {}/{}", LispAFIConvertor.toString(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 }