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