934286b820ca5db72a04261cdcf0fcb1e9ae93d3
[netvirt.git] /
1 /*
2  * Copyright (c) 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
15 import java.util.ArrayList;
16 import java.util.List;
17
18 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
19 import org.opendaylight.controller.md.sal.binding.api.NotificationPublishService;
20 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
21 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
22 import org.opendaylight.genius.datastoreutils.AsyncDataTreeChangeListenerBase;
23 import org.opendaylight.genius.datastoreutils.DataStoreJobCoordinator;
24 import org.opendaylight.genius.mdsalutil.MDSALUtil;
25 import org.opendaylight.genius.mdsalutil.NwConstants;
26 import org.opendaylight.netvirt.elanmanager.api.IElanService;
27 import org.opendaylight.netvirt.neutronvpn.api.utils.NeutronConstants;
28 import org.opendaylight.netvirt.neutronvpn.api.utils.NeutronUtils;
29 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.iana._if.type.rev140508.L2vlan;
30 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.Interface;
31 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.InterfaceBuilder;
32 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.PhysAddress;
33 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.IfL2vlan;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.IfL2vlanBuilder;
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 port security enabled/disabled as part of port update
193         boolean origSecurityEnabled = NeutronvpnUtils.getPortSecurityEnabled(original);
194         boolean updatedSecurityEnabled = NeutronvpnUtils.getPortSecurityEnabled(update);
195
196         if (origSecurityEnabled || updatedSecurityEnabled) {
197             InstanceIdentifier interfaceIdentifier = NeutronvpnUtils.buildVlanInterfaceIdentifier(portName);
198             final DataStoreJobCoordinator portDataStoreCoordinator = DataStoreJobCoordinator.getInstance();
199             portDataStoreCoordinator.enqueueJob("PORT- " + portName, () -> {
200                 WriteTransaction wrtConfigTxn = dataBroker.newWriteOnlyTransaction();
201                 try {
202                     Optional<Interface> optionalInf = NeutronvpnUtils.read(dataBroker, LogicalDatastoreType
203                             .CONFIGURATION, interfaceIdentifier);
204                     if (optionalInf.isPresent()) {
205                         InterfaceBuilder interfaceBuilder = new InterfaceBuilder(optionalInf.get());
206                         if (origSecurityEnabled || updatedSecurityEnabled) {
207                             InterfaceAcl infAcl = handlePortSecurityUpdated(original, update,
208                                     origSecurityEnabled, updatedSecurityEnabled, interfaceBuilder).build();
209                             interfaceBuilder.addAugmentation(InterfaceAcl.class, infAcl);
210                         }
211                         LOG.info("Of-port-interface updation for port {}", portName);
212                         // Update OFPort interface for this neutron port
213                         wrtConfigTxn.put(LogicalDatastoreType.CONFIGURATION, interfaceIdentifier,
214                                 interfaceBuilder.build());
215                     } else {
216                         LOG.error("Interface {} is not present", portName);
217                     }
218                 } catch (Exception e) {
219                     LOG.error("Failed to update interface {} due to the exception {}", portName, e);
220                 }
221                 List<ListenableFuture<Void>> futures = new ArrayList<>();
222                 futures.add(wrtConfigTxn.submit());
223                 return futures;
224             });
225         }
226         List<FixedIps> oldIPs = (original.getFixedIps() != null) ? original.getFixedIps() : new ArrayList<>();
227         List<FixedIps> newIPs = (update.getFixedIps() != null) ? update.getFixedIps() : new ArrayList<>();
228         if (!oldIPs.equals(newIPs)) {
229             newIPs.removeIf(oldIPs::remove);
230             handleNeutronPortUpdated(original, update);
231         }
232         if (NeutronConstants.DEVICE_OWNER_GATEWAY_INF.equals(update.getDeviceOwner())) {
233             handleRouterGatewayUpdated(update);
234         } else if (NeutronConstants.DEVICE_OWNER_FLOATING_IP.equals(update.getDeviceOwner())) {
235             elanService.handleKnownL3DmacAddress(update.getMacAddress().getValue(), update.getNetworkId().getValue(),
236                     NwConstants.ADD_FLOW);
237         }
238         // check for QoS updates
239         QosPortExtension updateQos = update.getAugmentation(QosPortExtension.class);
240         QosPortExtension originalQos = original.getAugmentation(QosPortExtension.class);
241         if (originalQos == null && updateQos != null) {
242             // qos policy add
243             NeutronvpnUtils.addToQosPortsCache(updateQos.getQosPolicyId(), update);
244             NeutronQosUtils.handleNeutronPortQosUpdate(dataBroker, odlInterfaceRpcService,
245                     update, updateQos.getQosPolicyId());
246         } else if (originalQos != null && updateQos != null
247                 && !originalQos.getQosPolicyId().equals(updateQos.getQosPolicyId())) {
248             // qos policy update
249             NeutronvpnUtils.removeFromQosPortsCache(originalQos.getQosPolicyId(), original);
250             NeutronvpnUtils.addToQosPortsCache(updateQos.getQosPolicyId(), update);
251             NeutronQosUtils.handleNeutronPortQosUpdate(dataBroker, odlInterfaceRpcService,
252                     update, updateQos.getQosPolicyId());
253         } else if (originalQos != null && updateQos == null) {
254             // qos policy delete
255             NeutronQosUtils.handleNeutronPortQosRemove(dataBroker, odlInterfaceRpcService,
256                     original, originalQos.getQosPolicyId());
257             NeutronvpnUtils.removeFromQosPortsCache(originalQos.getQosPolicyId(), original);
258         }
259     }
260
261     private void handleRouterInterfaceAdded(Port routerPort) {
262         if (routerPort.getDeviceId() != null) {
263             Uuid routerId = new Uuid(routerPort.getDeviceId());
264             Uuid infNetworkId = routerPort.getNetworkId();
265             Uuid existingVpnId = NeutronvpnUtils.getVpnForNetwork(dataBroker, infNetworkId);
266
267             elanService.handleKnownL3DmacAddress(routerPort.getMacAddress().getValue(), infNetworkId.getValue(),
268                     NwConstants.ADD_FLOW);
269             if (existingVpnId == null) {
270                 for (FixedIps portIP : routerPort.getFixedIps()) {
271                     Uuid vpnId = NeutronvpnUtils.getVpnForRouter(dataBroker, routerId, true);
272                     if (vpnId == null) {
273                         vpnId = routerId;
274                     }
275                     // NOTE:  Please donot change the order of calls to updateSubnetNodeWithFixedIPs
276                     // and addSubnetToVpn here
277                     String ipValue = String.valueOf(portIP.getIpAddress().getValue());
278                     nvpnManager.updateSubnetNodeWithFixedIps(portIP.getSubnetId(), routerId,
279                             routerPort.getUuid(), ipValue, routerPort.getMacAddress().getValue());
280                     nvpnManager.addSubnetToVpn(vpnId, portIP.getSubnetId());
281                     nvpnNatManager.handleSubnetsForExternalRouter(routerId, dataBroker);
282                     PhysAddress mac = new PhysAddress(routerPort.getMacAddress().getValue());
283                     LOG.trace("NeutronPortChangeListener Add Subnet Gateway IP {} MAC {} Interface {} VPN {}",
284                             ipValue, routerPort.getMacAddress(),
285                             routerPort.getUuid().getValue(), vpnId.getValue());
286                     // ping responder for router interfaces
287                     nvpnManager.createVpnInterface(vpnId, routerId, routerPort, null);
288                 }
289             } else {
290                 LOG.error("Neutron network {} corresponding to router interface port {} for neutron router {} already"
291                     + " associated to VPN {}", infNetworkId.getValue(), routerPort.getUuid().getValue(),
292                     routerId.getValue(), existingVpnId.getValue());
293             }
294         }
295     }
296
297     private void handleRouterInterfaceRemoved(Port routerPort) {
298         if (routerPort.getDeviceId() != null) {
299             Uuid routerId = new Uuid(routerPort.getDeviceId());
300             Uuid infNetworkId = routerPort.getNetworkId();
301
302             elanService.handleKnownL3DmacAddress(routerPort.getMacAddress().getValue(), infNetworkId.getValue(),
303                     NwConstants.DEL_FLOW);
304             for (FixedIps portIP : routerPort.getFixedIps()) {
305                 Uuid vpnId = NeutronvpnUtils.getVpnForRouter(dataBroker, routerId, true);
306                 if (vpnId == null) {
307                     vpnId = routerId;
308                 }
309                 // NOTE:  Please donot change the order of calls to removeSubnetFromVpn and
310                 // and updateSubnetNodeWithFixedIPs
311                 nvpnManager.removeSubnetFromVpn(vpnId, portIP.getSubnetId());
312                 nvpnManager.updateSubnetNodeWithFixedIps(portIP.getSubnetId(), null,
313                         null, null, null);
314                 nvpnNatManager.handleSubnetsForExternalRouter(routerId, dataBroker);
315                 String ipValue = String.valueOf(portIP.getIpAddress().getValue());
316                 NeutronvpnUtils.removeVpnPortFixedIpToPort(dataBroker, vpnId.getValue(),
317                         ipValue, null /*writeTransaction*/);
318                 // ping responder for router interfaces
319                 nvpnManager.deleteVpnInterface(vpnId, routerId, routerPort, null);
320             }
321         }
322     }
323
324     private void handleRouterGatewayUpdated(Port routerGwPort) {
325         Uuid routerId = new Uuid(routerGwPort.getDeviceId());
326         Uuid networkId = routerGwPort.getNetworkId();
327         elanService.handleKnownL3DmacAddress(routerGwPort.getMacAddress().getValue(), networkId.getValue(),
328                 NwConstants.ADD_FLOW);
329
330         Router router = NeutronvpnUtils.getNeutronRouter(dataBroker, routerId);
331         if (router == null) {
332             LOG.warn("No router found for router GW port {} router id {}", routerGwPort.getUuid(), routerId.getValue());
333             return;
334         }
335         gwMacResolver.sendArpRequestsToExtGateways(router);
336     }
337
338     private void handleNeutronPortCreated(final Port port) {
339         final String portName = port.getUuid().getValue();
340         final Uuid portId = port.getUuid();
341         final Uuid subnetId = port.getFixedIps().get(0).getSubnetId();
342         final DataStoreJobCoordinator portDataStoreCoordinator = DataStoreJobCoordinator.getInstance();
343         portDataStoreCoordinator.enqueueJob("PORT- " + portName, () -> {
344             WriteTransaction wrtConfigTxn = dataBroker.newWriteOnlyTransaction();
345             List<ListenableFuture<Void>> futures = new ArrayList<>();
346
347             // add direct port to subnetMaps config DS
348             if (!NeutronUtils.isPortVnicTypeNormal(port)) {
349                 nvpnManager.updateSubnetmapNodeWithPorts(subnetId, null, portId);
350                 LOG.info("Port {} is not a NORMAL VNIC Type port; OF Port interfaces are not created", portName);
351                 futures.add(wrtConfigTxn.submit());
352                 return futures;
353             }
354             LOG.info("Of-port-interface creation for port {}", portName);
355             // Create of-port interface for this neutron port
356             String portInterfaceName = createOfPortInterface(port, wrtConfigTxn);
357             LOG.debug("Creating ELAN Interface for port {}", portName);
358             createElanInterface(port, portInterfaceName, wrtConfigTxn);
359
360             Subnetmap subnetMap = nvpnManager.updateSubnetmapNodeWithPorts(subnetId, portId, null);
361             Uuid vpnId = (subnetMap != null) ? subnetMap.getVpnId() : null;
362             Uuid routerId = (subnetMap != null) ? subnetMap.getRouterId() : null;
363             if (vpnId != null) {
364                 // create vpn-interface on this neutron port
365                 LOG.debug("Adding VPN Interface for port {}", portName);
366                 nvpnManager.createVpnInterface(vpnId, routerId, port, wrtConfigTxn);
367             }
368             futures.add(wrtConfigTxn.submit());
369             return futures;
370         });
371     }
372
373     private void handleNeutronPortDeleted(final Port port) {
374         final String portName = port.getUuid().getValue();
375         final Uuid portId = port.getUuid();
376         final Uuid subnetId = port.getFixedIps().get(0).getSubnetId();
377         final DataStoreJobCoordinator portDataStoreCoordinator = DataStoreJobCoordinator.getInstance();
378         portDataStoreCoordinator.enqueueJob("PORT- " + portName, () -> {
379             WriteTransaction wrtConfigTxn = dataBroker.newWriteOnlyTransaction();
380             List<ListenableFuture<Void>> futures = new ArrayList<>();
381
382             // remove direct port from subnetMaps config DS
383             if (!NeutronUtils.isPortVnicTypeNormal(port)) {
384                 nvpnManager.removePortsFromSubnetmapNode(subnetId, null, portId);
385                 LOG.info("Port {} is not a NORMAL VNIC Type port; OF Port interfaces are not created", portName);
386                 futures.add(wrtConfigTxn.submit());
387                 return futures;
388             }
389             Subnetmap subnetMap = nvpnManager.removePortsFromSubnetmapNode(subnetId, portId, null);
390             Uuid vpnId = (subnetMap != null) ? subnetMap.getVpnId() : null;
391             Uuid routerId = (subnetMap != null) ? subnetMap.getRouterId() : null;
392             if (vpnId != null) {
393                 // remove vpn-interface for this neutron port
394                 LOG.debug("removing VPN Interface for port {}", portName);
395                 nvpnManager.deleteVpnInterface(vpnId, routerId, port, wrtConfigTxn);
396             }
397             // Remove of-port interface for this neutron port
398             // ELAN interface is also implicitly deleted as part of this operation
399             LOG.debug("Of-port-interface removal for port {}", portName);
400             deleteOfPortInterface(port, wrtConfigTxn);
401             //dissociate fixedIP from floatingIP if associated
402             nvpnManager.dissociatefixedIPFromFloatingIP(port.getUuid().getValue());
403             futures.add(wrtConfigTxn.submit());
404             return futures;
405         });
406     }
407
408     private void handleNeutronPortUpdated(final Port portoriginal, final Port portupdate) {
409         if (portoriginal.getFixedIps() == null || portoriginal.getFixedIps().isEmpty()) {
410             handleNeutronPortCreated(portupdate);
411             return;
412         }
413
414         if (portupdate.getFixedIps() == null || portupdate.getFixedIps().isEmpty()) {
415             LOG.debug("Ignoring portUpdate (fixed_ip removal) for port {} as this case is handled "
416                       + "during subnet deletion event.", portupdate.getUuid().getValue());
417             return;
418         }
419
420         final DataStoreJobCoordinator portDataStoreCoordinator = DataStoreJobCoordinator.getInstance();
421         portDataStoreCoordinator.enqueueJob("PORT- " + portupdate.getUuid().getValue(), () -> {
422             WriteTransaction wrtConfigTxn = dataBroker.newWriteOnlyTransaction();
423             Uuid vpnIdNew = null;
424             final Uuid subnetIdOr = portupdate.getFixedIps().get(0).getSubnetId();
425             final Uuid subnetIdUp = portupdate.getFixedIps().get(0).getSubnetId();
426             // check if subnet UUID has changed upon change in fixedIP
427             final Boolean subnetUpdated = subnetIdUp.equals(subnetIdOr) ? false : true;
428
429             if (subnetUpdated) {
430                 Subnetmap subnetMapOld = nvpnManager.removePortsFromSubnetmapNode(subnetIdOr, portoriginal
431                         .getUuid(), null);
432                 Uuid vpnIdOld = (subnetMapOld != null) ? subnetMapOld.getVpnId() : null;
433                 Subnetmap subnetMapNew = nvpnManager.updateSubnetmapNodeWithPorts(subnetIdUp, portupdate
434                                 .getUuid(), null);
435                 vpnIdNew = (subnetMapNew != null) ? subnetMapNew.getVpnId() : null;
436             }
437             if (!subnetUpdated) {
438                 Subnetmap subnetmap = NeutronvpnUtils.getSubnetmap(dataBroker, subnetIdUp);
439                 vpnIdNew = subnetmap != null ? subnetmap.getVpnId() : null;
440             }
441             if (vpnIdNew != null) {
442                 // remove vpn-interface for this neutron port
443                 LOG.debug("removing VPN Interface for port {}", portupdate.getUuid().getValue());
444                 nvpnManager.deleteVpnInterface(vpnIdNew, null, portupdate, wrtConfigTxn);
445                 // create vpn-interface on this neutron port
446                 LOG.debug("Adding VPN Interface for port {}", portupdate.getUuid().getValue());
447                 nvpnManager.createVpnInterface(vpnIdNew, null, portupdate, wrtConfigTxn);
448             }
449             List<ListenableFuture<Void>> futures = new ArrayList<>();
450             futures.add(wrtConfigTxn.submit());
451             return futures;
452         });
453     }
454
455     private static InterfaceAclBuilder handlePortSecurityUpdated(Port portOriginal, Port portUpdated, boolean
456             origSecurityEnabled, boolean updatedSecurityEnabled, InterfaceBuilder interfaceBuilder) {
457         String interfaceName = portUpdated.getUuid().getValue();
458         InterfaceAclBuilder interfaceAclBuilder = null;
459         if (origSecurityEnabled != updatedSecurityEnabled) {
460             interfaceAclBuilder = new InterfaceAclBuilder();
461             interfaceAclBuilder.setPortSecurityEnabled(updatedSecurityEnabled);
462             if (updatedSecurityEnabled) {
463                 // Handle security group enabled
464                 NeutronvpnUtils.populateInterfaceAclBuilder(interfaceAclBuilder, portUpdated);
465             } else {
466                 // Handle security group disabled
467                 interfaceAclBuilder.setSecurityGroups(new ArrayList<>());
468                 interfaceAclBuilder.setAllowedAddressPairs(new ArrayList<>());
469             }
470         } else {
471             if (updatedSecurityEnabled) {
472                 // handle SG add/delete delta
473                 InterfaceAcl interfaceAcl = interfaceBuilder.getAugmentation(InterfaceAcl.class);
474                 interfaceAclBuilder = new InterfaceAclBuilder(interfaceAcl);
475                 interfaceAclBuilder.setSecurityGroups(
476                         NeutronvpnUtils.getUpdatedSecurityGroups(interfaceAcl.getSecurityGroups(),
477                                 portOriginal.getSecurityGroups(), portUpdated.getSecurityGroups()));
478                 List<AllowedAddressPairs> updatedAddressPairs = NeutronvpnUtils.getUpdatedAllowedAddressPairs(
479                         interfaceAcl.getAllowedAddressPairs(), portOriginal.getAllowedAddressPairs(),
480                         portUpdated.getAllowedAddressPairs());
481                 interfaceAclBuilder.setAllowedAddressPairs(NeutronvpnUtils.getAllowedAddressPairsForFixedIps(
482                         updatedAddressPairs, portOriginal.getMacAddress(), portOriginal.getFixedIps(),
483                         portUpdated.getFixedIps()));
484             }
485         }
486         return interfaceAclBuilder;
487     }
488
489     // TODO Clean up the exception handling
490     @SuppressWarnings("checkstyle:IllegalCatch")
491     private String createOfPortInterface(Port port, WriteTransaction wrtConfigTxn) {
492         Interface inf = createInterface(port);
493         String infName = inf.getName();
494
495         LOG.debug("Creating OFPort Interface {}", infName);
496         InstanceIdentifier interfaceIdentifier = NeutronvpnUtils.buildVlanInterfaceIdentifier(infName);
497         try {
498             Optional<Interface> optionalInf = NeutronvpnUtils.read(dataBroker, LogicalDatastoreType.CONFIGURATION,
499                     interfaceIdentifier);
500             if (!optionalInf.isPresent()) {
501                 wrtConfigTxn.put(LogicalDatastoreType.CONFIGURATION, interfaceIdentifier, inf);
502             } else {
503                 LOG.warn("Interface {} is already present", infName);
504             }
505         } catch (Exception e) {
506             LOG.error("failed to create interface {} due to the exception {} ", infName, e.getMessage());
507         }
508         return infName;
509     }
510
511     private Interface createInterface(Port port) {
512         String interfaceName = port.getUuid().getValue();
513         IfL2vlan.L2vlanMode l2VlanMode = IfL2vlan.L2vlanMode.Trunk;
514         InterfaceBuilder interfaceBuilder = new InterfaceBuilder();
515         IfL2vlanBuilder ifL2vlanBuilder = new IfL2vlanBuilder();
516         ifL2vlanBuilder.setL2vlanMode(l2VlanMode);
517
518         interfaceBuilder.setEnabled(true).setName(interfaceName).setType(L2vlan.class)
519                 .addAugmentation(IfL2vlan.class, ifL2vlanBuilder.build());
520
521         if (NeutronvpnUtils.getPortSecurityEnabled(port)) {
522             InterfaceAclBuilder interfaceAclBuilder = new InterfaceAclBuilder();
523             interfaceAclBuilder.setPortSecurityEnabled(true);
524             NeutronvpnUtils.populateInterfaceAclBuilder(interfaceAclBuilder, port);
525             interfaceBuilder.addAugmentation(InterfaceAcl.class, interfaceAclBuilder.build());
526         }
527         return interfaceBuilder.build();
528     }
529
530     // TODO Clean up the exception handling
531     @SuppressWarnings("checkstyle:IllegalCatch")
532     private void deleteOfPortInterface(Port port, WriteTransaction wrtConfigTxn) {
533         String name = port.getUuid().getValue();
534         LOG.debug("Removing OFPort Interface {}", name);
535         InstanceIdentifier interfaceIdentifier = NeutronvpnUtils.buildVlanInterfaceIdentifier(name);
536         try {
537             Optional<Interface> optionalInf = NeutronvpnUtils.read(dataBroker, LogicalDatastoreType.CONFIGURATION,
538                     interfaceIdentifier);
539             if (optionalInf.isPresent()) {
540                 wrtConfigTxn.delete(LogicalDatastoreType.CONFIGURATION, interfaceIdentifier);
541             } else {
542                 LOG.error("Interface {} is not present", name);
543             }
544         } catch (Exception e) {
545             LOG.error("Failed to delete interface {} due to the exception {}", name, e.getMessage());
546         }
547     }
548
549     private void createElanInterface(Port port, String name, WriteTransaction wrtConfigTxn) {
550         String elanInstanceName = port.getNetworkId().getValue();
551         List<PhysAddress> physAddresses = new ArrayList<>();
552         physAddresses.add(new PhysAddress(port.getMacAddress().getValue()));
553
554         InstanceIdentifier<ElanInterface> id = InstanceIdentifier.builder(ElanInterfaces.class).child(ElanInterface
555                 .class, new ElanInterfaceKey(name)).build();
556         ElanInterface elanInterface = new ElanInterfaceBuilder().setElanInstanceName(elanInstanceName)
557                 .setName(name).setStaticMacEntries(physAddresses).setKey(new ElanInterfaceKey(name)).build();
558         wrtConfigTxn.put(LogicalDatastoreType.CONFIGURATION, id, elanInterface);
559         LOG.debug("Creating new ELan Interface {}", elanInterface);
560     }
561
562     // TODO Clean up the exception handling
563     @SuppressWarnings("checkstyle:IllegalCatch")
564     private void addToFloatingIpPortInfo(Uuid floatingIpId, Uuid floatingIpPortId, Uuid floatingIpPortSubnetId, String
565                                          floatingIpPortMacAddress) {
566         InstanceIdentifier id = buildfloatingIpIdToPortMappingIdentifier(floatingIpId);
567         try {
568             FloatingIpIdToPortMappingBuilder floatingipIdToPortMacMappingBuilder = new
569                 FloatingIpIdToPortMappingBuilder().setKey(new FloatingIpIdToPortMappingKey(floatingIpId))
570                 .setFloatingIpId(floatingIpId).setFloatingIpPortId(floatingIpPortId)
571                 .setFloatingIpPortSubnetId(floatingIpPortSubnetId)
572                 .setFloatingIpPortMacAddress(floatingIpPortMacAddress);
573             LOG.debug("Creating floating IP UUID {} to Floating IP neutron port {} mapping in Floating IP"
574                 + " Port Info Config DS", floatingIpId.getValue(), floatingIpPortId.getValue());
575             MDSALUtil.syncWrite(dataBroker, LogicalDatastoreType.CONFIGURATION, id,
576                 floatingipIdToPortMacMappingBuilder.build());
577         } catch (Exception e) {
578             LOG.error("Creating floating IP UUID {} to Floating IP neutron port {} mapping in Floating IP"
579                 + " Port Info Config DS failed with exception {}",
580                 floatingIpId.getValue(), floatingIpPortId.getValue(), e);
581         }
582     }
583 }