TSC-181 : ITM Yang Models Cleanup
[netvirt.git] / elanmanager / impl / src / main / java / org / opendaylight / netvirt / elan / utils / ElanUtils.java
index 334f871b103ffa0a6d2ca3e4a4078561d0d076fb..a25c8a25eed3c7b10a2475eca48ccbe96fbee4e6 100755 (executable)
@@ -21,6 +21,7 @@ import com.google.common.util.concurrent.FutureCallback;
 import com.google.common.util.concurrent.Futures;
 import com.google.common.util.concurrent.ListenableFuture;
 import com.google.common.util.concurrent.MoreExecutors;
+import edu.umd.cs.findbugs.annotations.CheckReturnValue;
 import java.math.BigInteger;
 import java.util.ArrayList;
 import java.util.Collection;
@@ -29,12 +30,11 @@ import java.util.List;
 import java.util.Objects;
 import java.util.concurrent.ExecutionException;
 import java.util.concurrent.Future;
-import javax.annotation.CheckReturnValue;
-import javax.annotation.Nonnull;
-import javax.annotation.Nullable;
 import javax.inject.Inject;
 import javax.inject.Singleton;
 import org.apache.commons.lang3.StringUtils;
+import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.jdt.annotation.Nullable;
 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
@@ -50,7 +50,6 @@ import org.opendaylight.genius.infra.TypedReadTransaction;
 import org.opendaylight.genius.infra.TypedReadWriteTransaction;
 import org.opendaylight.genius.infra.TypedWriteTransaction;
 import org.opendaylight.genius.interfacemanager.globals.InterfaceInfo;
-import org.opendaylight.genius.interfacemanager.globals.InterfaceServiceUtil;
 import org.opendaylight.genius.interfacemanager.interfaces.IInterfaceManager;
 import org.opendaylight.genius.itm.api.IITMProvider;
 import org.opendaylight.genius.itm.globals.ITMConstants;
@@ -74,8 +73,9 @@ import org.opendaylight.genius.mdsalutil.matches.MatchTunnelId;
 import org.opendaylight.genius.mdsalutil.packet.ARP;
 import org.opendaylight.genius.mdsalutil.packet.Ethernet;
 import org.opendaylight.genius.mdsalutil.packet.IPv4;
-import org.opendaylight.infrautils.utils.concurrent.JdkFutures;
-import org.opendaylight.infrautils.utils.concurrent.ListenableFutures;
+import org.opendaylight.infrautils.utils.concurrent.LoggingFutures;
+import org.opendaylight.infrautils.utils.concurrent.NamedLocks;
+import org.opendaylight.infrautils.utils.concurrent.NamedSimpleReentrantLock.Acquired;
 import org.opendaylight.netvirt.elan.arp.responder.ArpResponderUtil;
 import org.opendaylight.netvirt.elan.cache.ElanInterfaceCache;
 import org.opendaylight.netvirt.elanmanager.api.ElanHelper;
@@ -147,7 +147,6 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev16061
 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeLeafTagNameBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanDpnInterfaces;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanForwardingTables;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInstances;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInterfaceForwardingEntries;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInterfaces;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanState;
