0a58cfdbe5a1cca63fe4a77acab520a68344457c
[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.Set;
17
18 import org.apache.commons.lang3.BooleanUtils;
19 import org.apache.commons.lang3.exception.ExceptionUtils;
20 import org.opendaylight.controller.md.sal.binding.api.NotificationService;
21 import org.opendaylight.lispflowmapping.implementation.authentication.LispAuthenticationUtil;
22 import org.opendaylight.lispflowmapping.interfaces.dao.SubKeys;
23 import org.opendaylight.lispflowmapping.interfaces.dao.SubscriberRLOC;
24 import org.opendaylight.lispflowmapping.interfaces.lisp.IMapNotifyHandler;
25 import org.opendaylight.lispflowmapping.interfaces.lisp.IMapServerAsync;
26 import org.opendaylight.lispflowmapping.interfaces.mappingservice.IMappingService;
27 import org.opendaylight.lispflowmapping.lisp.util.LcafSourceDestHelper;
28 import org.opendaylight.lispflowmapping.lisp.util.LispAFIConvertor;
29 import org.opendaylight.lispflowmapping.lisp.util.MapNotifyBuilderHelper;
30 import org.opendaylight.lispflowmapping.lisp.util.MapRequestUtil;
31 import org.opendaylight.lispflowmapping.lisp.util.MaskUtil;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MapRegister;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.eidrecords.EidRecord;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.eidrecords.EidRecordBuilder;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.eidtolocatorrecords.EidToLocatorRecord;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.eidtolocatorrecords.EidToLocatorRecordBuilder;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.lispaddress.LispAddressContainer;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.lispaddress.lispaddresscontainer.address.LcafSourceDest;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapnotifymessage.MapNotifyBuilder;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.maprequestnotification.MapRequestBuilder;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.mappingservice.rev150906.MappingChange;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.mappingservice.rev150906.MappingChanged;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.mappingservice.rev150906.MappingOrigin;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.mappingservice.rev150906.MappingserviceListener;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.mappingservice.rev150906.SiteId;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48
49 import com.google.common.base.Preconditions;
50
51 public class MapServer implements IMapServerAsync, MappingserviceListener {
52
53     protected static final Logger LOG = LoggerFactory.getLogger(MapServer.class);
54     private IMappingService mapService;
55     private boolean authenticate;
56     private boolean subscriptionService;
57     private IMapNotifyHandler notifyHandler;
58     private NotificationService notificationService;
59
60     public MapServer(IMappingService mapService, boolean authenticate, boolean subscriptionService,
61             IMapNotifyHandler notifyHandler, NotificationService notificationService) {
62         Preconditions.checkNotNull(mapService);
63         this.mapService = mapService;
64         this.authenticate = authenticate;
65         this.subscriptionService = subscriptionService;
66         this.notifyHandler = notifyHandler;
67         this.notificationService = notificationService;
68         if (notificationService != null) {
69             notificationService.registerNotificationListener(this);
70         }
71     }
72
73     @Override
74     public void setSubscriptionService(boolean subscriptionService) {
75         this.subscriptionService = subscriptionService;
76     }
77
78     @Override
79     public boolean shouldAuthenticate() {
80         return authenticate;
81     }
82
83     @Override
84     public void setShouldAuthenticate(boolean shouldAuthenticate) {
85         authenticate = shouldAuthenticate;
86     }
87
88     public void handleMapRegister(MapRegister mapRegister) {
89         boolean failed = false;
90         String password = null;
91         for (EidToLocatorRecord record : mapRegister.getEidToLocatorRecord()) {
92             if (authenticate) {
93                 password = mapService.getAuthenticationKey(record.getLispAddressContainer());
94                 if (!LispAuthenticationUtil.validate(mapRegister, password)) {
95                     LOG.warn("Authentication failed");
96                     failed = true;
97                     break;
98                 }
99             }
100             EidToLocatorRecord oldMapping = (EidToLocatorRecord) mapService.getMapping(MappingOrigin.Southbound,
101                     record.getLispAddressContainer());
102             mapService.addMapping(MappingOrigin.Southbound, record.getLispAddressContainer(), getSiteId(mapRegister),
103                     record);
104             if (subscriptionService && !record.equals(oldMapping)) {
105                 LOG.debug("Sending SMRs for subscribers of {}", record.getLispAddressContainer());
106                 Set<SubscriberRLOC> subscribers = getSubscribers(record.getLispAddressContainer());
107                 sendSmrs(record, subscribers);
108             }
109         }
110         if (!failed) {
111             MapNotifyBuilder builder = new MapNotifyBuilder();
112             if (BooleanUtils.isTrue(mapRegister.isWantMapNotify())) {
113                 LOG.trace("MapRegister wants MapNotify");
114                 MapNotifyBuilderHelper.setFromMapRegister(builder, mapRegister);
115                 if (authenticate) {
116                     builder.setAuthenticationData(LispAuthenticationUtil.createAuthenticationData(builder.build(),
117                             password));
118                 }
119                 notifyHandler.handleMapNotify(builder.build());
120             }
121         }
122     }
123
124     private SiteId getSiteId(MapRegister mapRegister) {
125         return (mapRegister.getSiteId() != null) ? new SiteId(mapRegister.getSiteId()) : null;
126     }
127
128     @Override
129     public void onMappingChanged(MappingChanged notification) {
130         if (subscriptionService) {
131             sendSmrs(new EidToLocatorRecordBuilder(notification.getMapping()).build(), getSubscribers(notification
132                     .getMapping().getLispAddressContainer()));
133             if (notification.getChange().equals(MappingChange.Removed)) {
134                 removeSubscribers(notification.getMapping().getLispAddressContainer());
135             }
136         }
137     }
138
139     private void sendSmrs(EidToLocatorRecord record, Set<SubscriberRLOC> subscribers) {
140         LispAddressContainer eid = record.getLispAddressContainer();
141         handleSmr(record, subscribers, notifyHandler);
142
143         // For SrcDst LCAF also send SMRs to Dst prefix
144         if (eid.getAddress() instanceof LcafSourceDest) {
145             LispAddressContainer dstAddr = LispAFIConvertor.toContainer(LcafSourceDestHelper.getDstAfi(eid));
146             short dstMask = LcafSourceDestHelper.getDstMask(eid);
147             subscribers = getSubscribers(dstAddr);
148             EidToLocatorRecord newRecord = new EidToLocatorRecordBuilder().setAction(record.getAction())
149                     .setAuthoritative(record.isAuthoritative()).setLocatorRecord(record.getLocatorRecord())
150                     .setMapVersion(record.getMapVersion()).setRecordTtl(record.getRecordTtl())
151                     .setLispAddressContainer(dstAddr).setMaskLength(dstMask).build();
152             handleSmr(newRecord, subscribers, notifyHandler);
153         }
154     }
155
156     private void handleSmr(EidToLocatorRecord record, Set<SubscriberRLOC> subscribers, IMapNotifyHandler callback) {
157         if (subscribers == null) {
158             return;
159         }
160         MapRequestBuilder mrb = MapRequestUtil.prepareSMR(record.getLispAddressContainer(),
161                 LispAFIConvertor.toContainer(getLocalAddress()));
162         LOG.trace("Built SMR packet: " + mrb.build().toString());
163         for (SubscriberRLOC subscriber : subscribers) {
164             if (subscriber.timedOut()) {
165                 LOG.trace("Lazy removing expired subscriber entry " + subscriber.toString());
166                 subscribers.remove(subscriber);
167             } else {
168                 try {
169                     // The address stored in the SMR's EID record is used as Source EID in the SMR-invoked Map-Request.
170                     // To ensure consistent behavior it is set to the value used to originally request a given mapping
171                     mrb.setEidRecord(new ArrayList<EidRecord>());
172                     mrb.getEidRecord()
173                             .add(new EidRecordBuilder()
174                                     .setMask(
175                                             (short) MaskUtil.getMaxMask(LispAFIConvertor.toAFI(subscriber.getSrcEid())))
176                                     .setLispAddressContainer(subscriber.getSrcEid()).build());
177                     callback.handleSMR(mrb.build(), subscriber.getSrcRloc());
178                 } catch (Exception e) {
179                     LOG.error("Errors encountered while handling SMR:" + ExceptionUtils.getStackTrace(e));
180                 }
181             }
182         }
183         addSubscribers(record.getLispAddressContainer(), subscribers);
184     }
185
186     @SuppressWarnings("unchecked")
187     private Set<SubscriberRLOC> getSubscribers(LispAddressContainer address) {
188         return (Set<SubscriberRLOC>) mapService.getData(MappingOrigin.Southbound, address, SubKeys.SUBSCRIBERS);
189     }
190
191     private void removeSubscribers(LispAddressContainer address) {
192         mapService.removeData(MappingOrigin.Southbound, address, SubKeys.SUBSCRIBERS);
193     }
194
195     private void addSubscribers(LispAddressContainer address, Set<SubscriberRLOC> subscribers) {
196         mapService.addData(MappingOrigin.Southbound, address, SubKeys.SUBSCRIBERS, subscribers);
197     }
198
199     private static InetAddress getLocalAddress() {
200         try {
201             Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
202             while (interfaces.hasMoreElements()) {
203                 NetworkInterface current = interfaces.nextElement();
204                 LOG.debug("Interface " + current.toString());
205                 if (!current.isUp() || current.isLoopback() || current.isVirtual())
206                     continue;
207                 Enumeration<InetAddress> addresses = current.getInetAddresses();
208                 while (addresses.hasMoreElements()) {
209                     InetAddress current_addr = addresses.nextElement();
210                     // Skip loopback and link local addresses
211                     if (current_addr.isLoopbackAddress() || current_addr.isLinkLocalAddress())
212                         continue;
213                     LOG.debug(current_addr.getHostAddress());
214                     return current_addr;
215                 }
216             }
217         } catch (SocketException se) {
218         }
219         return null;
220     }
221 }