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