826955dff5a553b5a27daeadb7030ea2c64aa9c7
[vpnservice.git] / neutronvpn / neutronvpn-impl / src / main / java / org / opendaylight / vpnservice / neutronvpn / NeutronPortChangeListener.java
1 /*
2  * Copyright (c) 2015 - 2016 Ericsson India Global Services Pvt Ltd. 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 package org.opendaylight.vpnservice.neutronvpn;
9
10
11 import com.google.common.base.Optional;
12
13 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
14 import org.opendaylight.controller.md.sal.binding.api.DataChangeListener;
15 import org.opendaylight.controller.md.sal.binding.api.NotificationPublishService;
16 import org.opendaylight.controller.md.sal.binding.api.NotificationService;
17 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
18 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
19 import org.opendaylight.vpnservice.mdsalutil.AbstractDataChangeListener;
20 import org.opendaylight.vpnservice.mdsalutil.MDSALUtil;
21 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.iana._if.type.rev140508.L2vlan;
22 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.Interface;
23 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.InterfaceBuilder;
24 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.PhysAddress;
25 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
26 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.port.attributes.FixedIps;
27 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.Ports;
28 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.ports.Port;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.elan.rev150602.ElanInterfaces;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.elan.rev150602.elan.interfaces.ElanInterface;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.elan.rev150602.elan.interfaces.ElanInterfaceBuilder;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.elan.rev150602.elan.interfaces.ElanInterfaceKey;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.interfacemgr.rev150331.IfL2vlan;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.interfacemgr.rev150331.IfL2vlanBuilder;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.interfacemgr.rev150331.ParentRefs;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.interfacemgr.rev150331.ParentRefsBuilder;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.lockmanager.rev150819.LockManagerService;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.neutronvpn.rev150602.PortAddedToSubnetBuilder;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.neutronvpn.rev150602.PortRemovedFromSubnetBuilder;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.neutronvpn.rev150602.neutron.port.data
42         .PortFixedipToPortNameBuilder;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.neutronvpn.rev150602.subnetmaps.Subnetmap;
44 import org.opendaylight.yangtools.concepts.ListenerRegistration;
45 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48
49 import java.util.ArrayList;
50 import java.util.Iterator;
51 import java.util.List;
52
53
54 public class NeutronPortChangeListener extends AbstractDataChangeListener<Port> implements AutoCloseable {
55     private static final Logger LOG = LoggerFactory.getLogger(NeutronPortChangeListener.class);
56
57     private ListenerRegistration<DataChangeListener> listenerRegistration;
58     private final DataBroker broker;
59     private NeutronvpnManager nvpnManager;
60     private LockManagerService lockManager;
61     private NotificationPublishService notificationPublishService;
62     private NotificationService notificationService;
63
64
65     public NeutronPortChangeListener(final DataBroker db, NeutronvpnManager nVpnMgr,NotificationPublishService notiPublishService, NotificationService notiService) {
66         super(Port.class);
67         broker = db;
68         nvpnManager = nVpnMgr;
69         notificationPublishService = notiPublishService;
70         notificationService = notiService;
71         registerListener(db);
72     }
73
74     public void setLockManager(LockManagerService lockManager) {
75         this.lockManager = lockManager;
76     }
77
78     @Override
79     public void close() throws Exception {
80         if (listenerRegistration != null) {
81             try {
82                 listenerRegistration.close();
83             } catch (final Exception e) {
84                 LOG.error("Error when cleaning up DataChangeListener.", e);
85             }
86             listenerRegistration = null;
87         }
88         LOG.info("N_Port listener Closed");
89     }
90
91
92     private void registerListener(final DataBroker db) {
93         try {
94             listenerRegistration = db.registerDataChangeListener(LogicalDatastoreType.CONFIGURATION,
95                     InstanceIdentifier.create(Neutron.class).child(Ports.class).child(Port.class),
96                     NeutronPortChangeListener.this, DataChangeScope.SUBTREE);
97         } catch (final Exception e) {
98             LOG.error("Neutron Manager Port DataChange listener registration fail!", e);
99             throw new IllegalStateException("Neutron Manager Port DataChange listener registration failed.", e);
100         }
101     }
102
103     @Override
104     protected void add(InstanceIdentifier<Port> identifier, Port input) {
105         if (LOG.isTraceEnabled()) {
106             LOG.trace("Adding Port : key: " + identifier + ", value=" + input);
107         }
108         handleNeutronPortCreated(input);
109
110     }
111
112     @Override
113     protected void remove(InstanceIdentifier<Port> identifier, Port input) {
114         if (LOG.isTraceEnabled()) {
115             LOG.trace("Removing Port : key: " + identifier + ", value=" + input);
116         }
117         handleNeutronPortDeleted(input);
118
119     }
120
121     @Override
122     protected void update(InstanceIdentifier<Port> identifier, Port original, Port update) {
123         if (LOG.isTraceEnabled()) {
124             LOG.trace("Updating Port : key: " + identifier + ", original value=" + original + ", update value=" +
125                     update);
126         }
127         List<FixedIps> oldIPs = (original.getFixedIps() != null) ? original.getFixedIps() : new ArrayList<FixedIps>();
128         List<FixedIps> newIPs = (update.getFixedIps() != null) ? update.getFixedIps() : new ArrayList<FixedIps>();
129
130         if (!oldIPs.equals(newIPs)) {
131             Iterator<FixedIps> iterator = newIPs.iterator();
132             while (iterator.hasNext()) {
133                 FixedIps ip = iterator.next();
134                 if (oldIPs.remove(ip)) {
135                     iterator.remove();
136                 }
137             }
138             handleNeutronPortUpdated(original, update);
139         }
140     }
141
142     private void handleNeutronPortCreated(Port port) {
143         if (!NeutronvpnUtils.isPortVnicTypeNormal(port)) {
144             LOG.info("Port {} is not a NORMAL VNIC Type port; OF Port interfaces are not created",
145                     port.getUuid().getValue());
146             return;
147         }
148         LOG.info("Of-port-interface creation");
149         // Create of-port interface for this neutron port
150         String portInterfaceName = createOfPortInterface(port);
151         LOG.debug("Creating ELAN Interface");
152         createElanInterface(port, portInterfaceName);
153         LOG.debug("Add port to subnet");
154         // add port to local Subnets DS
155         Uuid vpnId = addPortToSubnets(port);
156
157         if (vpnId != null) {
158             // create vpn-interface on this neutron port
159             LOG.debug("Adding VPN Interface");
160             nvpnManager.createVpnInterface(vpnId, port);
161         }
162     }
163
164     private void handleNeutronPortDeleted(Port port) {
165         LOG.debug("Of-port-interface removal");
166         LOG.debug("Remove port from subnet");
167         // remove port from local Subnets DS
168         Uuid vpnId = removePortFromSubnets(port);
169
170         if (vpnId != null) {
171             // remove vpn-interface for this neutron port
172             LOG.debug("removing VPN Interface");
173             nvpnManager.deleteVpnInterface(port);
174         }
175         // Remove of-port interface for this neutron port
176         // ELAN interface is also implicitly deleted as part of this operation
177         deleteOfPortInterface(port);
178
179     }
180
181     private void handleNeutronPortUpdated(Port portoriginal, Port portupdate) {
182         LOG.debug("Add port to subnet");
183         // add port FixedIP to local Subnets DS
184         Uuid vpnIdup = addPortToSubnets(portupdate);
185
186         if (vpnIdup != null) {
187             nvpnManager.createVpnInterface(vpnIdup, portupdate);
188         }
189
190         // remove port FixedIP from local Subnets DS
191         Uuid vpnIdor = removePortFromSubnets(portoriginal);
192
193         if (vpnIdor != null) {
194             nvpnManager.deleteVpnInterface(portoriginal);
195         }
196     }
197
198     private String createOfPortInterface(Port port) {
199         Interface inf = createInterface(port);
200         String infName = inf.getName();
201
202         LOG.debug("Creating OFPort Interface {}", infName);
203         InstanceIdentifier interfaceIdentifier = NeutronvpnUtils.buildVlanInterfaceIdentifier(infName);
204         try {
205             Optional<Interface> optionalInf = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION,
206                     interfaceIdentifier);
207             if (!optionalInf.isPresent()) {
208                 MDSALUtil.syncWrite(broker, LogicalDatastoreType.CONFIGURATION, interfaceIdentifier, inf);
209             } else {
210                 LOG.error("Interface {} is already present", infName);
211             }
212         } catch (Exception e) {
213             LOG.error("failed to create interface {} due to the exception {} ", infName, e.getMessage());
214         }
215         return infName;
216     }
217
218     private Interface createInterface(Port port) {
219         String parentRefName = NeutronvpnUtils.uuidToTapPortName(port.getUuid());;
220         String interfaceName = port.getUuid().getValue();
221         IfL2vlan.L2vlanMode l2VlanMode = IfL2vlan.L2vlanMode.Trunk;
222         InterfaceBuilder interfaceBuilder = new InterfaceBuilder();
223         IfL2vlanBuilder ifL2vlanBuilder = new IfL2vlanBuilder();
224         ifL2vlanBuilder.setL2vlanMode(l2VlanMode);
225         ParentRefsBuilder parentRefsBuilder = new ParentRefsBuilder().setParentInterface(parentRefName);
226         interfaceBuilder.setEnabled(true).setName(interfaceName).setType(L2vlan.class).addAugmentation(IfL2vlan
227                 .class, ifL2vlanBuilder.build()).addAugmentation(ParentRefs.class, parentRefsBuilder.build());
228         return interfaceBuilder.build();
229     }
230
231     private void deleteOfPortInterface(Port port) {
232         String name = port.getUuid().getValue();
233         LOG.debug("Removing OFPort Interface {}", name);
234         InstanceIdentifier interfaceIdentifier = NeutronvpnUtils.buildVlanInterfaceIdentifier(name);
235         try {
236             Optional<Interface> optionalInf = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION,
237                     interfaceIdentifier);
238             if (optionalInf.isPresent()) {
239                 MDSALUtil.syncDelete(broker, LogicalDatastoreType.CONFIGURATION, interfaceIdentifier);
240             } else {
241                 LOG.error("Interface {} is not present", name);
242             }
243         } catch (Exception e) {
244             LOG.error("Failed to delete interface {} due to the exception {}", name, e.getMessage());
245         }
246     }
247
248     private void createElanInterface(Port port, String name) {
249         String elanInstanceName = port.getNetworkId().getValue();
250         List<PhysAddress> physAddresses = new ArrayList<>();
251         physAddresses.add(new PhysAddress(port.getMacAddress()));
252
253         InstanceIdentifier<ElanInterface> id = InstanceIdentifier.builder(ElanInterfaces.class).child(ElanInterface
254                 .class, new ElanInterfaceKey(name)).build();
255         ElanInterface elanInterface = new ElanInterfaceBuilder().setElanInstanceName(elanInstanceName)
256                 .setName(name).setStaticMacEntries(physAddresses).setKey(new ElanInterfaceKey(name)).build();
257         MDSALUtil.syncWrite(broker, LogicalDatastoreType.CONFIGURATION, id, elanInterface);
258         LOG.debug("Creating new ELan Interface {}", elanInterface);
259     }
260
261     // adds port to subnet list and creates vpnInterface
262     private Uuid addPortToSubnets(Port port) {
263         Uuid subnetId = null;
264         Uuid vpnId = null;
265         Subnetmap subnetmap = null;
266         String infName = port.getUuid().getValue();
267         boolean isLockAcquired = false;
268         String lockName = port.getUuid().getValue();
269
270         // find the subnet to which this port is associated
271         FixedIps ip = port.getFixedIps().get(0);
272         String ipValue = ip.getIpAddress().getIpv4Address().getValue();
273         InstanceIdentifier id = NeutronvpnUtils.buildFixedIpToPortNameIdentifier(ipValue);
274         PortFixedipToPortNameBuilder builder = new PortFixedipToPortNameBuilder().setPortFixedip(ipValue)
275                 .setPortName(infName);
276         MDSALUtil.syncWrite(broker, LogicalDatastoreType.CONFIGURATION, id, builder.build());
277         LOG.debug("fixedIp-name map for neutron port with fixedIp: {}, name: {} added to NeutronPortData DS",
278                 ipValue, infName);
279         subnetId = ip.getSubnetId();
280         subnetmap = nvpnManager.updateSubnetNode(subnetId, null, null, null, null, null, port.getUuid());
281         if (subnetmap != null) {
282             vpnId = subnetmap.getVpnId();
283         }
284         if(vpnId != null) {
285             try {
286                 isLockAcquired = NeutronvpnUtils.lock(lockManager, lockName);
287                 checkAndPublishPortAddNotification(subnetmap.getSubnetIp(), subnetId, port.getUuid());
288                 LOG.debug("Port added to subnet notification sent");
289             } catch (Exception e) {
290                 LOG.error("Port added to subnet notification failed", e);
291             } finally {
292                 if (isLockAcquired) {
293                     NeutronvpnUtils.unlock(lockManager, lockName);
294                 }
295             }
296         }
297         return vpnId;
298     }
299
300     private Uuid removePortFromSubnets(Port port) {
301         Uuid subnetId = null;
302         Uuid vpnId = null;
303         Subnetmap subnetmap = null;
304         boolean isLockAcquired = false;
305         String lockName = port.getUuid().getValue();
306
307         // find the subnet to which this port is associated
308         FixedIps ip = port.getFixedIps().get(0);
309         String ipValue = ip.getIpAddress().getIpv4Address().getValue();
310         InstanceIdentifier id = NeutronvpnUtils.buildFixedIpToPortNameIdentifier(ipValue);
311         MDSALUtil.syncDelete(broker, LogicalDatastoreType.CONFIGURATION, id);
312         LOG.debug("fixedIp-name map for neutron port with fixedIp: {} deleted from NeutronPortData DS", ipValue);
313         subnetId = ip.getSubnetId();
314         subnetmap = nvpnManager.removeFromSubnetNode(subnetId, null, null, null, port.getUuid());
315         if (subnetmap != null) {
316             vpnId = subnetmap.getVpnId();
317         }
318         if(vpnId != null) {
319             try {
320                 isLockAcquired = NeutronvpnUtils.lock(lockManager, lockName);
321                 checkAndPublishPortRemoveNotification(subnetmap.getSubnetIp(), subnetId, port.getUuid());
322                 LOG.debug("Port removed from subnet notification sent");
323             } catch (Exception e) {
324                 LOG.error("Port removed from subnet notification failed", e);
325             } finally {
326                 if (isLockAcquired) {
327                     NeutronvpnUtils.unlock(lockManager, lockName);
328                 }
329             }
330         }
331         return vpnId;
332     }
333
334     private void checkAndPublishPortAddNotification(String subnetIp, Uuid subnetId, Uuid portId)throws InterruptedException{
335         PortAddedToSubnetBuilder builder = new PortAddedToSubnetBuilder();
336
337         LOG.info("publish notification called");
338
339         builder.setSubnetIp(subnetIp);
340         builder.setSubnetId(subnetId);
341         builder.setPortId(portId);
342
343         notificationPublishService.putNotification(builder.build());
344     }
345
346     private void checkAndPublishPortRemoveNotification(String subnetIp, Uuid subnetId, Uuid portId)throws InterruptedException{
347         PortRemovedFromSubnetBuilder builder = new PortRemovedFromSubnetBuilder();
348
349         LOG.info("publish notification called");
350
351         builder.setPortId(portId);
352         builder.setSubnetIp(subnetIp);
353         builder.setSubnetId(subnetId);
354
355         notificationPublishService.putNotification(builder.build());
356     }
357 }