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