Bug9016:Using Single Transaction during NAPT SwitchOver
[netvirt.git] / vpnservice / natservice / natservice-impl / src / main / java / org / opendaylight / netvirt / natservice / internal / ExternalNetworksChangeListener.java
index 23b01c236b0cebedc0bb254b045effc2391f3b85..bd5f5b37084fd07e571efa11096cc2e851a87805 100644 (file)
@@ -8,10 +8,17 @@
 package org.opendaylight.netvirt.natservice.internal;
 
 import com.google.common.base.Optional;
+import com.google.common.util.concurrent.ListenableFuture;
 import java.math.BigInteger;
+import java.util.ArrayList;
+import java.util.Collection;
 import java.util.List;
+import javax.annotation.PostConstruct;
+import javax.inject.Inject;
+import javax.inject.Singleton;
+
 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.api.DataChangeListener;
+import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
 import org.opendaylight.genius.datastoreutils.AsyncDataTreeChangeListenerBase;
 import org.opendaylight.genius.mdsalutil.MDSALUtil;
@@ -21,6 +28,8 @@ import org.opendaylight.netvirt.bgpmanager.api.IBgpManager;
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.OdlInterfaceRpcService;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.fib.rpc.rev160121.FibRpcService;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.config.rev170206.NatserviceConfig;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.config.rev170206.NatserviceConfig.NatMode;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.ExternalNetworks;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.IntextIpMap;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.NaptSwitches;
@@ -32,16 +41,15 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev16011
 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.napt.switches.RouterToNaptSwitch;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.napt.switches.RouterToNaptSwitchKey;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.vpn.rpc.rev160201.VpnRpcService;
-import org.opendaylight.yangtools.concepts.ListenerRegistration;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.InstanceIdentifierBuilder;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+@Singleton
 public class ExternalNetworksChangeListener
         extends AsyncDataTreeChangeListenerBase<Networks, ExternalNetworksChangeListener> {
     private static final Logger LOG = LoggerFactory.getLogger(ExternalNetworksChangeListener.class);
-    private ListenerRegistration<DataChangeListener> listenerRegistration;
     private final DataBroker dataBroker;
     private final IMdsalApiManager mdsalManager;
     private final FloatingIPListener floatingIpListener;
@@ -51,7 +59,9 @@ public class ExternalNetworksChangeListener
     private final IBgpManager bgpManager;
     private final VpnRpcService vpnService;
     private final FibRpcService fibService;
+    private NatMode natMode = NatMode.Controller;
 
+    @Inject
     public ExternalNetworksChangeListener(final DataBroker dataBroker, final IMdsalApiManager mdsalManager,
                                           final FloatingIPListener floatingIpListener,
                                           final ExternalRoutersListener externalRouterListener,
@@ -59,7 +69,8 @@ public class ExternalNetworksChangeListener
                                           final NaptManager naptManager,
                                           final IBgpManager bgpManager,
                                           final VpnRpcService vpnService,
-                                          final FibRpcService fibService) {
+                                          final FibRpcService fibService,
+                                          final NatserviceConfig config) {
         super(Networks.class, ExternalNetworksChangeListener.class);
         this.dataBroker = dataBroker;
         this.mdsalManager = mdsalManager;
@@ -70,9 +81,13 @@ public class ExternalNetworksChangeListener
         this.bgpManager = bgpManager;
         this.vpnService = vpnService;
         this.fibService = fibService;
+        if (config != null) {
+            this.natMode = config.getNatMode();
+        }
     }
 
     @Override
+    @PostConstruct
     public void init() {
         LOG.info("{} init", getClass().getSimpleName());
         registerListener(LogicalDatastoreType.CONFIGURATION, dataBroker);
@@ -96,8 +111,7 @@ public class ExternalNetworksChangeListener
     @Override
     protected void remove(InstanceIdentifier<Networks> identifier, Networks networks) {
         if (identifier == null || networks == null || networks.getRouterIds().isEmpty()) {
-            LOG.info("ExternalNetworksChangeListener:remove:: returning without processing since "
-                + "networks/identifier is null");
+            LOG.error("remove : returning without processing since networks/identifier is null");
             return;
         }
 
@@ -109,8 +123,7 @@ public class ExternalNetworksChangeListener
 
             MDSALUtil.syncDelete(dataBroker, LogicalDatastoreType.OPERATIONAL, routerToNaptSwitchInstanceIdentifier);
 
-            LOG.debug("ExternalNetworksChangeListener:delete:: successful deletion of data in "
-                + "napt-switches container");
+            LOG.debug("remove : successful deletion of data in napt-switches container");
         }
     }
 
@@ -124,32 +137,37 @@ public class ExternalNetworksChangeListener
         //Check for VPN disassociation
         Uuid originalVpn = original.getVpnid();
         Uuid updatedVpn = update.getVpnid();
+        WriteTransaction writeFlowInvTx = dataBroker.newWriteOnlyTransaction();
+        List<ListenableFuture<Void>> futures = new ArrayList<>();
         if (originalVpn == null && updatedVpn != null) {
             //external network is dis-associated from L3VPN instance
-            associateExternalNetworkWithVPN(update);
+            associateExternalNetworkWithVPN(update, writeFlowInvTx);
         } else if (originalVpn != null && updatedVpn == null) {
             //external network is associated with vpn
             disassociateExternalNetworkFromVPN(update, originalVpn.getValue());
             //Remove the SNAT entries
-            removeSnatEntries(original, original.getId());
+            removeSnatEntries(original, original.getId(), writeFlowInvTx);
         }
+        futures.add(NatUtil.waitForTransactionToComplete(writeFlowInvTx));
     }
 
