Clean up lambdas
[netvirt.git] / vpnservice / neutronvpn / neutronvpn-impl / src / main / java / org / opendaylight / netvirt / 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.netvirt.neutronvpn;
9
10 import static org.opendaylight.netvirt.neutronvpn.NeutronvpnUtils.buildfloatingIpIdToPortMappingIdentifier;
11
12 import com.google.common.base.Optional;
13 import com.google.common.util.concurrent.ListenableFuture;
14 import java.util.ArrayList;
15 import java.util.Iterator;
16 import java.util.List;
17 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
18 import org.opendaylight.controller.md.sal.binding.api.NotificationPublishService;
19 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
20 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
21 import org.opendaylight.genius.datastoreutils.AsyncDataTreeChangeListenerBase;
22 import org.opendaylight.genius.datastoreutils.DataStoreJobCoordinator;
23 import org.opendaylight.genius.mdsalutil.MDSALUtil;
24 import org.opendaylight.genius.mdsalutil.NwConstants;
25 import org.opendaylight.netvirt.elanmanager.api.IElanService;
26 import org.opendaylight.netvirt.neutronvpn.api.utils.NeutronConstants;
27 import org.opendaylight.netvirt.neutronvpn.api.utils.NeutronUtils;
28 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.iana._if.type.rev140508.L2vlan;
29 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.Interface;
30 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.InterfaceBuilder;
31 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.PhysAddress;
32 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.IfL2vlan;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.IfL2vlanBuilder;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.ParentRefs;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.ParentRefsBuilder;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.OdlInterfaceRpcService;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.InterfaceAcl;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.InterfaceAclBuilder;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.interfaces._interface.AllowedAddressPairs;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInterfaces;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.ElanInterface;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.ElanInterfaceBuilder;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.ElanInterfaceKey;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.floating.ip.port.info.FloatingIpIdToPortMappingBuilder;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.floating.ip.port.info.FloatingIpIdToPortMappingKey;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.subnetmaps.Subnetmap;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.routers.attributes.routers.Router;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.networks.attributes.networks.Network;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.port.attributes.FixedIps;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.Ports;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.ports.Port;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.qos.ext.rev160613.QosPortExtension;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron;
55 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
58
59 public class NeutronPortChangeListener extends AsyncDataTreeChangeListenerBase<Port, NeutronPortChangeListener>
60         implements AutoCloseable {
61     private static final Logger LOG = LoggerFactory.getLogger(NeutronPortChangeListener.class);
62     private final DataBroker dataBroker;
63     private final NeutronvpnManager nvpnManager;
64     private final NeutronvpnNatManager nvpnNatManager;
65     private final NotificationPublishService notificationPublishService;
66     private final NeutronSubnetGwMacResolver gwMacResolver;
67     private OdlInterfaceRpcService odlInterfaceRpcService;
68     private final IElanService elanService;
69
70     public NeutronPortChangeListener(final DataBroker dataBroker,
71                                      final NeutronvpnManager neutronvpnManager,
72                                      final NeutronvpnNatManager neutronvpnNatManager,
73                                      final NotificationPublishService notiPublishService,
74                                      final NeutronSubnetGwMacResolver gwMacResolver,
75                                      final OdlInterfaceRpcService odlInterfaceRpcService,
76                                      final IElanService elanService) {
77         super(Port.class, NeutronPortChangeListener.class);
78         this.dataBroker = dataBroker;
79         nvpnManager = neutronvpnManager;
80         nvpnNatManager = neutronvpnNatManager;
81         notificationPublishService = notiPublishService;
82         this.gwMacResolver = gwMacResolver;
83         this.odlInterfaceRpcService = odlInterfaceRpcService;
84         this.elanService = elanService;
85     }
86
87
88     public void start() {
89         LOG.info("{} start", getClass().getSimpleName());
90         registerListener(LogicalDatastoreType.CONFIGURATION, dataBroker);
91     }
92
93     @Override
94     protected InstanceIdentifier<Port> getWildCardPath() {
95         return InstanceIdentifier.create(Neutron.class).child(Ports.class).child(Port.class);
96     }
97
98     @Override
99     protected NeutronPortChangeListener getDataTreeChangeListener() {
100         return NeutronPortChangeListener.this;
101     }
102
103
104     @Override
105     protected void add(InstanceIdentifier<Port> identifier, Port input) {
106         String portName = input.getUuid().getValue();
107         LOG.trace("Adding Port : key: {}, value={}", identifier, input);
108         Network network = NeutronvpnUtils.getNeutronNetwork(dataBroker, input.getNetworkId());
109         if (network == null || !NeutronvpnUtils.isNetworkTypeSupported(network)) {
110             //FIXME: This should be removed when support for VLAN and GRE network types is added
111             LOG.error("neutron vpn doesn't support vlan/gre network provider type for the port {} which is part of "
112                 + "network {}.", portName, network);
113             return;
114         }
115         NeutronvpnUtils.addToPortCache(input);
116
117         /* check if router interface has been created */
118         if ((input.getDeviceOwner() != null) && (input.getDeviceId() != null)) {
119             if (input.getDeviceOwner().equals(NeutronConstants.DEVICE_OWNER_ROUTER_INF)) {
120                 handleRouterInterfaceAdded(input);
121                 /* nothing else to do here */
122                 return;
123             }
124             if (NeutronConstants.DEVICE_OWNER_GATEWAY_INF.equals(input.getDeviceOwner())) {
125                 handleRouterGatewayUpdated(input);
126             } else if (NeutronConstants.DEVICE_OWNER_FLOATING_IP.equals(input.getDeviceOwner())) {
127
128                 // populate floating-ip uuid and floating-ip port attributes (uuid, mac and subnet id for the ONLY
129                 // fixed IP) to be used by NAT, depopulated in NATService once mac is retrieved in the removal path
130                 addToFloatingIpPortInfo(new Uuid(input.getDeviceId()), input.getUuid(), input.getFixedIps().get(0)
131                                 .getSubnetId(), input.getMacAddress().getValue());
132
133                 elanService.handleKnownL3DmacAddress(input.getMacAddress().getValue(), input.getNetworkId().getValue(),
134                         NwConstants.ADD_FLOW);
135             }
136         }
137         if (input.getFixedIps() != null && !input.getFixedIps().isEmpty()) {
138             handleNeutronPortCreated(input);
139         }
140     }
141
142     @Override
143     protected void remove(InstanceIdentifier<Port> identifier, Port input) {
144         LOG.trace("Removing Port : key: {}, value={}", identifier, input);
145         Network network = NeutronvpnUtils.getNeutronNetwork(dataBroker, input.getNetworkId());
146         if (network == null || !NeutronvpnUtils.isNetworkTypeSupported(network)) {
147             //FIXME: This should be removed when support for VLAN and GRE network types is added
148             LOG.error("neutron vpn doesn't support vlan/gre network provider type for the port {} which is part of "
149                 + "network {}.", input.getUuid().getValue(), network);
150             return;
151         }
152         NeutronvpnUtils.removeFromPortCache(input);
153
154         if ((input.getDeviceOwner() != null) && (input.getDeviceId() != null)) {
155             if (input.getDeviceOwner().equals(NeutronConstants.DEVICE_OWNER_ROUTER_INF)) {
156                 handleRouterInterfaceRemoved(input);
157                 /* nothing else to do here */
158                 return;
159             } else if (NeutronConstants.DEVICE_OWNER_GATEWAY_INF.equals(input.getDeviceOwner())
160                     || NeutronConstants.DEVICE_OWNER_FLOATING_IP.equals(input.getDeviceOwner())) {
161                 elanService.handleKnownL3DmacAddress(input.getMacAddress().getValue(), input.getNetworkId().getValue(),
162                         NwConstants.DEL_FLOW);
163             }
164         }
165         if (input.getFixedIps() != null && !input.getFixedIps().isEmpty()) {
166             handleNeutronPortDeleted(input);
167         }
168     }
169
170     @Override
171     // TODO Clean up the exception handling
172     @SuppressWarnings("checkstyle:IllegalCatch")
173     protected void update(InstanceIdentifier<Port> identifier, Port original, Port update) {
174         final String portName = update.getUuid().getValue();
175         LOG.trace("Updating Port : key: {}, original value={}, update value={}", identifier, original, update);
176         Network network = NeutronvpnUtils.getNeutronNetwork(dataBroker, update.getNetworkId());
177         if (network == null || !NeutronvpnUtils.isNetworkTypeSupported(network)) {
178             LOG.error("neutron vpn doesn't support vlan/gre network provider type for the port {} which is part of "
179                 + "network {}. Skipping the processing of Port update DCN", portName, network);
180             return;
181         }
182         NeutronvpnUtils.addToPortCache(update);
183
184         /* check if router interface has been updated */
185         if ((update.getDeviceOwner() != null) && (update.getDeviceId() != null)) {
186             if (update.getDeviceOwner().equals(NeutronConstants.DEVICE_OWNER_ROUTER_INF)) {
187                 handleRouterInterfaceAdded(update);
188                 /* nothing else to do here */
189                 return;
190             }
191         }
192
193         // check if VIF type updated as part of port binding
194         // check if port security enabled/disabled as part of port update
195         boolean isPortVifTypeUpdated = NeutronvpnUtils.isPortVifTypeUpdated(original, update);
196         boolean origSecurityEnabled = NeutronvpnUtils.getPortSecurityEnabled(original);
197         boolean updatedSecurityEnabled = NeutronvpnUtils.getPortSecurityEnabled(update);
198
199         if (isPortVifTypeUpdated || origSecurityEnabled || updatedSecurityEnabled) {
200             InstanceIdentifier interfaceIdentifier = NeutronvpnUtils.buildVlanInterfaceIdentifier(portName);
201             final DataStoreJobCoordinator portDataStoreCoordinator = DataStoreJobCoordinator.getInstance();
202             portDataStoreCoordinator.enqueueJob("PORT- " + portName, () -> {
203                 WriteTransaction wrtConfigTxn = dataBroker.newWriteOnlyTransaction();
204                 try {
205                     Optional<Interface> optionalInf = NeutronvpnUtils.read(dataBroker, LogicalDatastoreType
206                             .CONFIGURATION, interfaceIdentifier);
207                     if (optionalInf.isPresent()) {
208                         InterfaceBuilder interfaceBuilder = new InterfaceBuilder(optionalInf.get());
209                         if (isPortVifTypeUpdated && getParentRefsBuilder(update) != null) {
210                             interfaceBuilder.addAugmentation(ParentRefs.class,
211                                 getParentRefsBuilder(update).build());
212                         }
213                         if (origSecurityEnabled || updatedSecurityEnabled) {
214                             InterfaceAcl infAcl = handlePortSecurityUpdated(original, update,
215                                     origSecurityEnabled, updatedSecurityEnabled, interfaceBuilder).build();
216                             interfaceBuilder.addAugmentation(InterfaceAcl.class, infAcl);
217                         }
218                         LOG.info("Of-port-interface updation for port {}", portName);
219                         // Update OFPort interface for this neutron port
220                         wrtConfigTxn.put(LogicalDatastoreType.CONFIGURATION, interfaceIdentifier,
221                                 interfaceBuilder.build());
222                     } else {
223                         LOG.error("Interface {} is not present", portName);
224                     }
225                 } catch (Exception e) {
226                     LOG.error("Failed to update interface {} due to the exception {}", portName, e);
227                 }
228                 List<ListenableFuture<Void>> futures = new ArrayList<>();
229                 futures.add(wrtConfigTxn.submit());
230                 return futures;
231             });
232         }
233         List<FixedIps> oldIPs = (original.getFixedIps() != null) ? original.getFixedIps() : new ArrayList<>();
234         List<FixedIps> newIPs = (update.getFixedIps() != null) ? update.getFixedIps() : new ArrayList<>();
235         if (!oldIPs.equals(newIPs)) {
236             Iterator<FixedIps> iterator = newIPs.iterator();
237             while (iterator.hasNext()) {
238                 FixedIps ip = iterator.next();
239                 if (oldIPs.remove(ip)) {
240                     iterator.remove();
241                 }
242             }
243             handleNeutronPortUpdated(original, update);
244         }
245         if (NeutronConstants.DEVICE_OWNER_GATEWAY_INF.equals(update.getDeviceOwner())) {
246             handleRouterGatewayUpdated(update);
247         } else if (NeutronConstants.DEVICE_OWNER_FLOATING_IP.equals(update.getDeviceOwner())) {
248             elanService.handleKnownL3DmacAddress(update.getMacAddress().getValue(), update.getNetworkId().getValue(),
249                     NwConstants.ADD_FLOW);
250         }
251         // check for QoS updates
252         QosPortExtension updateQos = update.getAugmentation(QosPortExtension.class);
253         QosPortExtension originalQos = original.getAugmentation(QosPortExtension.class);
254         if (originalQos == null && updateQos != null) {
255             // qos policy add
256             NeutronvpnUtils.addToQosPortsCache(updateQos.getQosPolicyId(), update);
257             NeutronQosUtils.handleNeutronPortQosUpdate(dataBroker, odlInterfaceRpcService,
258                     update, updateQos.getQosPolicyId());
259         } else if (originalQos != null && updateQos != null
260                 && !originalQos.getQosPolicyId().equals(updateQos.getQosPolicyId())) {
261             // qos policy update
262             NeutronvpnUtils.removeFromQosPortsCache(originalQos.getQosPolicyId(), original);
263             NeutronvpnUtils.addToQosPortsCache(updateQos.getQosPolicyId(), update);
264             NeutronQosUtils.handleNeutronPortQosUpdate(dataBroker, odlInterfaceRpcService,
265                     update, updateQos.getQosPolicyId());
266         } else if (originalQos != null && updateQos == null) {
267             // qos policy delete
268             NeutronQosUtils.handleNeutronPortQosRemove(dataBroker, odlInterfaceRpcService,
269                     original, originalQos.getQosPolicyId());
270             NeutronvpnUtils.removeFromQosPortsCache(originalQos.getQosPolicyId(), original);
271         }
272     }
273
274     private void handleRouterInterfaceAdded(Port routerPort) {
275         if (routerPort.getDeviceId() != null) {
276             Uuid routerId = new Uuid(routerPort.getDeviceId());
277             Uuid infNetworkId = routerPort.getNetworkId();
278             Uuid existingVpnId = NeutronvpnUtils.getVpnForNetwork(dataBroker, infNetworkId);
279
280             elanService.handleKnownL3DmacAddress(routerPort.getMacAddress().getValue(), infNetworkId.getValue(),
281                     NwConstants.ADD_FLOW);
282             if (existingVpnId == null) {
283                 for (FixedIps portIP : routerPort.getFixedIps()) {
284                     Uuid vpnId = NeutronvpnUtils.getVpnForRouter(dataBroker, routerId, true);
285                     if (vpnId == null) {
286                         vpnId = routerId;
287                     }
288                     // NOTE:  Please donot change the order of calls to updateSubnetNodeWithFixedIPs
289                     // and addSubnetToVpn here
290                     String ipValue = String.valueOf(portIP.getIpAddress().getValue());
291                     nvpnManager.updateSubnetNodeWithFixedIps(portIP.getSubnetId(), routerId,
292                             routerPort.getUuid(), ipValue, routerPort.getMacAddress().getValue());
293                     nvpnManager.addSubnetToVpn(vpnId, portIP.getSubnetId());
294                     nvpnNatManager.handleSubnetsForExternalRouter(routerId, dataBroker);
295                     PhysAddress mac = new PhysAddress(routerPort.getMacAddress().getValue());
296                     LOG.trace("NeutronPortChangeListener Add Subnet Gateway IP {} MAC {} Interface {} VPN {}",
297                             ipValue, routerPort.getMacAddress(),
298                             routerPort.getUuid().getValue(), vpnId.getValue());
299                     // ping responder for router interfaces
300                     nvpnManager.createVpnInterface(vpnId, routerId, routerPort, null);
301                 }
302             } else {
303                 LOG.error("Neutron network {} corresponding to router interface port {} for neutron router {} already"
304                     + " associated to VPN {}", infNetworkId.getValue(), routerPort.getUuid().getValue(),
305                     routerId.getValue(), existingVpnId.getValue());
306             }
307         }
308     }
309
310     private void handleRouterInterfaceRemoved(Port routerPort) {
311         if (routerPort.getDeviceId() != null) {
312             Uuid routerId = new Uuid(routerPort.getDeviceId());
313             Uuid infNetworkId = routerPort.getNetworkId();
314
315             elanService.handleKnownL3DmacAddress(routerPort.getMacAddress().getValue(), infNetworkId.getValue(),
316                     NwConstants.DEL_FLOW);
317             for (FixedIps portIP : routerPort.getFixedIps()) {
318                 Uuid vpnId = NeutronvpnUtils.getVpnForRouter(dataBroker, routerId, true);
319                 if (vpnId == null) {
320                     vpnId = routerId;
321                 }
322                 // NOTE:  Please donot change the order of calls to removeSubnetFromVpn and
323                 // and updateSubnetNodeWithFixedIPs
324                 nvpnManager.removeSubnetFromVpn(vpnId, portIP.getSubnetId());
325                 nvpnManager.updateSubnetNodeWithFixedIps(portIP.getSubnetId(), null,
326                         null, null, null);
327                 nvpnNatManager.handleSubnetsForExternalRouter(routerId, dataBroker);
328                 String ipValue = String.valueOf(portIP.getIpAddress().getValue());
329                 NeutronvpnUtils.removeVpnPortFixedIpToPort(dataBroker, vpnId.getValue(),
330                         ipValue, null /*writeTransaction*/);
331                 // ping responder for router interfaces
332                 nvpnManager.deleteVpnInterface(vpnId, routerId, routerPort, null);
333             }
334         }
335     }
336
337     private void handleRouterGatewayUpdated(Port routerGwPort) {
338         Uuid routerId = new Uuid(routerGwPort.getDeviceId());
339         Uuid networkId = routerGwPort.getNetworkId();
340         elanService.handleKnownL3DmacAddress(routerGwPort.getMacAddress().getValue(), networkId.getValue(),
341                 NwConstants.ADD_FLOW);
342
343         Router router = NeutronvpnUtils.getNeutronRouter(dataBroker, routerId);
344         if (router == null) {
345             LOG.warn("No router found for router GW port {} router id {}", routerGwPort.getUuid(), routerId.getValue());
346             return;
347         }
348         gwMacResolver.sendArpRequestsToExtGateways(router);
349     }
350
351     private void handleNeutronPortCreated(final Port port) {
352         final String portName = port.getUuid().getValue();
353         final Uuid portId = port.getUuid();
354         final Uuid subnetId = port.getFixedIps().get(0).getSubnetId();
355         final DataStoreJobCoordinator portDataStoreCoordinator = DataStoreJobCoordinator.getInstance();
356         portDataStoreCoordinator.enqueueJob("PORT- " + portName, () -> {
357             WriteTransaction wrtConfigTxn = dataBroker.newWriteOnlyTransaction();
358             List<ListenableFuture<Void>> futures = new ArrayList<>();
359
360             // add direct port to subnetMaps config DS
361             if (!NeutronUtils.isPortVnicTypeNormal(port)) {
362                 nvpnManager.updateSubnetmapNodeWithPorts(subnetId, null, portId);
363                 LOG.info("Port {} is not a NORMAL VNIC Type port; OF Port interfaces are not created", portName);
364                 futures.add(wrtConfigTxn.submit());
365                 return futures;
366             }
367             LOG.info("Of-port-interface creation for port {}", portName);
368             // Create of-port interface for this neutron port
369             String portInterfaceName = createOfPortInterface(port, wrtConfigTxn);
370             LOG.debug("Creating ELAN Interface for port {}", portName);
371             createElanInterface(port, portInterfaceName, wrtConfigTxn);
372
373             Subnetmap subnetMap = nvpnManager.updateSubnetmapNodeWithPorts(subnetId, portId, null);
374             Uuid vpnId = (subnetMap != null) ? subnetMap.getVpnId() : null;
375             Uuid routerId = (subnetMap != null) ? subnetMap.getRouterId() : null;
376             if (vpnId != null) {
377                 // create vpn-interface on this neutron port
378                 LOG.debug("Adding VPN Interface for port {}", portName);
379                 nvpnManager.createVpnInterface(vpnId, routerId, port, wrtConfigTxn);
380             }
381             futures.add(wrtConfigTxn.submit());
382             return futures;
383         });
384     }
385
386     private void handleNeutronPortDeleted(final Port port) {
387         final String portName = port.getUuid().getValue();
388         final Uuid portId = port.getUuid();
389         final Uuid subnetId = port.getFixedIps().get(0).getSubnetId();
390         final DataStoreJobCoordinator portDataStoreCoordinator = DataStoreJobCoordinator.getInstance();
391         portDataStoreCoordinator.enqueueJob("PORT- " + portName, () -> {
392             WriteTransaction wrtConfigTxn = dataBroker.newWriteOnlyTransaction();
393             List<ListenableFuture<Void>> futures = new ArrayList<>();
394
395             // remove direct port from subnetMaps config DS
396             if (!NeutronUtils.isPortVnicTypeNormal(port)) {
397                 nvpnManager.removePortsFromSubnetmapNode(subnetId, null, portId);
398                 LOG.info("Port {} is not a NORMAL VNIC Type port; OF Port interfaces are not created", portName);
399                 futures.add(wrtConfigTxn.submit());
400                 return futures;
401             }
402             Subnetmap subnetMap = nvpnManager.removePortsFromSubnetmapNode(subnetId, portId, null);
403             Uuid vpnId = (subnetMap != null) ? subnetMap.getVpnId() : null;
404             Uuid routerId = (subnetMap != null) ? subnetMap.getRouterId() : null;
405             if (vpnId != null) {
406                 // remove vpn-interface for this neutron port
407                 LOG.debug("removing VPN Interface for port {}", portName);
408                 nvpnManager.deleteVpnInterface(vpnId, routerId, port, wrtConfigTxn);
409             }
410             // Remove of-port interface for this neutron port
411             // ELAN interface is also implicitly deleted as part of this operation
412             LOG.debug("Of-port-interface removal for port {}", portName);
413             deleteOfPortInterface(port, wrtConfigTxn);
414             //dissociate fixedIP from floatingIP if associated
415             nvpnManager.dissociatefixedIPFromFloatingIP(port.getUuid().getValue());
416             futures.add(wrtConfigTxn.submit());
417             return futures;
418         });
419     }
420
421     private void handleNeutronPortUpdated(final Port portoriginal, final Port portupdate) {
422         if (portoriginal.getFixedIps() == null || portoriginal.getFixedIps().isEmpty()) {
423             handleNeutronPortCreated(portupdate);
424             return;
425         }
426
427         if (portupdate.getFixedIps() == null || portupdate.getFixedIps().isEmpty()) {
428             LOG.debug("Ignoring portUpdate (fixed_ip removal) for port {} as this case is handled "
429                       + "during subnet deletion event.", portupdate.getUuid().getValue());
430             return;
431         }
432
433         final DataStoreJobCoordinator portDataStoreCoordinator = DataStoreJobCoordinator.getInstance();
434         portDataStoreCoordinator.enqueueJob("PORT- " + portupdate.getUuid().getValue(), () -> {
435             WriteTransaction wrtConfigTxn = dataBroker.newWriteOnlyTransaction();
436             Uuid vpnIdNew = null;
437             final Uuid subnetIdOr = portupdate.getFixedIps().get(0).getSubnetId();
438             final Uuid subnetIdUp = portupdate.getFixedIps().get(0).getSubnetId();
439             // check if subnet UUID has changed upon change in fixedIP
440             final Boolean subnetUpdated = subnetIdUp.equals(subnetIdOr) ? false : true;
441
442             if (subnetUpdated) {
443                 Subnetmap subnetMapOld = nvpnManager.removePortsFromSubnetmapNode(subnetIdOr, portoriginal
444                         .getUuid(), null);
445                 Uuid vpnIdOld = (subnetMapOld != null) ? subnetMapOld.getVpnId() : null;
446                 Subnetmap subnetMapNew = nvpnManager.updateSubnetmapNodeWithPorts(subnetIdUp, portupdate
447                                 .getUuid(), null);
448                 vpnIdNew = (subnetMapNew != null) ? subnetMapNew.getVpnId() : null;
449             }
450             if (!subnetUpdated) {
451                 Subnetmap subnetmap = NeutronvpnUtils.getSubnetmap(dataBroker, subnetIdUp);
452                 vpnIdNew = subnetmap != null ? subnetmap.getVpnId() : null;
453             }
454             if (vpnIdNew != null) {
455                 // remove vpn-interface for this neutron port
456                 LOG.debug("removing VPN Interface for port {}", portupdate.getUuid().getValue());
457                 nvpnManager.deleteVpnInterface(vpnIdNew, null, portupdate, wrtConfigTxn);
458                 // create vpn-interface on this neutron port
459                 LOG.debug("Adding VPN Interface for port {}", portupdate.getUuid().getValue());
460                 nvpnManager.createVpnInterface(vpnIdNew, null, portupdate, wrtConfigTxn);
461             }
462             List<ListenableFuture<Void>> futures = new ArrayList<>();
463             futures.add(wrtConfigTxn.submit());
464             return futures;
465         });
466     }
467
468     private static InterfaceAclBuilder handlePortSecurityUpdated(Port portOriginal, Port portUpdated, boolean
469             origSecurityEnabled, boolean updatedSecurityEnabled, InterfaceBuilder interfaceBuilder) {
470         String interfaceName = portUpdated.getUuid().getValue();
471         InterfaceAclBuilder interfaceAclBuilder = null;
472         if (origSecurityEnabled != updatedSecurityEnabled) {
473             interfaceAclBuilder = new InterfaceAclBuilder();
474             interfaceAclBuilder.setPortSecurityEnabled(updatedSecurityEnabled);
475             if (updatedSecurityEnabled) {
476                 // Handle security group enabled
477                 NeutronvpnUtils.populateInterfaceAclBuilder(interfaceAclBuilder, portUpdated);
478             } else {
479                 // Handle security group disabled
480                 interfaceAclBuilder.setSecurityGroups(new ArrayList<>());
481                 interfaceAclBuilder.setAllowedAddressPairs(new ArrayList<>());
482             }
483         } else {
484             if (updatedSecurityEnabled) {
485                 // handle SG add/delete delta
486                 InterfaceAcl interfaceAcl = interfaceBuilder.getAugmentation(InterfaceAcl.class);
487                 interfaceAclBuilder = new InterfaceAclBuilder(interfaceAcl);
488                 interfaceAclBuilder.setSecurityGroups(
489                         NeutronvpnUtils.getUpdatedSecurityGroups(interfaceAcl.getSecurityGroups(),
490                                 portOriginal.getSecurityGroups(), portUpdated.getSecurityGroups()));
491                 List<AllowedAddressPairs> updatedAddressPairs = NeutronvpnUtils.getUpdatedAllowedAddressPairs(
492                         interfaceAcl.getAllowedAddressPairs(), portOriginal.getAllowedAddressPairs(),
493                         portUpdated.getAllowedAddressPairs());
494                 interfaceAclBuilder.setAllowedAddressPairs(NeutronvpnUtils.getAllowedAddressPairsForFixedIps(
495                         updatedAddressPairs, portOriginal.getMacAddress(), portOriginal.getFixedIps(),
496                         portUpdated.getFixedIps()));
497             }
498         }
499         return interfaceAclBuilder;
500     }
501
502     // TODO Clean up the exception handling
503     @SuppressWarnings("checkstyle:IllegalCatch")
504     private String createOfPortInterface(Port port, WriteTransaction wrtConfigTxn) {
505         Interface inf = createInterface(port);
506         String infName = inf.getName();
507
508         LOG.debug("Creating OFPort Interface {}", infName);
509         InstanceIdentifier interfaceIdentifier = NeutronvpnUtils.buildVlanInterfaceIdentifier(infName);
510         try {
511             Optional<Interface> optionalInf = NeutronvpnUtils.read(dataBroker, LogicalDatastoreType.CONFIGURATION,
512                     interfaceIdentifier);
513             if (!optionalInf.isPresent()) {
514                 wrtConfigTxn.put(LogicalDatastoreType.CONFIGURATION, interfaceIdentifier, inf);
515             } else {
516                 LOG.error("Interface {} is already present", infName);
517             }
518         } catch (Exception e) {
519             LOG.error("failed to create interface {} due to the exception {} ", infName, e.getMessage());
520         }
521         return infName;
522     }
523
524     private Interface createInterface(Port port) {
525         String parentRefName = NeutronvpnUtils.getVifPortName(port);
526         String interfaceName = port.getUuid().getValue();
527         IfL2vlan.L2vlanMode l2VlanMode = IfL2vlan.L2vlanMode.Trunk;
528         InterfaceBuilder interfaceBuilder = new InterfaceBuilder();
529         IfL2vlanBuilder ifL2vlanBuilder = new IfL2vlanBuilder();
530
531         Network network = NeutronvpnUtils.getNeutronNetwork(dataBroker, port.getNetworkId());
532         ifL2vlanBuilder.setL2vlanMode(l2VlanMode);
533
534         if (parentRefName != null) {
535             ParentRefsBuilder parentRefsBuilder = new ParentRefsBuilder().setParentInterface(parentRefName);
536             interfaceBuilder.addAugmentation(ParentRefs.class, parentRefsBuilder.build());
537         }
538
539         interfaceBuilder.setEnabled(true).setName(interfaceName).setType(L2vlan.class)
540                 .addAugmentation(IfL2vlan.class, ifL2vlanBuilder.build());
541
542         if (NeutronvpnUtils.getPortSecurityEnabled(port)) {
543             InterfaceAclBuilder interfaceAclBuilder = new InterfaceAclBuilder();
544             interfaceAclBuilder.setPortSecurityEnabled(true);
545             NeutronvpnUtils.populateInterfaceAclBuilder(interfaceAclBuilder, port);
546             interfaceBuilder.addAugmentation(InterfaceAcl.class, interfaceAclBuilder.build());
547         }
548         return interfaceBuilder.build();
549     }
550
551     // TODO Clean up the exception handling
552     @SuppressWarnings("checkstyle:IllegalCatch")
553     private void deleteOfPortInterface(Port port, WriteTransaction wrtConfigTxn) {
554         String name = port.getUuid().getValue();
555         LOG.debug("Removing OFPort Interface {}", name);
556         InstanceIdentifier interfaceIdentifier = NeutronvpnUtils.buildVlanInterfaceIdentifier(name);
557         try {
558             Optional<Interface> optionalInf = NeutronvpnUtils.read(dataBroker, LogicalDatastoreType.CONFIGURATION,
559                     interfaceIdentifier);
560             if (optionalInf.isPresent()) {
561                 wrtConfigTxn.delete(LogicalDatastoreType.CONFIGURATION, interfaceIdentifier);
562             } else {
563                 LOG.error("Interface {} is not present", name);
564             }
565         } catch (Exception e) {
566             LOG.error("Failed to delete interface {} due to the exception {}", name, e.getMessage());
567         }
568     }
569
570     private ParentRefsBuilder getParentRefsBuilder(Port update) {
571         String parentRefName = NeutronvpnUtils.getVifPortName(update);
572         if (parentRefName != null) {
573             return new ParentRefsBuilder().setParentInterface(parentRefName);
574         }
575         return null;
576     }
577
578     private void createElanInterface(Port port, String name, WriteTransaction wrtConfigTxn) {
579         String elanInstanceName = port.getNetworkId().getValue();
580         List<PhysAddress> physAddresses = new ArrayList<>();
581         physAddresses.add(new PhysAddress(port.getMacAddress().getValue()));
582
583         InstanceIdentifier<ElanInterface> id = InstanceIdentifier.builder(ElanInterfaces.class).child(ElanInterface
584                 .class, new ElanInterfaceKey(name)).build();
585         ElanInterface elanInterface = new ElanInterfaceBuilder().setElanInstanceName(elanInstanceName)
586                 .setName(name).setStaticMacEntries(physAddresses).setKey(new ElanInterfaceKey(name)).build();
587         wrtConfigTxn.put(LogicalDatastoreType.CONFIGURATION, id, elanInterface);
588         LOG.debug("Creating new ELan Interface {}", elanInterface);
589     }
590
591     // TODO Clean up the exception handling
592     @SuppressWarnings("checkstyle:IllegalCatch")
593     private void addToFloatingIpPortInfo(Uuid floatingIpId, Uuid floatingIpPortId, Uuid floatingIpPortSubnetId, String
594                                          floatingIpPortMacAddress) {
595         InstanceIdentifier id = buildfloatingIpIdToPortMappingIdentifier(floatingIpId);
596         try {
597             FloatingIpIdToPortMappingBuilder floatingipIdToPortMacMappingBuilder = new
598                 FloatingIpIdToPortMappingBuilder().setKey(new FloatingIpIdToPortMappingKey(floatingIpId))
599                 .setFloatingIpId(floatingIpId).setFloatingIpPortId(floatingIpPortId)
600                 .setFloatingIpPortSubnetId(floatingIpPortSubnetId)
601                 .setFloatingIpPortMacAddress(floatingIpPortMacAddress);
602             LOG.debug("Creating floating IP UUID {} to Floating IP neutron port {} mapping in Floating IP"
603                 + " Port Info Config DS", floatingIpId.getValue(), floatingIpPortId.getValue());
604             MDSALUtil.syncWrite(dataBroker, LogicalDatastoreType.CONFIGURATION, id,
605                 floatingipIdToPortMacMappingBuilder.build());
606         } catch (Exception e) {
607             LOG.error("Creating floating IP UUID {} to Floating IP neutron port {} mapping in Floating IP"
608                 + " Port Info Config DS failed with exception {}",
609                 floatingIpId.getValue(), floatingIpPortId.getValue(), e);
610         }
611     }
612 }