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