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