Bug 9022: ACL: Broadcast traffic is dropped in ACL tables
[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(dataBroker, 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(DataBroker dataBroker, Port portOriginal,
468             Port portUpdated, boolean origSecurityEnabled, boolean updatedSecurityEnabled,
469             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.warn("Interface {} is already present", infName);
517             }
518         } catch (Exception e) {
519             LOG.error("failed to create interface {}", infName, e);
520         }
521         return infName;
522     }
523
524     private Interface createInterface(Port port) {
525         String interfaceName = port.getUuid().getValue();
526         IfL2vlan.L2vlanMode l2VlanMode = IfL2vlan.L2vlanMode.Trunk;
527         InterfaceBuilder interfaceBuilder = new InterfaceBuilder();
528         IfL2vlanBuilder ifL2vlanBuilder = new IfL2vlanBuilder();
529         ifL2vlanBuilder.setL2vlanMode(l2VlanMode);
530
531         interfaceBuilder.setEnabled(true).setName(interfaceName).setType(L2vlan.class)
532                 .addAugmentation(IfL2vlan.class, ifL2vlanBuilder.build());
533
534         if (NeutronvpnUtils.getPortSecurityEnabled(port)) {
535             InterfaceAclBuilder interfaceAclBuilder = new InterfaceAclBuilder();
536             interfaceAclBuilder.setPortSecurityEnabled(true);
537             NeutronvpnUtils.populateInterfaceAclBuilder(interfaceAclBuilder, port);
538             interfaceBuilder.addAugmentation(InterfaceAcl.class, interfaceAclBuilder.build());
539             NeutronvpnUtils.populateSubnetIpPrefixes(dataBroker, port);
540         }
541         return interfaceBuilder.build();
542     }
543
544     // TODO Clean up the exception handling
545     @SuppressWarnings("checkstyle:IllegalCatch")
546     private void deleteOfPortInterface(Port port, WriteTransaction wrtConfigTxn) {
547         String name = port.getUuid().getValue();
548         LOG.debug("Removing OFPort Interface {}", name);
549         InstanceIdentifier interfaceIdentifier = NeutronvpnUtils.buildVlanInterfaceIdentifier(name);
550         try {
551             Optional<Interface> optionalInf = NeutronvpnUtils.read(dataBroker, LogicalDatastoreType.CONFIGURATION,
552                     interfaceIdentifier);
553             if (optionalInf.isPresent()) {
554                 wrtConfigTxn.delete(LogicalDatastoreType.CONFIGURATION, interfaceIdentifier);
555             } else {
556                 LOG.error("Interface {} is not present", name);
557             }
558         } catch (Exception e) {
559             LOG.error("Failed to delete interface {}", name, e);
560         }
561     }
562
563     private void createElanInterface(Port port, String name, WriteTransaction wrtConfigTxn) {
564         String elanInstanceName = port.getNetworkId().getValue();
565         List<StaticMacEntries> staticMacEntries = NeutronvpnUtils.buildStaticMacEntry(port);
566
567         InstanceIdentifier<ElanInterface> id = InstanceIdentifier.builder(ElanInterfaces.class).child(ElanInterface
568                 .class, new ElanInterfaceKey(name)).build();
569         ElanInterface elanInterface = new ElanInterfaceBuilder().setElanInstanceName(elanInstanceName)
570                 .setName(name).setStaticMacEntries(staticMacEntries).setKey(new ElanInterfaceKey(name)).build();
571         wrtConfigTxn.put(LogicalDatastoreType.CONFIGURATION, id, elanInterface);
572         LOG.debug("Creating new ELan Interface {}", elanInterface);
573     }
574
575     private void deleteElanInterface(String name, WriteTransaction wrtConfigTxn) {
576         InstanceIdentifier<ElanInterface> id = InstanceIdentifier.builder(ElanInterfaces.class).child(ElanInterface
577                 .class, new ElanInterfaceKey(name)).build();
578         wrtConfigTxn.delete(LogicalDatastoreType.CONFIGURATION, id);
579     }
580
581     // TODO Clean up the exception handling
582     @SuppressWarnings("checkstyle:IllegalCatch")
583     private void addToFloatingIpPortInfo(Uuid floatingIpId, Uuid floatingIpPortId, Uuid floatingIpPortSubnetId, String
584                                          floatingIpPortMacAddress) {
585         InstanceIdentifier id = buildfloatingIpIdToPortMappingIdentifier(floatingIpId);
586         try {
587             FloatingIpIdToPortMappingBuilder floatingipIdToPortMacMappingBuilder = new
588                 FloatingIpIdToPortMappingBuilder().setKey(new FloatingIpIdToPortMappingKey(floatingIpId))
589                 .setFloatingIpId(floatingIpId).setFloatingIpPortId(floatingIpPortId)
590                 .setFloatingIpPortSubnetId(floatingIpPortSubnetId)
591                 .setFloatingIpPortMacAddress(floatingIpPortMacAddress);
592             LOG.debug("Creating floating IP UUID {} to Floating IP neutron port {} mapping in Floating IP"
593                 + " Port Info Config DS", floatingIpId.getValue(), floatingIpPortId.getValue());
594             MDSALUtil.syncWrite(dataBroker, LogicalDatastoreType.CONFIGURATION, id,
595                 floatingipIdToPortMacMappingBuilder.build());
596         } catch (Exception e) {
597             LOG.error("Creating floating IP UUID {} to Floating IP neutron port {} mapping in Floating IP"
598                 + " Port Info Config DS failed", floatingIpId.getValue(), floatingIpPortId.getValue(), e);
599         }
600     }
601
602     private Set<FixedIps> getFixedIpSet(List<FixedIps> fixedIps) {
603         return fixedIps != null ? new HashSet<>(fixedIps) : Collections.emptySet();
604     }
605 }