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