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