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