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