6a50e129457adaa1f927a397356e61f9e2bbe94d
[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.concurrent.Future;
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.ProviderContext;
19 import org.opendaylight.controller.sal.binding.api.BindingAwareProvider;
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.lisp.MapResolver;
27 import org.opendaylight.lispflowmapping.implementation.lisp.MapServer;
28 import org.opendaylight.lispflowmapping.implementation.serializer.LispMessage;
29 import org.opendaylight.lispflowmapping.implementation.util.LispAFIConvertor;
30 import org.opendaylight.lispflowmapping.implementation.util.LispNotificationHelper;
31 import org.opendaylight.lispflowmapping.interfaces.dao.ILispDAO;
32 import org.opendaylight.lispflowmapping.interfaces.dao.ILispTypeConverter;
33 import org.opendaylight.lispflowmapping.interfaces.dao.IRowVisitor;
34 import org.opendaylight.lispflowmapping.interfaces.lisp.IFlowMapping;
35 import org.opendaylight.lispflowmapping.interfaces.lisp.IFlowMappingShell;
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.urn.opendaylight.lfm.control.plane.rev150314.AddMapping;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.LfmControlPlaneService;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.MapNotify;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.MapRegister;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.MapReply;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.MapRequest;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.RequestMapping;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.SendMapNotifyInputBuilder;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.SendMapReplyInputBuilder;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.SendMapRequestInputBuilder;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.lispaddress.LispAddressContainer;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.lispaddress.lispaddresscontainer.address.ipv4.Ipv4AddressBuilder;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.mapnotifymessage.MapNotifyBuilder;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.mapreplymessage.MapReplyBuilder;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.maprequestmessage.MapRequestBuilder;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.transportaddress.TransportAddress;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.transportaddress.TransportAddressBuilder;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.mapping.database.rev150314.AddKeyInput;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.mapping.database.rev150314.AddMappingInput;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.mapping.database.rev150314.GetKeyInput;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.mapping.database.rev150314.GetKeyOutput;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.mapping.database.rev150314.GetMappingInput;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.mapping.database.rev150314.GetMappingOutput;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.mapping.database.rev150314.LfmMappingDatabaseService;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.mapping.database.rev150314.RemoveKeyInput;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.mapping.database.rev150314.RemoveMappingInput;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.mapping.database.rev150314.UpdateKeyInput;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.mapping.database.rev150314.UpdateMappingInput;
68 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Address;
69 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv6Address;
70 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.PortNumber;
71 import org.opendaylight.yangtools.yang.binding.Notification;
72 import org.opendaylight.yangtools.yang.common.RpcResult;
73 import org.osgi.framework.BundleContext;
74 import org.osgi.framework.FrameworkUtil;
75 import org.slf4j.Logger;
76 import org.slf4j.LoggerFactory;
77
78 public class LispMappingService implements CommandProvider, IFlowMapping, IFlowMappingShell, BindingAwareProvider,
79         IMapRequestResultHandler, IMapNotifyHandler, LfmMappingDatabaseService {
80     protected static final Logger LOG = LoggerFactory.getLogger(LispMappingService.class);
81
82     private static final ConfigIni configIni = new ConfigIni();
83     private LfmMappingDatabaseRPCs rpc = new LfmMappingDatabaseRPCs();
84     private ILispDAO lispDao = null;
85     private IMapResolverAsync mapResolver;
86     private IMapServerAsync mapServer;
87     private volatile boolean shouldIterateMask;
88     private volatile boolean shouldAuthenticate;
89     private volatile boolean smr = configIni.smrIsSet();
90     private ThreadLocal<MapReply> tlsMapReply = new ThreadLocal<MapReply>();
91     private ThreadLocal<MapNotify> tlsMapNotify = new ThreadLocal<MapNotify>();
92     private ThreadLocal<Pair<MapRequest, TransportAddress>> tlsMapRequest = new ThreadLocal<Pair<MapRequest, TransportAddress>>();
93
94     private LfmControlPlaneService lispSB = null;
95
96     private ProviderContext session;
97
98     private NotificationService notificationService;
99
100     class LispIpv4AddressInMemoryConverter implements ILispTypeConverter<Ipv4Address, Integer> {
101     }
102
103     class LispIpv6AddressInMemoryConverter implements ILispTypeConverter<Ipv6Address, Integer> {
104     }
105
106     class MappingServiceKeyConvertor implements ILispTypeConverter<MappingServiceKey, Integer> {
107     }
108
109     class MappingServiceNoMaskKeyConvertor implements ILispTypeConverter<MappingServiceNoMaskKey, Integer> {
110     }
111
112     void setBindingAwareBroker(BindingAwareBroker bindingAwareBroker) {
113         LOG.trace("BindingAwareBroker set!");
114         BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass()).getBundleContext();
115         bindingAwareBroker.registerProvider(this, bundleContext);
116     }
117
118     void unsetBindingAwareBroker(BindingAwareBroker bindingAwareBroker) {
119         LOG.debug("BindingAwareBroker was unset in LispMappingService");
120     }
121
122     public void basicInit(ILispDAO dao) {
123         lispDao = dao;
124         mapResolver = new MapResolver(dao);
125         mapServer = new MapServer(dao);
126     }
127
128     void setLispDao(ILispDAO dao) {
129         LOG.trace("LispDAO set in LispMappingService");
130         basicInit(dao);
131     }
132
133     void unsetLispDao(ILispDAO dao) {
134         LOG.trace("LispDAO was unset in LispMappingService");
135         mapServer = null;
136         mapResolver = null;
137         lispDao = null;
138     }
139
140     public void init() {
141         try {
142             registerWithOSGIConsole();
143             LOG.info("LISP (RFC6830) Mapping Service init finished");
144         } catch (Exception e) {
145             LOG.error(e.getStackTrace().toString());
146         }
147     }
148
149     private void registerWithOSGIConsole() {
150         BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass()).getBundleContext();
151         bundleContext.registerService(CommandProvider.class.getName(), this, null);
152     }
153
154     public void destroy() {
155         LOG.info("LISP (RFC6830) Mapping Service is destroyed!");
156         mapResolver = null;
157         mapServer = null;
158     }
159
160     public void _removeEid(final CommandInterpreter ci) {
161         LispAddressContainer eid = LispAFIConvertor.getIPContainer(ci.nextArgument());
162         lispDao.remove(MappingServiceKeyUtil.generateMappingServiceKey(eid));
163     }
164
165     public void _dumpAll(final CommandInterpreter ci) {
166         ci.print(printMappings());
167     }
168
169     public String printMappings() {
170         final StringBuffer sb = new StringBuffer();
171         sb.append("EID\tRLOCs\n");
172         lispDao.getAll(new IRowVisitor() {
173             String lastKey = "";
174
175             public void visitRow(Object keyId, String valueKey, Object value) {
176                 String key = keyId.getClass().getSimpleName() + "#" + keyId;
177                 if (!lastKey.equals(key)) {
178                     sb.append("\n" + key + "\t");
179                 }
180                 sb.append(valueKey + "=" + value + "\t");
181                 lastKey = key;
182             }
183         });
184         sb.append("\n");
185         return sb.toString();
186     }
187
188     public void _setShouldOverwriteRlocs(final CommandInterpreter ci) {
189         try {
190             boolean shouldOverwriteRloc = Boolean.parseBoolean(ci.nextArgument());
191             setOverwrite(shouldOverwriteRloc);
192         } catch (Exception e) {
193             ci.println("Bad Usage!!");
194         }
195
196     }
197
198     public void _addDefaultPassword(final CommandInterpreter ci) {
199         addDefaultKeyIPv4();
200     }
201
202     public void addDefaultKeyIPv4() {
203         LispAddressContainer address = LispAFIConvertor.toContainer(
204                 new Ipv4AddressBuilder().setIpv4Address(new Ipv4Address("0.0.0.0")).build());
205         addAuthenticationKey(address, 0, "password");
206     }
207
208     public String getHelp() {
209         StringBuffer help = new StringBuffer();
210         help.append("---LISP Mapping Service---\n");
211         help.append("\t dumpAll                               - Dump all current EID -> RLOC mappings\n");
212         help.append("\t removeEid <EID>                       - Remove a single EID (/32 or /128)\n");
213         help.append("\t setShouldOverwriteRlocs <true|false>  - Set the map server's behavior regarding existing RLOCs\n");
214         help.append("\t addDefaultPassword                    - Add \"password\" as default password for IPv4 EIDs");
215         return help.toString();
216     }
217
218     public MapReply handleMapRequest(MapRequest request) {
219         return handleMapRequest(request, smr);
220     }
221
222     public MapReply handleMapRequest(MapRequest request, boolean smr) {
223         tlsMapReply.set(null);
224         tlsMapRequest.set(null);
225         mapResolver.handleMapRequest(request, smr, this);
226         // After this invocation we assume that the thread local is filled with
227         // the reply
228         if (tlsMapRequest.get() != null) {
229             SendMapRequestInputBuilder smrib = new SendMapRequestInputBuilder();
230             new MapRequestBuilder(tlsMapRequest.get().getLeft());
231             smrib.setMapRequest(new MapRequestBuilder(tlsMapRequest.get().getLeft()).build());
232             smrib.setTransportAddress(tlsMapRequest.get().getRight());
233             getLispSB().sendMapRequest(smrib.build());
234             return null;
235         } else {
236             return tlsMapReply.get();
237         }
238
239     }
240
241     public MapNotify handleMapRegister(MapRegister mapRegister) {
242         return handleMapRegister(mapRegister, smr);
243     }
244
245     public MapNotify handleMapRegister(MapRegister mapRegister, boolean smr) {
246         tlsMapNotify.set(null);
247         mapServer.handleMapRegister(mapRegister, smr, this);
248         // After this invocation we assume that the thread local is filled with
249         // the reply
250         return tlsMapNotify.get();
251     }
252
253     public String getAuthenticationKey(LispAddressContainer address, int maskLen) {
254         return mapServer.getAuthenticationKey(address, maskLen);
255     }
256
257     public void removeAuthenticationKey(LispAddressContainer address, int maskLen) {
258         mapServer.removeAuthenticationKey(address, maskLen);
259     }
260
261     public void addAuthenticationKey(LispAddressContainer address, int maskLen, String key) {
262         mapServer.addAuthenticationKey(address, maskLen, key);
263     }
264
265     public void removeMapping(LispAddressContainer address, int maskLen) {
266         mapServer.removeMapping(address, maskLen, smr, this);
267     }
268
269     public boolean shouldIterateMask() {
270         return this.shouldIterateMask;
271     }
272
273     public boolean shouldUseSmr() {
274         return this.smr;
275     }
276
277     public void setShouldUseSmr(boolean smr) {
278         this.smr = smr;
279     }
280
281     public void setShouldIterateMask(boolean shouldIterateMask) {
282         this.shouldIterateMask = shouldIterateMask;
283         this.mapResolver.setShouldIterateMask(shouldIterateMask);
284         this.mapServer.setShouldIterateMask(shouldIterateMask);
285     }
286
287     public void setShouldAuthenticate(boolean shouldAuthenticate) {
288         this.shouldAuthenticate = shouldAuthenticate;
289         this.mapResolver.setShouldAuthenticate(shouldAuthenticate);
290         this.mapServer.setShouldAuthenticate(shouldAuthenticate);
291     }
292
293     public boolean shouldAuthenticate() {
294         return shouldAuthenticate;
295     }
296
297     @Override
298     public void onSessionInitiated(ProviderContext session) {
299         LOG.info("Lisp Consumer session initialized!");
300         notificationService = session.getSALService(NotificationService.class);
301         registerNotificationListener(AddMapping.class, new MapRegisterNotificationHandler());
302         registerNotificationListener(RequestMapping.class, new MapRequestNotificationHandler());
303         session.addRpcImplementation(LfmMappingDatabaseService.class, this);
304         rpc.setLispMappingService(this);
305         this.session = session;
306     }
307
308     public <T extends Notification> void registerNotificationListener(Class<T> notificationType, NotificationListener<T> listener) {
309         notificationService.registerNotificationListener(notificationType, listener);
310     }
311
312     private class MapRegisterNotificationHandler implements NotificationListener<AddMapping> {
313
314         @Override
315         public void onNotification(AddMapping mapRegisterNotification) {
316             MapNotify mapNotify = handleMapRegister(mapRegisterNotification.getMapRegister(), 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                 LOG.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                 LOG.warn("got null map reply");
344             }
345         }
346     }
347
348     private LfmControlPlaneService getLispSB() {
349         if (lispSB == null) {
350             lispSB = session.getRpcService(LfmControlPlaneService.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         LOG.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     @Override
393     public Future<RpcResult<Void>> addKey(AddKeyInput input) {
394         return rpc.addKey(input);
395     }
396
397     @Override
398     public Future<RpcResult<Void>> addMapping(AddMappingInput input) {
399         return rpc.addMapping(input);
400     }
401
402     @Override
403     public Future<RpcResult<GetKeyOutput>> getKey(GetKeyInput input) {
404         return rpc.getKey(input);
405     }
406
407     @Override
408     public Future<RpcResult<GetMappingOutput>> getMapping(GetMappingInput input) {
409         return rpc.getMapping(input);
410     }
411
412     @Override
413     public Future<RpcResult<Void>> removeKey(RemoveKeyInput input) {
414         return rpc.removeKey(input);
415     }
416
417     @Override
418     public Future<RpcResult<Void>> removeMapping(RemoveMappingInput input) {
419         return rpc.removeMapping(input);
420     }
421
422     @Override
423     public Future<RpcResult<Void>> updateKey(UpdateKeyInput input) {
424         return rpc.updateKey(input);
425     }
426
427     @Override
428     public Future<RpcResult<Void>> updateMapping(UpdateMappingInput input) {
429         return rpc.updateMapping(input);
430     }
431 }