Bug 5267 - Setting vlan id for termination end point not working
[vpnservice.git] / neutronvpn / neutronvpn-impl / src / main / java / org / opendaylight / vpnservice / neutronvpn / NeutronPortChangeListener.java
1 /*
2  * Copyright (c) 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.common.api.data.AsyncDataBroker.DataChangeScope;
16 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
17 import org.opendaylight.vpnservice.mdsalutil.AbstractDataChangeListener;
18 import org.opendaylight.vpnservice.mdsalutil.MDSALUtil;
19 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.iana._if.type.rev140508.L2vlan;
20 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.Interface;
21 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.InterfaceBuilder;
22 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.PhysAddress;
23 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
24 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.port.attributes.FixedIps;
25 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.Ports;
26 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.ports.Port;
27 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron;
28 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.elan.rev150602.ElanInterfaces;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.elan.rev150602.elan.interfaces.ElanInterface;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.elan.rev150602.elan.interfaces.ElanInterfaceBuilder;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.elan.rev150602.elan.interfaces.ElanInterfaceKey;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.neutronvpn.rev150602.neutron.port.data
33         .PortFixedipToPortNameBuilder;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.neutronvpn.rev150602.neutron.port.data
35         .PortNameToPortUuidBuilder;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.neutronvpn.rev150602.subnetmaps.Subnetmap;
37 import org.opendaylight.yangtools.concepts.ListenerRegistration;
38 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41
42 import java.util.ArrayList;
43 import java.util.Iterator;
44 import java.util.List;
45
46
47 public class NeutronPortChangeListener extends AbstractDataChangeListener<Port> implements AutoCloseable {
48     private static final Logger LOG = LoggerFactory.getLogger(NeutronPortChangeListener.class);
49
50     private ListenerRegistration<DataChangeListener> listenerRegistration;
51     private final DataBroker broker;
52     private NeutronvpnManager nvpnManager;
53
54
55     public NeutronPortChangeListener(final DataBroker db, NeutronvpnManager nVpnMgr) {
56         super(Port.class);
57         broker = db;
58         nvpnManager = nVpnMgr;
59         registerListener(db);
60     }
61
62     @Override
63     public void close() throws Exception {
64         if (listenerRegistration != null) {
65             try {
66                 listenerRegistration.close();
67             } catch (final Exception e) {
68                 LOG.error("Error when cleaning up DataChangeListener.", e);
69             }
70             listenerRegistration = null;
71         }
72         LOG.info("N_Port listener Closed");
73     }
74
75
76     private void registerListener(final DataBroker db) {
77         try {
78             listenerRegistration = db.registerDataChangeListener(LogicalDatastoreType.CONFIGURATION,
79                     InstanceIdentifier.create(Neutron.class).child(Ports.class).child(Port.class),
80                     NeutronPortChangeListener.this, DataChangeScope.SUBTREE);
81         } catch (final Exception e) {
82             LOG.error("Neutron Manager Port DataChange listener registration fail!", e);
83             throw new IllegalStateException("Neutron Manager Port DataChange listener registration failed.", e);
84         }
85     }
86
87     @Override
88     protected void add(InstanceIdentifier<Port> identifier, Port input) {
89         if (LOG.isTraceEnabled()) {
90             LOG.trace("Adding Port : key: " + identifier + ", value=" + input);
91         }
92         handleNeutronPortCreated(input);
93
94     }
95
96     @Override
97     protected void remove(InstanceIdentifier<Port> identifier, Port input) {
98         if (LOG.isTraceEnabled()) {
99             LOG.trace("Removing Port : key: " + identifier + ", value=" + input);
100         }
101         handleNeutronPortDeleted(input);
102
103     }
104
105     @Override
106     protected void update(InstanceIdentifier<Port> identifier, Port original, Port update) {
107         if (LOG.isTraceEnabled()) {
108             LOG.trace("Updating Port : key: " + identifier + ", original value=" + original + ", update value=" +
109                     update);
110         }
111         List<FixedIps> oldIPs = (original.getFixedIps() != null) ? original.getFixedIps() : new ArrayList<FixedIps>();
112         List<FixedIps> newIPs = (update.getFixedIps() != null) ? update.getFixedIps() : new ArrayList<FixedIps>();
113
114         if (!oldIPs.equals(newIPs)) {
115             Iterator<FixedIps> iterator = newIPs.iterator();
116             while (iterator.hasNext()) {
117                 FixedIps ip = iterator.next();
118                 if (oldIPs.remove(ip)) {
119                     iterator.remove();
120                 }
121             }
122             handleNeutronPortUpdated(original, update);
123         }
124     }
125
126     private void handleNeutronPortCreated(Port port) {
127         LOG.info("Of-port-interface creation");
128         int portVlanId = NeutronvpnUtils.getVlanFromNeutronPort(port);
129         // Create of-port interface for this neutron port
130         createOfPortInterface(port, portVlanId);
131         LOG.debug("Creating ELAN Interface");
132         createElanInterface(port, portVlanId);
133         LOG.debug("Add port to subnet");
134         // add port to local Subnets DS
135         Uuid vpnId = addPortToSubnets(port);
136
137         if (vpnId != null) {
138             // create vpn-interface on this neutron port
139             LOG.debug("Adding VPN Interface");
140             nvpnManager.createVpnInterface(vpnId, port);
141         }
142     }
143
144     private void handleNeutronPortDeleted(Port port) {
145         LOG.debug("Of-port-interface removal");
146         LOG.debug("Remove port from subnet");
147         // remove port from local Subnets DS
148         Uuid vpnId = removePortFromSubnets(port);
149
150         if (vpnId != null) {
151             // remove vpn-interface for this neutron port
152             LOG.debug("removing VPN Interface");
153             nvpnManager.deleteVpnInterface(port);
154         }
155         int portVlanId = NeutronvpnUtils.getVlanFromNeutronPort(port);
156         // Remove of-port interface for this neutron port
157         // ELAN interface is also implicitly deleted as part of this operation
158         deleteOfPortInterface(port, portVlanId);
159
160     }
161
162     private void handleNeutronPortUpdated(Port portoriginal, Port portupdate) {
163         LOG.debug("Add port to subnet");
164         // add port FixedIPs to local Subnets DS
165         Uuid vpnIdup = addPortToSubnets(portupdate);
166
167         if (vpnIdup != null) {
168             nvpnManager.createVpnInterface(vpnIdup, portupdate);
169         }
170
171         // remove port FixedIPs from local Subnets DS
172         Uuid vpnIdor = removePortFromSubnets(portoriginal);
173
174         if (vpnIdor != null) {
175             nvpnManager.deleteVpnInterface(portoriginal);
176         }
177     }
178
179     private void createOfPortInterface(Port port, int portVlanId) {
180         String name = NeutronvpnUtils.uuidToTapPortName(port.getUuid());
181         //String ifname = new StringBuilder(name).append(":").append(Integer.toString(portVlanId)).toString();
182         //Network network = NeutronvpnUtils.getNeutronNetwork(broker, port.getNetworkId());
183         //Boolean isVlanTransparent = network.isVlanTransparent();
184
185         LOG.debug("Creating OFPort Interface {}", name);
186         InstanceIdentifier interfaceIdentifier = NeutronvpnUtils.buildVlanInterfaceIdentifier(name);
187         try {
188             Optional<Interface> optionalInf = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION,
189                     interfaceIdentifier);
190             if (!optionalInf.isPresent()) {
191                 // handle these for trunkport extensions : portVlanId, isVlanTransparent
192                 Interface inf = new InterfaceBuilder().setEnabled(true).setName(name).setType(L2vlan.class).build();
193                 MDSALUtil.syncWrite(broker, LogicalDatastoreType.CONFIGURATION, interfaceIdentifier, inf);
194             } else {
195                 LOG.error("Interface {} is already present", name);
196             }
197         } catch (Exception e) {
198             LOG.error("failed to create interface {} due to the exception {} ", name, e.getMessage());
199         }
200
201         InstanceIdentifier portIdentifier = NeutronvpnUtils.buildPortNameToPortUuidIdentifier(name);
202         PortNameToPortUuidBuilder builder = new PortNameToPortUuidBuilder().setPortName(name).setPortId(port.getUuid());
203         MDSALUtil.syncWrite(broker, LogicalDatastoreType.CONFIGURATION, portIdentifier, builder.build());
204         LOG.debug("name-uuid map for port with name: {}, uuid: {} added to NeutronPortData DS", name, port.getUuid());
205     }
206
207     private void deleteOfPortInterface(Port port, int portVlanId) {
208         String name = NeutronvpnUtils.uuidToTapPortName(port.getUuid());
209         //String ifname = new StringBuilder(name).append(":").append(Integer.toString(portVlanId)).toString();
210         LOG.debug("Removing OFPort Interface {}", name);
211         InstanceIdentifier interfaceIdentifier = NeutronvpnUtils.buildVlanInterfaceIdentifier(name);
212         try {
213             Optional<Interface> optionalInf = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION,
214                     interfaceIdentifier);
215             if (optionalInf.isPresent()) {
216                 MDSALUtil.syncDelete(broker, LogicalDatastoreType.CONFIGURATION, interfaceIdentifier);
217             } else {
218                 LOG.error("Interface {} is not present", name);
219             }
220         } catch (Exception e) {
221             LOG.error("Failed to delete interface {} due to the exception {}", name, e.getMessage());
222         }
223
224         InstanceIdentifier portIdentifier = NeutronvpnUtils.buildPortNameToPortUuidIdentifier(name);
225         MDSALUtil.syncDelete(broker, LogicalDatastoreType.CONFIGURATION, portIdentifier);
226         LOG.debug("name-uuid map for port with name: {}, uuid: {} deleted from NeutronPortData DS", name, port
227                 .getUuid());
228     }
229
230     private void createElanInterface(Port port, int portVlanId) {
231         String name = NeutronvpnUtils.uuidToTapPortName(port.getUuid());
232         String interfaceName = new StringBuilder(name).append(":").append(Integer.toString(portVlanId)).toString();
233         String elanInstanceName = port.getNetworkId().getValue();
234         List<PhysAddress> physAddresses = new ArrayList<>();
235         physAddresses.add(new PhysAddress(port.getMacAddress()));
236
237         InstanceIdentifier<ElanInterface> id = InstanceIdentifier.builder(ElanInterfaces.class).child(ElanInterface
238                 .class, new ElanInterfaceKey(interfaceName)).build();
239         ElanInterface elanInterface = new ElanInterfaceBuilder().setElanInstanceName(elanInstanceName)
240                 .setName(interfaceName).setStaticMacEntries(physAddresses).
241                         setKey(new ElanInterfaceKey(interfaceName)).build();
242         MDSALUtil.syncWrite(broker, LogicalDatastoreType.CONFIGURATION, id, elanInterface);
243         LOG.debug("Creating new ELan Interface {}", elanInterface);
244     }
245
246     // adds port to subnet list and creates vpnInterface
247     private Uuid addPortToSubnets(Port port) {
248         Uuid subnetId = null;
249         Uuid vpnId = null;
250         String name = NeutronvpnUtils.uuidToTapPortName(port.getUuid());
251
252         // find all subnets to which this port is associated
253         List<FixedIps> ips = port.getFixedIps();
254         for (FixedIps ip : ips) {
255             String ipValue = ip.getIpAddress().getIpv4Address().getValue();
256
257             InstanceIdentifier id = NeutronvpnUtils.buildFixedIpToPortNameIdentifier(ipValue);
258             PortFixedipToPortNameBuilder builder = new PortFixedipToPortNameBuilder().setPortFixedip(ipValue)
259                     .setPortName(name);
260             MDSALUtil.syncWrite(broker, LogicalDatastoreType.CONFIGURATION, id, builder.build());
261             LOG.debug("fixedIp-name map for neutron port with fixedIp: {}, name: {} added to NeutronPortData DS",
262                     ipValue, name);
263
264             subnetId = ip.getSubnetId();
265             Subnetmap subnetmap = nvpnManager.updateSubnetNode(subnetId, null, null, null, null, port.getUuid());
266             if (vpnId == null && subnetmap != null) {
267                 vpnId = subnetmap.getVpnId();
268             }
269         }
270         return vpnId;
271     }
272
273     private Uuid removePortFromSubnets(Port port) {
274         Uuid subnetId = null;
275         Uuid vpnId = null;
276
277         // find all Subnets to which this port is associated
278         List<FixedIps> ips = port.getFixedIps();
279         for (FixedIps ip : ips) {
280             String ipValue = ip.getIpAddress().getIpv4Address().getValue();
281
282             InstanceIdentifier id = NeutronvpnUtils.buildFixedIpToPortNameIdentifier(ipValue);
283             MDSALUtil.syncDelete(broker, LogicalDatastoreType.CONFIGURATION, id);
284             LOG.debug("fixedIp-name map for neutron port with fixedIp: {} deleted from NeutronPortData DS", ipValue);
285
286             subnetId = ip.getSubnetId();
287             Subnetmap subnetmap = nvpnManager.removeFromSubnetNode(subnetId, null, null, null, port.getUuid());
288             if (vpnId == null && subnetmap != null) {
289                 vpnId = subnetmap.getVpnId();
290             }
291         }
292         return vpnId;
293     }
294 }