-    private void removeSnatEntries(Networks original, Uuid networkUuid) {
+    private void removeSnatEntries(Networks original, Uuid networkUuid, WriteTransaction writeFlowInvTx) {
         List<Uuid> routerUuids = original.getRouterIds();
         for (Uuid routerUuid : routerUuids) {
             Long routerId = NatUtil.getVpnId(dataBroker, routerUuid.getValue());
             if (routerId == NatConstants.INVALID_ID) {
-                LOG.error("NAT Service : Invalid routerId returned for routerName {}", routerUuid.getValue());
+                LOG.error("removeSnatEntries : Invalid routerId returned for routerName {}", routerUuid.getValue());
                 return;
             }
-            List<String> externalIps = NatUtil.getExternalIpsForRouter(dataBroker,routerId);
-            externalRouterListener.handleDisableSnatInternetVpn(routerUuid.getValue(), networkUuid, externalIps,
-                false, original.getVpnid().getValue());
+            Collection<String> externalIps = NatUtil.getExternalIpsForRouter(dataBroker,routerId);
+            if (natMode == NatMode.Controller) {
+                externalRouterListener.handleDisableSnatInternetVpn(routerUuid.getValue(), networkUuid, externalIps,
+                        false, original.getVpnid().getValue(), writeFlowInvTx);
+            }
         }
     }
 
-    private void associateExternalNetworkWithVPN(Networks network) {
+    private void associateExternalNetworkWithVPN(Networks network, WriteTransaction writeFlowInvTx) {
         List<Uuid> routerIds = network.getRouterIds();
         for (Uuid routerId : routerIds) {
             //long router = NatUtil.getVpnId(dataBroker, routerId.getValue());
@@ -158,8 +176,8 @@ public class ExternalNetworksChangeListener
             Optional<RouterPorts> optRouterPorts = MDSALUtil.read(dataBroker, LogicalDatastoreType.CONFIGURATION,
                 routerPortsId);
             if (!optRouterPorts.isPresent()) {
-                LOG.debug("Could not read Router Ports data object with id: {} to handle associate ext nw {}",
-                    routerId, network.getId());
+                LOG.debug("associateExternalNetworkWithVPN : Could not read Router Ports data object with id: {} "
+                        + "to handle associate ext nw {}", routerId, network.getId());
                 continue;
             }
             RouterPorts routerPorts = optRouterPorts.get();
@@ -168,8 +186,8 @@ public class ExternalNetworksChangeListener
                 String portName = port.getPortName();
                 BigInteger dpnId = NatUtil.getDpnForInterface(interfaceManager, portName);
                 if (dpnId.equals(BigInteger.ZERO)) {
-                    LOG.debug("DPN not found for {}, skip handling of ext nw {} association",
-                        portName, network.getId());
+                    LOG.debug("associateExternalNetworkWithVPN : DPN not found for {}, "
+                            + "skip handling of ext nw {} association", portName, network.getId());
                     continue;
                 }
                 List<InternalToExternalPortMap> intExtPortMapList = port.getInternalToExternalPortMap();
@@ -183,15 +201,16 @@ public class ExternalNetworksChangeListener
 
         // SNAT
         for (Uuid routerId : routerIds) {
-            LOG.debug("NAT Service : associateExternalNetworkWithVPN() for routerId {}",  routerId);
+            LOG.debug("associateExternalNetworkWithVPN() : for routerId {}",  routerId);
             Uuid networkId = network.getId();
             if (networkId == null) {
-                LOG.error("NAT Service : networkId is null for the router ID {}", routerId);
+                LOG.error("associateExternalNetworkWithVPN : networkId is null for the router ID {}", routerId);
                 return;
             }
             final String vpnName = network.getVpnid().getValue();
             if (vpnName == null) {
-                LOG.error("NAT Service : No VPN associated with ext nw {} for router {}", networkId, routerId);
+                LOG.error("associateExternalNetworkWithVPN : No VPN associated with ext nw {} for router {}",
+                        networkId, routerId);
                 return;
             }
 
@@ -203,10 +222,9 @@ public class ExternalNetworksChangeListener
             if (rtrToNapt.isPresent()) {
                 dpnId = rtrToNapt.get().getPrimarySwitchId();
             }
-            LOG.debug("NAT Service : got primarySwitch as dpnId{} ", dpnId);
+            LOG.debug("associateExternalNetworkWithVPN : got primarySwitch as dpnId{} ", dpnId);
             if (dpnId == null || dpnId.equals(BigInteger.ZERO)) {
-                LOG.debug("NAT Service : primary napt Switch not found for router {} in "
-                    + "associateExternalNetworkWithVPN", routerId);
+                LOG.error("associateExternalNetworkWithVPN : primary napt Switch not found for router {}", routerId);
                 return;
             }
 
@@ -226,24 +244,29 @@ public class ExternalNetworksChangeListener
                 List<IpMap> ipMaps = ipMapping.get().getIpMap();
                 for (IpMap ipMap : ipMaps) {
                     String externalIp = ipMap.getExternalIp();
-                    LOG.debug("NAT Service : got externalIp as {}", externalIp);
-                    LOG.debug("NAT Service : About to call advToBgpAndInstallFibAndTsFlows for dpnId {}, "
+                    LOG.debug("associateExternalNetworkWithVPN : Calling advToBgpAndInstallFibAndTsFlows for dpnId {},"
                         + "vpnName {} and externalIp {}", dpnId, vpnName, externalIp);
-                    externalRouterListener.advToBgpAndInstallFibAndTsFlows(dpnId, NwConstants.INBOUND_NAPT_TABLE,
-                        vpnName, NatUtil.getVpnId(dataBroker, routerId.getValue()), routerId.getValue(), externalIp,
-                        null /* external-router */, vpnService, fibService, bgpManager, dataBroker, LOG);
+                    if (natMode == NatMode.Controller) {
+                        externalRouterListener.advToBgpAndInstallFibAndTsFlows(dpnId, NwConstants.INBOUND_NAPT_TABLE,
+                                vpnName, NatUtil.getVpnId(dataBroker, routerId.getValue()), routerId.getValue(),
+                                externalIp, null /* external-router */, vpnService, fibService, bgpManager, dataBroker,
+                                LOG, writeFlowInvTx);
+                    }
                 }
             } else {
-                LOG.warn("NAT Service : No ipMapping present fot the routerId {}", routerId);
+                LOG.warn("associateExternalNetworkWithVPN : No ipMapping present fot the routerId {}", routerId);
             }
 
             long vpnId = NatUtil.getVpnId(dataBroker, vpnName);
             // Install 47 entry to point to 21
-            externalRouterListener.installNaptPfibEntriesForExternalSubnets(routerId.getValue(), dpnId);
-            if (vpnId != -1) {
-                LOG.debug("NAT Service : Calling externalRouterListener installNaptPfibEntry for dpnId {} "
-                    + "and vpnId {}", dpnId, vpnId);
-                externalRouterListener.installNaptPfibEntry(dpnId, vpnId);
+            if (natMode == NatMode.Controller) {
+                externalRouterListener.installNaptPfibEntriesForExternalSubnets(routerId.getValue(), dpnId,
+                        writeFlowInvTx);
+                if (vpnId != -1) {
+                    LOG.debug("associateExternalNetworkWithVPN : Calling externalRouterListener installNaptPfibEntry "
+                            + "for dpnId {} and vpnId {}", dpnId, vpnId);
+                    externalRouterListener.installNaptPfibEntry(dpnId, vpnId, writeFlowInvTx);
+                }
             }
         }
 
@@ -257,8 +280,8 @@ public class ExternalNetworksChangeListener
             Optional<RouterPorts> optRouterPorts = MDSALUtil.read(dataBroker, LogicalDatastoreType.CONFIGURATION,
                 routerPortsId);
             if (!optRouterPorts.isPresent()) {
-                LOG.debug("Could not read Router Ports data object with id: {} to handle disassociate ext nw {}",
-                    routerId, network.getId());
+                LOG.debug("disassociateExternalNetworkFromVPN : Could not read Router Ports data object with id: {} "
+                        + "to handle disassociate ext nw {}", routerId, network.getId());
                 continue;
             }
             RouterPorts routerPorts = optRouterPorts.get();
@@ -267,8 +290,8 @@ public class ExternalNetworksChangeListener
                 String portName = port.getPortName();
                 BigInteger dpnId = NatUtil.getDpnForInterface(interfaceManager, portName);
                 if (dpnId.equals(BigInteger.ZERO)) {
-                    LOG.debug("DPN not found for {}, skip handling of ext nw {} disassociation",
-                        portName, network.getId());
+                    LOG.debug("disassociateExternalNetworkFromVPN : DPN not found for {},"
+                            + "skip handling of ext nw {} disassociation", portName, network.getId());
                     continue;
                 }
                 List<InternalToExternalPortMap> intExtPortMapList = port.getInternalToExternalPortMap();
@@ -279,5 +302,4 @@ public class ExternalNetworksChangeListener
             }
         }
     }
-
 }