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