Fix LispMappingService closing CSS provider
[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 com.google.common.annotations.VisibleForTesting;
12 import com.google.common.util.concurrent.Futures;
13 import com.google.common.util.concurrent.ListenableFuture;
14 import java.util.List;
15 import java.util.Set;
16 import javax.annotation.PreDestroy;
17 import javax.inject.Inject;
18 import javax.inject.Singleton;
19 import org.apache.commons.lang3.tuple.MutablePair;
20 import org.apache.commons.lang3.tuple.Pair;
21 import org.opendaylight.lispflowmapping.config.ConfigIni;
22 import org.opendaylight.lispflowmapping.implementation.lisp.MapResolver;
23 import org.opendaylight.lispflowmapping.implementation.lisp.MapServer;
24 import org.opendaylight.lispflowmapping.implementation.util.LispNotificationHelper;
25 import org.opendaylight.lispflowmapping.interfaces.lisp.IFlowMapping;
26 import org.opendaylight.lispflowmapping.interfaces.lisp.IMapNotifyHandler;
27 import org.opendaylight.lispflowmapping.interfaces.lisp.IMapRequestResultHandler;
28 import org.opendaylight.lispflowmapping.interfaces.lisp.IMapResolverAsync;
29 import org.opendaylight.lispflowmapping.interfaces.lisp.ISmrNotificationListener;
30 import org.opendaylight.lispflowmapping.interfaces.mappingservice.IMappingService;
31 import org.opendaylight.lispflowmapping.lisp.type.LispMessage;
32 import org.opendaylight.lispflowmapping.lisp.util.LispAddressStringifier;
33 import org.opendaylight.mdsal.binding.api.NotificationService;
34 import org.opendaylight.mdsal.binding.api.NotificationService.CompositeListener;
35 import org.opendaylight.mdsal.binding.api.RpcProviderService;
36 import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonService;
37 import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceProvider;
38 import org.opendaylight.mdsal.singleton.common.api.ServiceGroupIdentifier;
39 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.AddMapping;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.GotMapNotify;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.GotMapReply;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MapNotify;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MapRegister;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MapReply;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MapRequest;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MappingKeepAlive;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.RequestMapping;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.XtrId;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.XtrReplyMapping;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.XtrRequestMapping;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.eid.container.Eid;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.map.register.cache.metadata.container.MapRegisterCacheMetadata;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.map.register.cache.metadata.container.map.register.cache.metadata.EidLispAddress;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapnotifymessage.MapNotifyBuilder;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapreplymessage.MapReplyBuilder;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.maprequestmessage.MapRequestBuilder;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.rloc.container.Rloc;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.transport.address.TransportAddress;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.transport.address.TransportAddressBuilder;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.sb.rev150904.OdlLispSbService;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.sb.rev150904.SendMapNotifyInputBuilder;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.sb.rev150904.SendMapReplyInputBuilder;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.sb.rev150904.SendMapRequestInputBuilder;
65 import org.opendaylight.yangtools.concepts.Registration;
66 import org.osgi.service.component.annotations.Activate;
67 import org.osgi.service.component.annotations.Component;
68 import org.osgi.service.component.annotations.Deactivate;
69 import org.osgi.service.component.annotations.Reference;
70 import org.slf4j.Logger;
71 import org.slf4j.LoggerFactory;
72
73 @Singleton
74 @Component(service = {IFlowMapping.class, IMapRequestResultHandler.class, IMapNotifyHandler.class},
75         immediate = true, property = "type=default")
76 public class LispMappingService implements IFlowMapping, IMapRequestResultHandler,
77         IMapNotifyHandler, AutoCloseable, ClusterSingletonService {
78     private static final String LISPFLOWMAPPING_ENTITY_NAME = "lispflowmapping";
79     private static final ServiceGroupIdentifier SERVICE_GROUP_IDENTIFIER = ServiceGroupIdentifier.create(
80             LISPFLOWMAPPING_ENTITY_NAME);
81
82     private static final Logger LOG = LoggerFactory.getLogger(LispMappingService.class);
83
84     private volatile boolean smr = ConfigIni.getInstance().smrIsSet();
85     private volatile String elpPolicy = ConfigIni.getInstance().getElpPolicy();
86
87     private ThreadLocal<MapReply> tlsMapReply = new ThreadLocal<>();
88     private ThreadLocal<Pair<MapNotify, List<TransportAddress>>> tlsMapNotify = new ThreadLocal<>();
89     private ThreadLocal<Pair<MapRequest, TransportAddress>> tlsMapRequest = new ThreadLocal<>();
90
91     private IMapResolverAsync mapResolver;
92     private MapServer mapServer;
93
94     private final IMappingService mapService;
95     private final OdlLispSbService lispSB;
96     private final ClusterSingletonServiceProvider clusterSingletonService;
97     private final NotificationService notificationService;
98     private final Registration rpcRegistration;
99     private final Registration listenerRegistration;
100     private final Registration cssRegistration;
101
102     @Inject
103     @Activate
104     public LispMappingService(@Reference final IMappingService mappingService,
105             @Reference final OdlLispSbService odlLispService,
106             @Reference final ClusterSingletonServiceProvider clusterSingletonService,
107             @Reference final RpcProviderService rpcProviderService,
108             @Reference final NotificationService notificationService) {
109         this.mapService = mappingService;
110         this.lispSB = odlLispService;
111         this.clusterSingletonService = clusterSingletonService;
112         this.notificationService = notificationService;
113
114         // initialize
115         listenerRegistration = notificationService.registerCompositeListener(new CompositeListener(Set.of(
116                 new CompositeListener.Component<>(AddMapping.class, this::onAddMapping),
117                 new CompositeListener.Component<>(GotMapNotify.class, this::onGotMapNotify),
118                 new CompositeListener.Component<>(RequestMapping.class, this::onRequestMapping),
119                 new CompositeListener.Component<>(GotMapReply.class, this::onGotMapReply),
120                 new CompositeListener.Component<>(XtrRequestMapping.class, this::onXtrRequestMapping),
121                 new CompositeListener.Component<>(XtrReplyMapping.class, this::onXtrReplyMapping),
122                 new CompositeListener.Component<>(MappingKeepAlive.class, this::onMappingKeepAlive))));
123         rpcRegistration = rpcProviderService.registerRpcImplementation(OdlLispSbService.class, lispSB);
124
125         mapResolver = new MapResolver(mapService, smr, elpPolicy, this);
126         mapServer = new MapServer(mapService, smr, this, notificationService);
127         cssRegistration = clusterSingletonService.registerClusterSingletonService(this);
128         mapResolver.setSmrNotificationListener((ISmrNotificationListener) mapServer);
129         LOG.info("LISP (RFC6830) Mapping Service initialized");
130     }
131
132     public boolean shouldUseSmr() {
133         return this.smr;
134     }
135
136     @Override
137     public void setShouldUseSmr(boolean shouldUseSmr) {
138         this.smr = shouldUseSmr;
139         if (mapServer != null) {
140             mapServer.setSubscriptionService(shouldUseSmr);
141         }
142         if (mapResolver != null) {
143             mapResolver.setSubscriptionService(shouldUseSmr);
144         }
145         ConfigIni.getInstance().setSmr(shouldUseSmr);
146     }
147
148     public NotificationService getNotificationService() {
149         return this.notificationService;
150     }
151
152     @Override
153     public MapReply handleMapRequest(MapRequest request) {
154         if (LOG.isDebugEnabled()) {
155             LOG.debug("LISP: Retrieving mapping for {}",
156                     LispAddressStringifier.getString(request.getEidItem().get(0).getEid()));
157         }
158
159         tlsMapReply.set(null);
160         tlsMapRequest.set(null);
161         mapResolver.handleMapRequest(request);
162         // After this invocation we assume that the thread local is filled with the reply
163         if (tlsMapRequest.get() != null) {
164             SendMapRequestInputBuilder smrib = new SendMapRequestInputBuilder();
165             smrib.setMapRequest(new MapRequestBuilder(tlsMapRequest.get().getLeft()).build());
166             smrib.setTransportAddress(tlsMapRequest.get().getRight());
167             getLispSB().sendMapRequest(smrib.build());
168             return null;
169         } else {
170             return tlsMapReply.get();
171         }
172     }
173
174     @Override
175     public Pair<MapNotify, List<TransportAddress>> handleMapRegister(MapRegister mapRegister) {
176         if (LOG.isDebugEnabled()) {
177             LOG.debug("LISP: Adding mapping for {}",
178                     LispAddressStringifier.getString(mapRegister.getMappingRecordItem().get(0)
179                             .getMappingRecord().getEid()));
180         }
181
182         tlsMapNotify.set(null);
183         mapServer.handleMapRegister(mapRegister);
184         // After this invocation we assume that the thread local is filled with the reply
185         return tlsMapNotify.get();
186     }
187
188     public void setShouldAuthenticate(boolean shouldAuthenticate) {
189         this.mapResolver.setShouldAuthenticate(shouldAuthenticate);
190     }
191
192     private void sendMapNotify(MapNotify mapNotify, TransportAddress address) {
193         SendMapNotifyInputBuilder smnib = new SendMapNotifyInputBuilder();
194         smnib.setMapNotify(new MapNotifyBuilder(mapNotify).build());
195         smnib.setTransportAddress(address);
196         getLispSB().sendMapNotify(smnib.build());
197     }
198
199     @VisibleForTesting
200     void onAddMapping(AddMapping mapRegisterNotification) {
201         Pair<MapNotify, List<TransportAddress>> result = handleMapRegister(mapRegisterNotification.getMapRegister());
202         if (result != null && result.getLeft() != null) {
203             MapNotify mapNotify = result.getLeft();
204             List<TransportAddress> rlocs = result.getRight();
205             if (rlocs == null) {
206                 TransportAddressBuilder tab = new TransportAddressBuilder();
207                 tab.setIpAddress(mapRegisterNotification.getTransportAddress().getIpAddress());
208                 tab.setPort(new PortNumber(LispMessage.PORT_NUMBER));
209                 sendMapNotify(mapNotify, tab.build());
210             } else {
211                 for (TransportAddress ta : rlocs) {
212                     sendMapNotify(mapNotify, ta);
213                 }
214             }
215         } else {
216             LOG.debug("Not sending Map-Notify");
217         }
218     }
219
220     @VisibleForTesting
221     void onRequestMapping(RequestMapping mapRequestNotification) {
222         MapReply mapReply = handleMapRequest(mapRequestNotification.getMapRequest());
223         if (mapReply != null) {
224             SendMapReplyInputBuilder smrib = new SendMapReplyInputBuilder();
225             smrib.setMapReply(new MapReplyBuilder(mapReply).build());
226             smrib.setTransportAddress(mapRequestNotification.getTransportAddress());
227             getLispSB().sendMapReply(smrib.build());
228         } else {
229             LOG.debug("handleMapRequest: Got null MapReply");
230         }
231     }
232
233     @VisibleForTesting
234     void onGotMapReply(GotMapReply notification) {
235         LOG.debug("Received GotMapReply notification, ignoring");
236     }
237
238     @VisibleForTesting
239     void onGotMapNotify(GotMapNotify notification) {
240         LOG.debug("Received GotMapNotify notification, ignoring");
241     }
242
243     @VisibleForTesting
244     void onXtrRequestMapping(XtrRequestMapping notification) {
245         LOG.debug("Received XtrRequestMapping notification, ignoring");
246     }
247
248     @VisibleForTesting
249     void onXtrReplyMapping(XtrReplyMapping notification) {
250         LOG.debug("Received XtrReplyMapping notification, ignoring");
251     }
252
253     @VisibleForTesting
254     void onMappingKeepAlive(MappingKeepAlive notification) {
255         final MapRegisterCacheMetadata cacheMetadata = notification.getMapRegisterCacheMetadata();
256         for (EidLispAddress eidLispAddress : cacheMetadata.nonnullEidLispAddress().values()) {
257             final Eid eid = eidLispAddress.getEid();
258             final XtrId xtrId = cacheMetadata.getXtrId();
259             final Long timestamp = cacheMetadata.getTimestamp();
260             LOG.debug("Update map registration for eid {} with timestamp {}", LispAddressStringifier.getString(eid),
261                     timestamp);
262             mapService.refreshMappingRegistration(eid, xtrId, timestamp);
263         }
264     }
265
266     private OdlLispSbService getLispSB() {
267         return lispSB;
268     }
269
270     @Override
271     public void handleMapReply(MapReply reply) {
272         tlsMapReply.set(reply);
273     }
274
275     @Override
276     public void handleMapNotify(MapNotify notify, List<TransportAddress> rlocs) {
277         tlsMapNotify.set(new MutablePair<>(notify, rlocs));
278     }
279
280     @Override
281     public void handleSMR(MapRequest smrMapRequest, Rloc subscriber) {
282         if (LOG.isDebugEnabled()) {
283             LOG.debug("Sending SMR Map-Request to {} with Source-EID {} and EID Record {} (reversed)",
284                     LispAddressStringifier.getString(subscriber),
285                     LispAddressStringifier.getString(smrMapRequest.getSourceEid().getEid()),
286                     LispAddressStringifier.getString(smrMapRequest.getEidItem().get(0).getEid()));
287         }
288         SendMapRequestInputBuilder smrib = new SendMapRequestInputBuilder();
289         smrib.setMapRequest(new MapRequestBuilder(smrMapRequest).build());
290         smrib.setTransportAddress(LispNotificationHelper.getTransportAddressFromRloc(subscriber));
291         getLispSB().sendMapRequest(smrib.build());
292
293     }
294
295     @Override
296     public void handleNonProxyMapRequest(MapRequest mapRequest, TransportAddress transportAddress) {
297         tlsMapRequest.set(new MutablePair<>(mapRequest, transportAddress));
298     }
299
300     private void destroy() {
301         LOG.info("LISP (RFC6830) Mapping Service is destroyed!");
302         mapResolver = null;
303         if (mapServer != null) {
304             mapServer.close();
305             mapServer = null;
306         }
307     }
308
309     @Deactivate
310     @PreDestroy
311     @Override
312     public void close() throws Exception {
313         destroy();
314         cssRegistration.close();
315         clusterSingletonService.close();
316         rpcRegistration.close();
317         listenerRegistration.close();
318     }
319
320     @Override
321     public void instantiateServiceInstance() {
322         mapService.setIsMaster(true);
323     }
324
325     @Override
326     public ListenableFuture<Void> closeServiceInstance() {
327         if (mapService != null) {
328             mapService.setIsMaster(false);
329         }
330         return Futures.<Void>immediateFuture(null);
331     }
332
333     @Override
334     public ServiceGroupIdentifier getIdentifier() {
335         return SERVICE_GROUP_IDENTIFIER;
336     }
337 }