Migrate implementation/neutron/southbound to IETF YANG model
[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             mapService.addMapping(MappingOrigin.Southbound, mapping.getEid(), getSiteId(mapRegister), mapping);
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         }
114         if (!failed) {
115             MapNotifyBuilder builder = new MapNotifyBuilder();
116             if (BooleanUtils.isTrue(mapRegister.isWantMapNotify())) {
117                 LOG.trace("MapRegister wants MapNotify");
118                 MapNotifyBuilderHelper.setFromMapRegister(builder, mapRegister);
119                 if (authenticate) {
120                     builder.setAuthenticationData(LispAuthenticationUtil.createAuthenticationData(builder.build(),
121                             password));
122                 }
123                 notifyHandler.handleMapNotify(builder.build());
124             }
125         }
126     }
127
128     private SiteId getSiteId(MapRegister mapRegister) {
129         return (mapRegister.getSiteId() != null) ? new SiteId(mapRegister.getSiteId()) : null;
130     }
131
132     @Override
133     public void onMappingChanged(MappingChanged notification) {
134         if (subscriptionService) {
135             sendSmrs(notification.getMappingRecord(), getSubscribers(notification.getMappingRecord().getEid()));
136             if (notification.getChangeType().equals(MappingChange.Removed)) {
137                 removeSubscribers(notification.getMappingRecord().getEid());
138             }
139         }
140     }
141
142     private void sendSmrs(MappingRecord record, Set<SubscriberRLOC> subscribers) {
143         Eid eid = record.getEid();
144         handleSmr(record, subscribers, notifyHandler);
145
146         // For SrcDst LCAF also send SMRs to Dst prefix
147         if (eid.getAddress() instanceof SourceDestKey) {
148             Eid dstAddr = SourceDestKeyHelper.getDst(eid);
149             subscribers = getSubscribers(dstAddr);
150             MappingRecord newRecord = new MappingRecordBuilder().setAction(record.getAction())
151                     .setAuthoritative(record.isAuthoritative()).setLocatorRecord(record.getLocatorRecord())
152                     .setMapVersion(record.getMapVersion()).setRecordTtl(record.getRecordTtl())
153                     .setEid(dstAddr).build();
154             handleSmr(newRecord, subscribers, notifyHandler);
155         }
156     }
157
158     private void handleSmr(MappingRecord record, Set<SubscriberRLOC> subscribers, IMapNotifyHandler callback) {
159         if (subscribers == null) {
160             return;
161         }
162         MapRequestBuilder mrb = MapRequestUtil.prepareSMR(record.getEid(), LispAddressUtil.toRloc(getLocalAddress()));
163         LOG.trace("Built SMR packet: " + mrb.build().toString());
164         for (SubscriberRLOC subscriber : subscribers) {
165             if (subscriber.timedOut()) {
166                 LOG.trace("Lazy removing expired subscriber entry " + subscriber.toString());
167                 subscribers.remove(subscriber);
168             } else {
169                 try {
170                     // The address stored in the SMR's EID record is used as Source EID in the SMR-invoked Map-Request.
171                     // To ensure consistent behavior it is set to the value used to originally request a given mapping
172                     mrb.setEidItem(new ArrayList<EidItem>());
173                     mrb.getEidItem().add(new EidItemBuilder().setEid(subscriber.getSrcEid()).build());
174                     callback.handleSMR(mrb.build(), subscriber.getSrcRloc());
175                 } catch (Exception e) {
176                     LOG.error("Errors encountered while handling SMR:" + ExceptionUtils.getStackTrace(e));
177                 }
178             }
179         }
180         addSubscribers(record.getEid(), subscribers);
181     }
182
183     @SuppressWarnings("unchecked")
184     private Set<SubscriberRLOC> getSubscribers(Eid address) {
185         return (Set<SubscriberRLOC>) mapService.getData(MappingOrigin.Southbound, address, SubKeys.SUBSCRIBERS);
186     }
187
188     private void removeSubscribers(Eid address) {
189         mapService.removeData(MappingOrigin.Southbound, address, SubKeys.SUBSCRIBERS);
190     }
191
192     private void addSubscribers(Eid address, Set<SubscriberRLOC> subscribers) {
193         mapService.addData(MappingOrigin.Southbound, address, SubKeys.SUBSCRIBERS, subscribers);
194     }
195
196     private static InetAddress getLocalAddress() {
197         try {
198             Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
199             while (interfaces.hasMoreElements()) {
200                 NetworkInterface current = interfaces.nextElement();
201                 LOG.debug("Interface " + current.toString());
202                 if (!current.isUp() || current.isLoopback() || current.isVirtual())
203                     continue;
204                 Enumeration<InetAddress> addresses = current.getInetAddresses();
205                 while (addresses.hasMoreElements()) {
206                     InetAddress current_addr = addresses.nextElement();
207                     // Skip loopback and link local addresses
208                     if (current_addr.isLoopbackAddress() || current_addr.isLinkLocalAddress())
209                         continue;
210                     LOG.debug(current_addr.getHostAddress());
211                     return current_addr;
212                 }
213             }
214         } catch (SocketException se) {
215         }
216         return null;
217     }
218 }