@@ -191,8 +190,38 @@ import org.slf4j.LoggerFactory;
 
 @Singleton
 public class ElanUtils {
+    private static final class ElanLockName {
+        private final String macAddress;
+        private final BigInteger dpnId;
+        private final long elanTag;
+
+        ElanLockName(long elanTag, String macAddress, BigInteger dpnId) {
+            this.elanTag = elanTag;
+            this.macAddress = macAddress;
+            this.dpnId = dpnId;
+        }
+
+        @Override
+        public int hashCode() {
+            return 31 * Long.hashCode(elanTag) + Objects.hash(macAddress, dpnId);
+        }
+
+        @Override
+        public boolean equals(Object obj) {
+            if (this == obj) {
+                return true;
+            }
+            if (!(obj instanceof ElanLockName)) {
+                return false;
+            }
+            final ElanLockName other = (ElanLockName) obj;
+            return elanTag == other.elanTag && Objects.equals(macAddress, other.macAddress)
+                    && Objects.equals(dpnId, other.dpnId);
+        }
+    }
 
     private static final Logger LOG = LoggerFactory.getLogger(ElanUtils.class);
+    private static final NamedLocks<ElanLockName> ELAN_LOCKS = new NamedLocks<>();
 
     private final DataBroker broker;
     private final ManagedNewTransactionRunner txRunner;
@@ -271,7 +300,7 @@ public class ElanUtils {
 
     public static void releaseId(IdManagerService idManager, String poolName, String idKey) {
         ReleaseIdInput releaseIdInput = new ReleaseIdInputBuilder().setPoolName(poolName).setIdKey(idKey).build();
-        JdkFutures.addErrorLogging(idManager.releaseId(releaseIdInput), LOG, "Release Id");
+        LoggingFutures.addErrorLogging(idManager.releaseId(releaseIdInput), LOG, "Release Id");
     }
 
     /**
@@ -287,7 +316,7 @@ public class ElanUtils {
      */
     @Deprecated
     @SuppressWarnings("checkstyle:IllegalCatch")
-    public static <T extends DataObject> Optional<T> read(@Nonnull DataBroker broker,
+    public static <T extends DataObject> Optional<T> read(@NonNull DataBroker broker,
             LogicalDatastoreType datastoreType, InstanceIdentifier<T> path) {
         try (ReadOnlyTransaction tx = broker.newReadOnlyTransaction()) {
             return tx.read(datastoreType, path).get();
@@ -312,18 +341,6 @@ public class ElanUtils {
         Futures.addCallback(tx.submit(), DEFAULT_CALLBACK, MoreExecutors.directExecutor());
     }
 
-    @SuppressWarnings("checkstyle:ForbidCertainMethod")
-    public static <T extends DataObject> void delete(DataBroker broker, LogicalDatastoreType datastoreType,
-            InstanceIdentifier<T> path, FutureCallback<Void> callback) {
-        WriteTransaction tx = broker.newWriteOnlyTransaction();
-        tx.delete(datastoreType, path);
-        Futures.addCallback(tx.submit(), callback, MoreExecutors.directExecutor());
-    }
-
-    public static InstanceIdentifier<ElanInstance> getElanInstanceIdentifier() {
-        return InstanceIdentifier.builder(ElanInstances.class).child(ElanInstance.class).build();
-    }
-
     public static InstanceIdentifier<ElanInterface> getElanInterfaceConfigurationDataPathId(String interfaceName) {
         return InstanceIdentifier.builder(ElanInterfaces.class)
                 .child(ElanInterface.class, new ElanInterfaceKey(interfaceName)).build();
@@ -409,25 +426,6 @@ public class ElanUtils {
         return read(dataBroker, LogicalDatastoreType.OPERATIONAL, elanInterfaceId).orNull();
     }
 
-    /**
-     * Gets the elan interface mac addresses.
-     *
-     * @param interfaceName
-     *            the interface name
-     * @return the elan interface mac addresses
-     */
-    public List<PhysAddress> getElanInterfaceMacAddresses(String interfaceName) {
-        List<PhysAddress> macAddresses = new ArrayList<>();
-        ElanInterfaceMac elanInterfaceMac = getElanInterfaceMacByInterfaceName(interfaceName);
-        if (elanInterfaceMac != null && elanInterfaceMac.getMacEntry() != null) {
-            List<MacEntry> macEntries = elanInterfaceMac.getMacEntry();
-            for (MacEntry macEntry : macEntries) {
-                macAddresses.add(macEntry.getMacAddress());
-            }
-        }
-        return macAddresses;
-    }
-
     public static InstanceIdentifier<ElanInterfaceMac> getElanInterfaceMacEntriesOperationalDataPath(
             String interfaceName) {
         return InstanceIdentifier.builder(ElanInterfaceForwardingEntries.class)
@@ -521,7 +519,7 @@ public class ElanUtils {
      *            the elan instance name
      * @return list of dpIds
      */
-    @Nonnull
+    @NonNull
     public List<BigInteger> getParticipatingDpnsInElanInstance(String elanInstanceName) {
         List<BigInteger> dpIds = new ArrayList<>();
         InstanceIdentifier<ElanDpnInterfacesList> elanDpnInterfaceId = getElanDpnOperationDataPath(elanInstanceName);
@@ -537,40 +535,6 @@ public class ElanUtils {
         return dpIds;
     }
 
-    /**
-     * To check given dpId is already present in Elan instance. This can be used
-     * to program flow entry in external tunnel table when a new access port
-     * added for first time into the ELAN instance
-     *
-     * @param dpId
-     *            the dp id
-     * @param elanInstanceName
-     *            the elan instance name
-     * @return true if dpId is already present, otherwise return false
-     */
-    public boolean isDpnAlreadyPresentInElanInstance(BigInteger dpId, String elanInstanceName) {
-        InstanceIdentifier<ElanDpnInterfacesList> elanDpnInterfaceId = getElanDpnOperationDataPath(elanInstanceName);
-        Optional<ElanDpnInterfacesList> existingElanDpnInterfaces = read(broker,
-                LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId);
-        if (!existingElanDpnInterfaces.isPresent()) {
-            return false;
-        }
-        List<DpnInterfaces> dpnInterfaces = existingElanDpnInterfaces.get().nonnullDpnInterfaces();
-        for (DpnInterfaces dpnInterface : dpnInterfaces) {
-            if (Objects.equals(dpnInterface.getDpId(), dpId)) {
-                return true;
-            }
-        }
-        return false;
-    }
-
-    @Nullable
-    public ElanForwardingTables getElanForwardingList() {
-        InstanceIdentifier<ElanForwardingTables> elanForwardingTableId = InstanceIdentifier
-                .builder(ElanForwardingTables.class).build();
-        return read(broker, LogicalDatastoreType.OPERATIONAL, elanForwardingTableId).orNull();
-    }
-
     public static long getElanRemoteBroadCastGroupID(long elanTag) {
         return ElanConstants.ELAN_GID_MIN + elanTag % ElanConstants.ELAN_GID_MIN * 2;
     }
@@ -633,7 +597,7 @@ public class ElanUtils {
     public void setupMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo,
                               long macTimeout, String macAddress, boolean configureRemoteFlows,
                               TypedWriteTransaction<Configuration> writeFlowGroupTx) {
-        synchronized (getElanMacDPNKey(elanInfo.getElanTag(), macAddress, interfaceInfo.getDpId())) {
+        try (Acquired lock = lockElanMacDPN(elanInfo.getElanTag(), macAddress, interfaceInfo.getDpId())) {
             setupKnownSmacFlow(elanInfo, interfaceInfo, macTimeout, macAddress, mdsalManager,
                 writeFlowGroupTx);
             setupOrigDmacFlows(elanInfo, interfaceInfo, macAddress, configureRemoteFlows, mdsalManager,
@@ -747,7 +711,7 @@ public class ElanUtils {
      * @return the Internal tunnel
      */
     public static String getIntTunnelTableFlowRef(short tableId, int elanTag) {
-        return new StringBuffer().append(tableId).append(elanTag).toString();
+        return new StringBuilder().append(tableId).append(elanTag).toString();
     }
 
     /**
@@ -797,7 +761,7 @@ public class ElanUtils {
      * @return the egress actions for interface
      */
     @SuppressWarnings("checkstyle:IllegalCatch")
-    @Nonnull
+    @NonNull
     public List<Action> getEgressActionsForInterface(String ifName, @Nullable Long tunnelKey) {
         List<Action> listAction = new ArrayList<>();
         try {
@@ -865,12 +829,12 @@ public class ElanUtils {
         // TODO: Make sure that the same is performed against the ElanDevices.
     }
 
-    @Nonnull
+    @NonNull
     public List<DpnInterfaces> getInvolvedDpnsInElan(String elanName) {
         return getElanDPNByName(elanName);
     }
 
-    @Nonnull
+    @NonNull
     public List<DpnInterfaces> getElanDPNByName(String elanInstanceName) {
         InstanceIdentifier<ElanDpnInterfacesList> elanIdentifier = getElanDpnOperationDataPath(elanInstanceName);
         return MDSALUtil.read(broker, LogicalDatastoreType.OPERATIONAL, elanIdentifier).toJavaUtil().map(
@@ -1067,7 +1031,7 @@ public class ElanUtils {
             return;
         }
         String macAddress = macEntry.getMacAddress().getValue();
-        synchronized (getElanMacDPNKey(elanInfo.getElanTag(), macAddress, interfaceInfo.getDpId())) {
+        try (Acquired lock = lockElanMacDPN(elanInfo.getElanTag(), macAddress, interfaceInfo.getDpId())) {
             deleteMacFlows(elanInfo, interfaceInfo, macAddress, /* alsoDeleteSMAC */ true, flowTx);
         }
     }
@@ -1230,11 +1194,6 @@ public class ElanUtils {
         return read(broker, LogicalDatastoreType.CONFIGURATION, node).isPresent();
     }
 
-    public static ServicesInfo getServiceInfo(String elanInstanceName, String interfaceName) {
-        return InterfaceServiceUtil.buildServiceInfo(elanInstanceName + "." + interfaceName,
-                ElanConstants.ELAN_SERVICE_PRIORITY);
-    }
-
     public static String getElanServiceName(String elanName, String interfaceName) {
         return "elan." + elanName + interfaceName;
     }
@@ -1374,14 +1333,10 @@ public class ElanUtils {
      *            the data broker
      * @return the interface state from oper ds
      */
-    @Nullable
-    public static org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
-        .ietf.interfaces.rev140508.interfaces.state.Interface getInterfaceStateFromOperDS(
-            String interfaceName, DataBroker dataBroker) {
-        InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
-            .ietf.interfaces.rev140508.interfaces.state.Interface> ifStateId = createInterfaceStateInstanceIdentifier(
-                interfaceName);
-        return MDSALUtil.read(dataBroker, LogicalDatastoreType.OPERATIONAL, ifStateId).orNull();
+    public static org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state
+            .@Nullable Interface getInterfaceStateFromOperDS(String interfaceName, DataBroker dataBroker) {
+        return MDSALUtil.read(dataBroker, LogicalDatastoreType.OPERATIONAL,
+            createInterfaceStateInstanceIdentifier(interfaceName)).orNull();
     }
 
     /**
@@ -1405,19 +1360,6 @@ public class ElanUtils {
         return idBuilder.build();
     }
 
-    @CheckReturnValue
-    public static CheckedFuture<Void, TransactionCommitFailedException> waitForTransactionToComplete(
-            WriteTransaction tx) {
-        CheckedFuture<Void, TransactionCommitFailedException> futures = tx.submit();
-        try {
-            futures.get();
-        } catch (InterruptedException | ExecutionException e) {
-            // NETVIRT-1215: Do not log.error() here, only debug(); but callers *MUST* @CheckReturnValue
-            LOG.debug("Error writing to datastore", e);
-        }
-        return futures;
-    }
-
     @CheckReturnValue
     public static ListenableFuture<Void> waitForTransactionToComplete(ListenableFuture<Void> future) {
         try {
@@ -1491,7 +1433,7 @@ public class ElanUtils {
     public void addDmacRedirectToDispatcherFlows(Long elanTag, String displayName,
             String macAddress, List<BigInteger> dpnIds) {
         for (BigInteger dpId : dpnIds) {
-            ListenableFutures.addErrorLogging(txRunner.callWithNewWriteOnlyTransactionAndSubmit(CONFIGURATION,
+            LoggingFutures.addErrorLogging(txRunner.callWithNewWriteOnlyTransactionAndSubmit(CONFIGURATION,
                 tx -> mdsalManager.addFlow(tx, buildDmacRedirectToDispatcherFlow(dpId, macAddress, displayName,
                         elanTag))), LOG,
                 "Error adding DMAC redirect to dispatcher flows");
@@ -1499,7 +1441,7 @@ public class ElanUtils {
     }
 
     public void removeDmacRedirectToDispatcherFlows(Long elanTag, String macAddress, List<BigInteger> dpnIds) {
-        ListenableFutures.addErrorLogging(
+        LoggingFutures.addErrorLogging(
             txRunner.callWithNewReadWriteTransactionAndSubmit(Datastore.CONFIGURATION, tx -> {
                 for (BigInteger dpId : dpnIds) {
                     String flowId = getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, macAddress, elanTag);
@@ -1542,14 +1484,8 @@ public class ElanUtils {
         return null;
     }
 
-    public static String getElanMacDPNKey(long elanTag, String macAddress, BigInteger dpnId) {
-        String elanMacDmacDpnKey = "MAC-" + macAddress + " ELAN_TAG-" + elanTag + "DPN_ID-" + dpnId;
-        return elanMacDmacDpnKey.intern();
-    }
-
-    public static String getElanMacKey(long elanTag, String macAddress) {
-        String elanMacKey = "MAC-" + macAddress + " ELAN_TAG-" + elanTag;
-        return elanMacKey.intern();
+    public static Acquired lockElanMacDPN(long elanTag, String macAddress, BigInteger dpnId) {
+        return ELAN_LOCKS.acquire(new ElanLockName(elanTag, macAddress, dpnId));
     }
 
     public static List<ListenableFuture<Void>>
@@ -1592,18 +1528,6 @@ public class ElanUtils {
                         new StaticMacEntriesKey(new PhysAddress(macAddress))).build();
     }
 
-    public static List<StaticMacEntries> getDeletedEntries(List<StaticMacEntries> originalStaticMacEntries,
-                                                           List<StaticMacEntries> updatedStaticMacEntries) {
-        if (isEmpty(originalStaticMacEntries)) {
-            return Collections.EMPTY_LIST;
-        }
-        List<StaticMacEntries> deleted = Lists.newArrayList(originalStaticMacEntries);
-        if (isNotEmpty(updatedStaticMacEntries)) {
-            deleted.removeAll(updatedStaticMacEntries);
-        }
-        return deleted;
-    }
-
     public static <T> List<T> diffOf(List<T> orig, List<T> updated) {
         if (isEmpty(orig)) {
             return Collections.EMPTY_LIST;
@@ -1615,18 +1539,6 @@ public class ElanUtils {
         return diff;
     }
 
-    public static void segregateToBeDeletedAndAddEntries(List<StaticMacEntries> originalStaticMacEntries,
-                                                             List<StaticMacEntries> updatedStaticMacEntries) {
-        if (isNotEmpty(updatedStaticMacEntries)) {
-            List<StaticMacEntries> existingClonedStaticMacEntries = new ArrayList<>();
-            if (isNotEmpty(originalStaticMacEntries)) {
-                existingClonedStaticMacEntries.addAll(0, originalStaticMacEntries);
-                originalStaticMacEntries.removeAll(updatedStaticMacEntries);
-                updatedStaticMacEntries.removeAll(existingClonedStaticMacEntries);
-            }
-        }
-    }
-
     public static boolean isEmpty(Collection collection) {
         return collection == null || collection.isEmpty();
     }
@@ -1700,7 +1612,7 @@ public class ElanUtils {
             int lportTag) {
         LOG.info("Removing the ARP responder flow on DPN {} of Interface {} with IP {}", dpnId, ingressInterfaceName,
                 ipAddress);
-        ListenableFutures.addErrorLogging(txRunner.callWithNewReadWriteTransactionAndSubmit(Datastore.CONFIGURATION,
+        LoggingFutures.addErrorLogging(txRunner.callWithNewReadWriteTransactionAndSubmit(Datastore.CONFIGURATION,
             tx -> mdsalManager.removeFlow(tx, dpnId, ArpResponderUtil.getFlowId(lportTag, ipAddress),
                 NwConstants.ARP_RESPONDER_TABLE)), LOG, "Error removing ARP responder flow");
     }