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