Bug 5228: Use custom comparator for mappings
[lispflowmapping.git] / mappingservice / implementation / src / main / java / org / opendaylight / lispflowmapping / implementation / lisp / MapServer.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.lisp;
10
11 import java.net.InetAddress;
12 import java.net.NetworkInterface;
13 import java.net.SocketException;
14 import java.util.ArrayList;
15 import java.util.Arrays;
16 import java.util.Enumeration;
17 import java.util.HashSet;
18 import java.util.List;
19 import java.util.Objects;
20 import java.util.Set;
21
22 import org.apache.commons.lang3.BooleanUtils;
23 import org.apache.commons.lang3.exception.ExceptionUtils;
24 import org.opendaylight.controller.md.sal.binding.api.NotificationService;
25 import org.opendaylight.lispflowmapping.implementation.authentication.LispAuthenticationUtil;
26 import org.opendaylight.lispflowmapping.implementation.config.ConfigIni;
27 import org.opendaylight.lispflowmapping.interfaces.dao.SubKeys;
28 import org.opendaylight.lispflowmapping.interfaces.dao.SubscriberRLOC;
29 import org.opendaylight.lispflowmapping.interfaces.lisp.IMapNotifyHandler;
30 import org.opendaylight.lispflowmapping.interfaces.lisp.IMapServerAsync;
31 import org.opendaylight.lispflowmapping.interfaces.mappingservice.IMappingService;
32 import org.opendaylight.lispflowmapping.lisp.type.LispMessage;
33 import org.opendaylight.lispflowmapping.lisp.util.LispAddressStringifier;
34 import org.opendaylight.lispflowmapping.lisp.util.LispAddressUtil;
35 import org.opendaylight.lispflowmapping.lisp.util.MapNotifyBuilderHelper;
36 import org.opendaylight.lispflowmapping.lisp.util.MapRequestUtil;
37 import org.opendaylight.lispflowmapping.lisp.util.SourceDestKeyHelper;
38 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddress;
39 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.PortNumber;
40 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.SourceDestKey;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MapRegister;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.eid.container.Eid;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.eid.list.EidItem;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.eid.list.EidItemBuilder;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapnotifymessage.MapNotifyBuilder;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.record.container.MappingRecord;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.record.container.MappingRecordBuilder;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.record.list.MappingRecordItem;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.record.list.MappingRecordItemBuilder;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.maprequestnotification.MapRequestBuilder;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.transport.address.TransportAddress;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.transport.address.TransportAddressBuilder;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.mappingservice.rev150906.MappingChange;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.mappingservice.rev150906.MappingChanged;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.mappingservice.rev150906.MappingOrigin;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.mappingservice.rev150906.OdlMappingserviceListener;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.mappingservice.rev150906.SiteId;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.mappingservice.rev150906.mapping.authkey.container.MappingAuthkey;
59 import org.slf4j.Logger;
60 import org.slf4j.LoggerFactory;
61
62 import com.google.common.base.Preconditions;
63
64 public class MapServer implements IMapServerAsync, OdlMappingserviceListener {
65
66     protected static final Logger LOG = LoggerFactory.getLogger(MapServer.class);
67     private IMappingService mapService;
68     private boolean authenticate;
69     private boolean subscriptionService;
70     private IMapNotifyHandler notifyHandler;
71     private NotificationService notificationService;
72
73     public MapServer(IMappingService mapService, boolean authenticate, boolean subscriptionService,
74             IMapNotifyHandler notifyHandler, NotificationService notificationService) {
75         Preconditions.checkNotNull(mapService);
76         this.mapService = mapService;
77         this.authenticate = authenticate;
78         this.subscriptionService = subscriptionService;
79         this.notifyHandler = notifyHandler;
80         this.notificationService = notificationService;
81         if (notificationService != null) {
82             notificationService.registerNotificationListener(this);
83         }
84     }
85
86     @Override
87     public void setSubscriptionService(boolean subscriptionService) {
88         this.subscriptionService = subscriptionService;
89     }
90
91     @Override
92     public boolean shouldAuthenticate() {
93         return authenticate;
94     }
95
96     @Override
97     public void setShouldAuthenticate(boolean shouldAuthenticate) {
98         authenticate = shouldAuthenticate;
99     }
100
101     @SuppressWarnings("unchecked")
102     public void handleMapRegister(MapRegister mapRegister) {
103         boolean failed = false;
104         boolean updated = false;
105         String password = null;
106         Set<SubscriberRLOC> subscribers = null;
107         MappingRecord oldMapping;
108
109         for (MappingRecordItem record : mapRegister.getMappingRecordItem()) {
110             MappingRecord mapping = record.getMappingRecord();
111             if (authenticate) {
112                 MappingAuthkey authkey = mapService.getAuthenticationKey(mapping.getEid());
113                 if (authkey != null) {
114                     password = authkey.getKeyString();
115                 }
116                 if (!LispAuthenticationUtil.validate(mapRegister, password)) {
117                     LOG.warn("Authentication failed");
118                     failed = true;
119                     break;
120                 }
121             }
122             oldMapping = (MappingRecord) mapService.getMapping(MappingOrigin.Southbound, mapping.getEid());
123
124             if (subscriptionService && mappingChanged(oldMapping, mapping)) {
125                 if (LOG.isDebugEnabled()){
126                     LOG.debug("Mapping update occured for {} SMRs will be sent for its subscribers.",
127                             LispAddressStringifier.getString(mapping.getEid()));
128                 }
129                 subscribers = getSubscribers(mapping.getEid());
130                 updated = true;
131             }
132             // Must update the record before sending SMRs
133             mapService.addMapping(MappingOrigin.Southbound, mapping.getEid(), getSiteId(mapRegister), mapping);
134             if (updated) {
135                 updated = false;
136                 sendSmrs(mapping, subscribers);
137             }
138         }
139         if (!failed && BooleanUtils.isTrue(mapRegister.isWantMapNotify())) {
140             LOG.trace("MapRegister wants MapNotify");
141             MapNotifyBuilder builder = new MapNotifyBuilder();
142             List<TransportAddress> rlocs = null;
143             if (ConfigIni.getInstance().mappingMergeIsSet()) {
144                 Set<IpAddress> notifyRlocs = new HashSet<IpAddress>();
145                 List<MappingRecordItem> mergedMappings = new ArrayList<MappingRecordItem>();
146                 for (MappingRecordItem record : mapRegister.getMappingRecordItem()) {
147                     MappingRecord mapping = record.getMappingRecord();
148                     MappingRecord currentRecord = (MappingRecord) mapService.getMapping(MappingOrigin.Southbound,
149                             mapping.getEid());
150                     mergedMappings.add(new MappingRecordItemBuilder().setMappingRecord(currentRecord).build());
151                     Set<IpAddress> sourceRlocs = (Set<IpAddress>) mapService.getData(MappingOrigin.Southbound,
152                             mapping.getEid(), SubKeys.SRC_RLOCS);
153                     notifyRlocs.addAll(sourceRlocs);
154                 }
155                 MapNotifyBuilderHelper.setFromMapRegisterAndMappingRecordItems(builder, mapRegister, mergedMappings);
156                 rlocs = getTransportAddresses(notifyRlocs);
157             } else {
158                 MapNotifyBuilderHelper.setFromMapRegister(builder, mapRegister);
159             }
160             if (authenticate) {
161                 builder.setAuthenticationData(LispAuthenticationUtil.createAuthenticationData(builder.build(),
162                         password));
163             }
164             notifyHandler.handleMapNotify(builder.build(), rlocs);
165         }
166     }
167
168     private static List<TransportAddress> getTransportAddresses(Set<IpAddress> addresses) {
169         List<TransportAddress> rlocs = new ArrayList<TransportAddress>();
170         for (IpAddress address : addresses) {
171             TransportAddressBuilder tab = new TransportAddressBuilder();
172             tab.setIpAddress(address);
173             tab.setPort(new PortNumber(LispMessage.PORT_NUM));
174             rlocs.add(tab.build());
175         }
176         return rlocs;
177     }
178
179     private SiteId getSiteId(MapRegister mapRegister) {
180         return (mapRegister.getSiteId() != null) ? new SiteId(mapRegister.getSiteId()) : null;
181     }
182
183     @Override
184     public void onMappingChanged(MappingChanged notification) {
185         if (subscriptionService) {
186             sendSmrs(notification.getMappingRecord(), getSubscribers(notification.getMappingRecord().getEid()));
187             if (notification.getChangeType().equals(MappingChange.Removed)) {
188                 removeSubscribers(notification.getMappingRecord().getEid());
189             }
190         }
191     }
192
193     private static boolean mappingChanged(MappingRecord oldMapping, MappingRecord newMapping) {
194         // We only check for fields we care about
195         // XXX: This code needs to be checked and updated when the YANG model is modified
196         Preconditions.checkNotNull(newMapping, "The new mapping should never be null");
197         if (oldMapping == null) {
198             LOG.trace("mappingChanged(): old mapping is null");
199             return true;
200         } else if (!Objects.equals(oldMapping.getEid(), newMapping.getEid())) {
201             LOG.trace("mappingChanged(): EID");
202             return true;
203         } else if (!Objects.equals(oldMapping.getLocatorRecord(), newMapping.getLocatorRecord())) {
204             LOG.trace("mappingChanged(): RLOC");
205             return true;
206         } else if (!Objects.equals(oldMapping.getAction(), newMapping.getAction())) {
207             LOG.trace("mappingChanged(): action");
208             return true;
209         } else if (!Objects.equals(oldMapping.getRecordTtl(), newMapping.getRecordTtl())) {
210             LOG.trace("mappingChanged(): TTL");
211             return true;
212         } else if (!Arrays.equals(oldMapping.getXtrId(), newMapping.getXtrId())) {
213             LOG.trace("mappingChanged(): xTR-ID");
214             return true;
215         } else if (!Arrays.equals(oldMapping.getSiteId(), newMapping.getSiteId())) {
216             LOG.trace("mappingChanged(): site-ID");
217             return true;
218         } else if (!Objects.equals(oldMapping.getMapVersion(), newMapping.getMapVersion())) {
219             LOG.trace("mappingChanged(): mapping version");
220             return true;
221         }
222         return false;
223     }
224
225     private void sendSmrs(MappingRecord record, Set<SubscriberRLOC> subscribers) {
226         Eid eid = record.getEid();
227         handleSmr(record, subscribers, notifyHandler);
228
229         // For SrcDst LCAF also send SMRs to Dst prefix
230         if (eid.getAddress() instanceof SourceDestKey) {
231             Eid dstAddr = SourceDestKeyHelper.getDst(eid);
232             Set<SubscriberRLOC> dstSubs = getSubscribers(dstAddr);
233             MappingRecord newRecord = new MappingRecordBuilder().setAction(record.getAction())
234                     .setAuthoritative(record.isAuthoritative()).setLocatorRecord(record.getLocatorRecord())
235                     .setMapVersion(record.getMapVersion()).setRecordTtl(record.getRecordTtl())
236                     .setEid(dstAddr).build();
237             handleSmr(newRecord, dstSubs, notifyHandler);
238         }
239     }
240
241     private void handleSmr(MappingRecord record, Set<SubscriberRLOC> subscribers, IMapNotifyHandler callback) {
242         if (subscribers == null) {
243             return;
244         }
245         MapRequestBuilder mrb = MapRequestUtil.prepareSMR(record.getEid(), LispAddressUtil.toRloc(getLocalAddress()));
246         LOG.trace("Built SMR packet: " + mrb.build().toString());
247         for (SubscriberRLOC subscriber : subscribers) {
248             if (subscriber.timedOut()) {
249                 LOG.trace("Lazy removing expired subscriber entry " + subscriber.toString());
250                 subscribers.remove(subscriber);
251             } else {
252                 try {
253                     // The address stored in the SMR's EID record is used as Source EID in the SMR-invoked Map-Request.
254                     // To ensure consistent behavior it is set to the value used to originally request a given mapping
255                     mrb.setEidItem(new ArrayList<EidItem>());
256                     mrb.getEidItem().add(new EidItemBuilder().setEid(subscriber.getSrcEid()).build());
257                     callback.handleSMR(mrb.build(), subscriber.getSrcRloc());
258                 } catch (Exception e) {
259                     LOG.error("Errors encountered while handling SMR:" + ExceptionUtils.getStackTrace(e));
260                 }
261             }
262         }
263         addSubscribers(record.getEid(), subscribers);
264     }
265
266     @SuppressWarnings("unchecked")
267     private Set<SubscriberRLOC> getSubscribers(Eid address) {
268         return (Set<SubscriberRLOC>) mapService.getData(MappingOrigin.Southbound, address, SubKeys.SUBSCRIBERS);
269     }
270
271     private void removeSubscribers(Eid address) {
272         mapService.removeData(MappingOrigin.Southbound, address, SubKeys.SUBSCRIBERS);
273     }
274
275     private void addSubscribers(Eid address, Set<SubscriberRLOC> subscribers) {
276         mapService.addData(MappingOrigin.Southbound, address, SubKeys.SUBSCRIBERS, subscribers);
277     }
278
279     private static InetAddress getLocalAddress() {
280         try {
281             Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
282             while (interfaces.hasMoreElements()) {
283                 NetworkInterface current = interfaces.nextElement();
284                 LOG.debug("Interface " + current.toString());
285                 if (!current.isUp() || current.isLoopback() || current.isVirtual()) {
286                     continue;
287                 }
288                 Enumeration<InetAddress> addresses = current.getInetAddresses();
289                 while (addresses.hasMoreElements()) {
290                     InetAddress current_addr = addresses.nextElement();
291                     // Skip loopback and link local addresses
292                     if (current_addr.isLoopbackAddress() || current_addr.isLinkLocalAddress()) {
293                         continue;
294                     }
295                     LOG.debug(current_addr.getHostAddress());
296                     return current_addr;
297                 }
298             }
299         } catch (SocketException se) {
300             LOG.debug("Caught socket exceptio", se);
301         }
302         return null;
303     }
304 }