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