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