Bc Group population during cluster reboot
[netvirt.git] / elanmanager / impl / src / main / java / org / opendaylight / netvirt / elan / utils / ElanUtils.java
index ff832a637f956acd1bec517e9deb05db9a775211..88d29f9ee514c11d7bd10afc1c96849fe4e50eb8 100755 (executable)
@@ -7,6 +7,7 @@
  */
 package org.opendaylight.netvirt.elan.utils;
 
+import static java.util.Collections.emptyList;
 import static org.opendaylight.controller.md.sal.binding.api.WriteTransaction.CREATE_MISSING_PARENTS;
 import static org.opendaylight.genius.infra.Datastore.CONFIGURATION;
 
@@ -20,22 +21,26 @@ 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;
 import java.util.Collections;
+import java.util.LinkedHashSet;
 import java.util.List;
+import java.util.Objects;
+import java.util.Set;
 import java.util.concurrent.ExecutionException;
 import java.util.concurrent.Future;
-
-import javax.annotation.CheckReturnValue;
-import javax.annotation.Nonnull;
-import javax.annotation.Nullable;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.function.BiFunction;
+import java.util.function.Function;
+import java.util.stream.Collectors;
 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;
@@ -51,7 +56,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;
@@ -75,10 +79,12 @@ 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.elan.internal.ElanGroupCache;
 import org.opendaylight.netvirt.elanmanager.api.ElanHelper;
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddressBuilder;
@@ -130,7 +136,12 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.I
 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.RemoveTerminatingServiceActionsInput;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.RemoveTerminatingServiceActionsInputBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.RemoveTerminatingServiceActionsOutput;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.BucketId;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupId;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupTypes;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.group.Buckets;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.group.buckets.Bucket;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.group.buckets.BucketBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.Group;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.GroupKey;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
@@ -148,7 +159,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;
@@ -192,8 +202,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;
@@ -206,6 +246,16 @@ public class ElanUtils {
     private final ElanEtreeUtils elanEtreeUtils;
     private final ElanInterfaceCache elanInterfaceCache;
     private final IITMProvider iitmProvider;
+    private final ElanGroupCache elanGroupCache;
+
+    private static final Function<Bucket, Bucket> TO_BUCKET_WITHOUT_ID = (bucket) -> new BucketBuilder(bucket)
+            .setBucketId(new BucketId(0L))
+            .build();
+
+    private static final BiFunction<Bucket, AtomicLong, Bucket> TO_BUCKET_WITH_ID = (bucket, id)
+        -> new BucketBuilder(bucket)
+            .setBucketId(new BucketId(id.incrementAndGet()))
+            .build();
 
     public static final FutureCallback<Void> DEFAULT_CALLBACK = new FutureCallback<Void>() {
         @Override
@@ -223,7 +273,7 @@ public class ElanUtils {
     public ElanUtils(DataBroker dataBroker, IMdsalApiManager mdsalManager,
             OdlInterfaceRpcService interfaceManagerRpcService, ItmRpcService itmRpcService, ElanConfig elanConfig,
             IInterfaceManager interfaceManager, ElanEtreeUtils elanEtreeUtils, ElanItmUtils elanItmUtils,
-            ElanInterfaceCache elanInterfaceCache, IITMProvider iitmProvider) {
+            ElanInterfaceCache elanInterfaceCache, IITMProvider iitmProvider, ElanGroupCache elanGroupCache) {
         this.broker = dataBroker;
         this.txRunner = new ManagedNewTransactionRunnerImpl(dataBroker);
         this.mdsalManager = mdsalManager;
@@ -235,6 +285,7 @@ public class ElanUtils {
         this.elanItmUtils = elanItmUtils;
         this.elanInterfaceCache = elanInterfaceCache;
         this.iitmProvider = iitmProvider;
+        this.elanGroupCache = elanGroupCache;
     }
 
     public final Boolean isOpenstackVniSemanticsEnforced() {
@@ -272,7 +323,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");
     }
 
     /**
@@ -288,7 +339,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();
@@ -313,24 +364,13 @@ 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();
     }
 
     // elan-state Operational container
+    @Nullable
     public static Elan getElanByName(DataBroker broker, String elanInstanceName) {
         InstanceIdentifier<Elan> elanIdentifier = getElanInstanceOperationalDataPath(elanInstanceName);
         return MDSALUtil.read(broker, LogicalDatastoreType.OPERATIONAL, elanIdentifier).orNull();
@@ -347,18 +387,14 @@ public class ElanUtils {
     }
 
     // grouping of forwarding-entries
+    @Nullable
     public MacEntry getInterfaceMacEntriesOperationalDataPath(String interfaceName, PhysAddress physAddress) {
         InstanceIdentifier<MacEntry> existingMacEntryId = getInterfaceMacEntriesIdentifierOperationalDataPath(
                 interfaceName, physAddress);
         return read(broker, LogicalDatastoreType.OPERATIONAL, existingMacEntryId).orNull();
     }
 
-    public MacEntry getInterfaceMacEntriesOperationalDataPathFromId(InstanceIdentifier identifier) {
-        Optional<MacEntry> existingInterfaceMacEntry = read(broker,
-                LogicalDatastoreType.OPERATIONAL, identifier);
-        return existingInterfaceMacEntry.orNull();
-    }
-
+    @Nullable
     public MacEntry getInterfaceMacEntriesOperationalDataPathFromId(TypedReadTransaction<Operational> tx,
             InstanceIdentifier<MacEntry> identifier) throws ExecutionException, InterruptedException {
         return tx.read(identifier).get().orNull();
@@ -384,12 +420,7 @@ public class ElanUtils {
         return tx.read(macId).get();
     }
 
-    public MacEntry getMacEntryFromElanMacId(InstanceIdentifier identifier) {
-        Optional<MacEntry> existingInterfaceMacEntry = read(broker,
-                LogicalDatastoreType.OPERATIONAL, identifier);
-        return existingInterfaceMacEntry.orNull();
-    }
-
+    @Nullable
     public MacEntry getMacEntryFromElanMacId(TypedReadTransaction<Operational> tx,
             InstanceIdentifier<MacEntry> identifier) throws ExecutionException, InterruptedException {
         return tx.read(identifier).get().orNull();
@@ -418,25 +449,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)
@@ -445,7 +457,7 @@ public class ElanUtils {
 
     /**
      * Returns the list of Interfaces that belong to an Elan on an specific DPN.
-     * Data retrieved from Elan's operational DS: elan-dpn-interfaces container
+     * Data retrieved from Elan's operational DS: elan-dpn-interfaces container.
      *
      * @param elanInstanceName
      *            name of the Elan to which the interfaces must belong to
@@ -453,6 +465,7 @@ public class ElanUtils {
      *            Id of the DPN where the interfaces are located
      * @return the elan interface Info
      */
+    @Nullable
     public DpnInterfaces getElanInterfaceInfoByElanDpn(String elanInstanceName, BigInteger dpId) {
         InstanceIdentifier<DpnInterfaces> elanDpnInterfacesId = getElanDpnInterfaceOperationalDataPath(elanInstanceName,
                 dpId);
@@ -478,6 +491,7 @@ public class ElanUtils {
     }
 
     // elan-tag-name-map Operational Container
+    @Nullable
     public ElanTagName getElanInfoByElanTag(long elanTag) {
         InstanceIdentifier<ElanTagName> elanId = getElanInfoEntriesOperationalDataPath(elanTag);
         Optional<ElanTagName> existingElanInfo = read(broker,
@@ -506,11 +520,13 @@ public class ElanUtils {
                 .child(ElanDpnInterfacesList.class, new ElanDpnInterfacesListKey(elanInstanceName)).build();
     }
 
+    @Nullable
     public ElanDpnInterfacesList getElanDpnInterfacesList(String elanName) {
         InstanceIdentifier<ElanDpnInterfacesList> elanDpnInterfaceId = getElanDpnOperationDataPath(elanName);
         return read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId).orNull();
     }
 
+    @Nullable
     public ElanDpnInterfaces getElanDpnInterfacesList() {
         InstanceIdentifier<ElanDpnInterfaces> elanDpnInterfaceId = InstanceIdentifier.builder(ElanDpnInterfaces.class)
                 .build();
@@ -526,7 +542,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);
@@ -535,46 +551,13 @@ public class ElanUtils {
         if (!existingElanDpnInterfaces.isPresent()) {
             return dpIds;
         }
-        List<DpnInterfaces> dpnInterfaces = existingElanDpnInterfaces.get().getDpnInterfaces();
+        List<DpnInterfaces> dpnInterfaces = existingElanDpnInterfaces.get().nonnullDpnInterfaces();
         for (DpnInterfaces dpnInterface : dpnInterfaces) {
             dpIds.add(dpnInterface.getDpId());
         }
         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().getDpnInterfaces();
-        for (DpnInterfaces dpnInterface : dpnInterfaces) {
-            if (dpnInterface.getDpId().equals(dpId)) {
-                return true;
-            }
-        }
-        return false;
-    }
-
-    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;
     }
@@ -586,6 +569,7 @@ public class ElanUtils {
      *            the elan name
      * @return the elan mac table
      */
+    @Nullable
     public MacTable getElanMacTable(String elanName) {
         return getElanMacTable(broker, elanName);
     }
@@ -636,7 +620,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,
@@ -750,7 +734,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();
     }
 
     /**
@@ -800,7 +784,8 @@ public class ElanUtils {
      * @return the egress actions for interface
      */
     @SuppressWarnings("checkstyle:IllegalCatch")
-    public List<Action> getEgressActionsForInterface(String ifName, Long tunnelKey) {
+    @NonNull
+    public List<Action> getEgressActionsForInterface(String ifName, @Nullable Long tunnelKey) {
         List<Action> listAction = new ArrayList<>();
         try {
             GetEgressActionsForInterfaceInput getEgressActionInput = new GetEgressActionsForInterfaceInputBuilder()
@@ -812,8 +797,7 @@ public class ElanUtils {
                 LOG.debug("RPC Call to Get egress actions for interface {} returned with Errors {}", ifName,
                         rpcResult.getErrors());
             } else {
-                List<Action> actions = rpcResult.getResult().getAction();
-                listAction = actions;
+                listAction = rpcResult.getResult().nonnullAction();
             }
         } catch (Exception e) {
             LOG.warn("Exception when egress actions for interface {}", ifName, e);
@@ -843,7 +827,7 @@ public class ElanUtils {
         List<DpnInterfaces> elanDpns = getInvolvedDpnsInElan(elanInstanceName);
         for (DpnInterfaces elanDpn : elanDpns) {
 
-            if (elanDpn.getDpId().equals(dpId)) {
+            if (Objects.equals(elanDpn.getDpId(), dpId)) {
                 continue;
             }
 
@@ -868,16 +852,16 @@ 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(
-                ElanDpnInterfacesList::getDpnInterfaces).orElse(Collections.emptyList());
+                ElanDpnInterfacesList::getDpnInterfaces).orElse(emptyList());
     }
 
     private void setupLocalDmacFlow(long elanTag, BigInteger dpId, String ifName, String macAddress,
@@ -1070,7 +1054,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);
         }
     }
@@ -1208,6 +1192,8 @@ public class ElanUtils {
             elanInstanceBuilder.addAugmentation(EtreeInstance.class, etreeInstance);
         }
         ElanInstance elanInstanceWithTag = elanInstanceBuilder.build();
+        LOG.trace("Updated elan Operational DS for elan: {} with elanTag: {} and interfaces: {}", elanInstanceName,
+                elanTag, elanInterfaces);
         confTx.merge(ElanHelper.getElanInstanceConfigurationDataPath(elanInstanceName), elanInstanceWithTag,
             CREATE_MISSING_PARENTS);
         return elanInstanceWithTag;
@@ -1233,11 +1219,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;
     }
@@ -1296,6 +1277,7 @@ public class ElanUtils {
      *            the datastore type
      * @return the external tunnel
      */
+    @Nullable
     public ExternalTunnel getExternalTunnel(String sourceDevice, String destinationDevice,
             LogicalDatastoreType datastoreType) {
         Class<? extends TunnelTypeBase> tunType = TunnelTypeVxlan.class;
@@ -1313,6 +1295,7 @@ public class ElanUtils {
      *            the datastore type
      * @return the external tunnel
      */
+    @Nullable
     public ExternalTunnel getExternalTunnel(String interfaceName, LogicalDatastoreType datastoreType) {
         ExternalTunnel externalTunnel = null;
         List<ExternalTunnel> externalTunnels = getAllExternalTunnels(datastoreType);
@@ -1335,7 +1318,7 @@ public class ElanUtils {
     public List<ExternalTunnel> getAllExternalTunnels(LogicalDatastoreType datastoreType) {
         InstanceIdentifier<ExternalTunnelList> iid = InstanceIdentifier.builder(ExternalTunnelList.class).build();
         return read(broker, datastoreType, iid).toJavaUtil().map(ExternalTunnelList::getExternalTunnel).orElse(
-                Collections.emptyList());
+                emptyList());
     }
 
     public static List<MatchInfo> buildMatchesForElanTagShFlagAndDstMac(long elanTag, boolean shFlag, String macAddr) {
@@ -1375,13 +1358,10 @@ public class ElanUtils {
      *            the data broker
      * @return the interface state from oper ds
      */
-    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 +1385,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 {
@@ -1435,7 +1402,7 @@ public class ElanUtils {
                 && elanInstance.getSegmentationId() != null && elanInstance.getSegmentationId() != 0;
     }
 
-    private static boolean isVxlanSegment(ElanInstance elanInstance) {
+    private static boolean isVxlanSegment(@Nullable ElanInstance elanInstance) {
         if (elanInstance != null) {
             List<ElanSegments> elanSegments = elanInstance.getElanSegments();
             if (elanSegments != null) {
@@ -1451,7 +1418,7 @@ public class ElanUtils {
         return false;
     }
 
-    public static boolean isVxlanNetworkOrVxlanSegment(ElanInstance elanInstance) {
+    public static boolean isVxlanNetworkOrVxlanSegment(@Nullable ElanInstance elanInstance) {
         return isVxlan(elanInstance) || isVxlanSegment(elanInstance);
     }
 
@@ -1491,7 +1458,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 +1466,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);
@@ -1524,6 +1491,7 @@ public class ElanUtils {
                 matches, instructions);
     }
 
+    @Nullable
     public String getExternalElanInterface(String elanInstanceName, BigInteger dpnId) {
         DpnInterfaces dpnInterfaces = getElanInterfaceInfoByElanDpn(elanInstanceName, dpnId);
         if (dpnInterfaces == null || dpnInterfaces.getInterfaces() == null) {
@@ -1541,14 +1509,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>>
@@ -1591,18 +1553,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;
@@ -1614,18 +1564,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();
     }
@@ -1656,7 +1594,7 @@ public class ElanUtils {
     public List<MacEntry> getElanMacEntries(String elanName) {
         MacTable macTable = getElanMacTable(elanName);
         if (macTable == null) {
-            return Collections.emptyList();
+            return emptyList();
         }
         return macTable.getMacEntry();
     }
@@ -1699,11 +1637,12 @@ 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");
     }
 
+    @Nullable
     public static String getRouterPordIdFromElanInstance(DataBroker dataBroker, String elanInstanceName) {
         Optional<Subnetmaps> subnetMapsData =
                 read(dataBroker, LogicalDatastoreType.CONFIGURATION, buildSubnetMapsWildCardPath());
@@ -1722,6 +1661,71 @@ public class ElanUtils {
         return null;
     }
 
+    protected  Node buildDpnNode(BigInteger dpnId) {
+        org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId nodeId =
+                new org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819
+                        .NodeId("openflow:" + dpnId);
+        Node nodeDpn = new NodeBuilder().setId(nodeId).withKey(new NodeKey(nodeId)).build();
+        return nodeDpn;
+    }
+
+    public void syncUpdateGroup(BigInteger dpnId, Group newGroup, long delayTime,
+                                TypedWriteTransaction<Datastore.Configuration> confTx) {
+        Node nodeDpn = buildDpnNode(dpnId);
+        long groupIdInfo = newGroup.getGroupId().getValue();
+        GroupKey groupKey = new GroupKey(new GroupId(groupIdInfo));
+        InstanceIdentifier<Group> groupInstanceId = InstanceIdentifier.builder(Nodes.class)
+                .child(Node.class, nodeDpn.key()).augmentation(FlowCapableNode.class)
+                .child(Group.class, groupKey).build();
+        LOG.trace("Performing merge operation for remote BC group for node {} with group {}", nodeDpn, newGroup);
+        Optional<Group> existingGroupOpt = ElanUtils.read(broker, LogicalDatastoreType.CONFIGURATION, groupInstanceId);
+        if (!existingGroupOpt.isPresent()) {
+            LOG.debug("Group {} doesn't exist. Performing syncInstall", groupIdInfo);
+            mdsalManager.addGroup(confTx, dpnId, newGroup);
+            return;
+        }
+        Buckets existingGroup = existingGroupOpt.get().getBuckets();
+        if (existingGroup == null) {
+            LOG.debug("Bucket doesn't exist for group {}. Performing syncInstall", groupIdInfo);
+            mdsalManager.addGroup(confTx, dpnId, newGroup);
+            return;
+        }
+        if (newGroup.getBuckets() == null) {
+            LOG.debug("Buckets are not sent for group {}. Skipping merge operation", groupIdInfo);
+            return;
+        }
+        List<Bucket> newBuckets = newGroup.getBuckets().getBucket();
+        List<Bucket> existingBuckets = existingGroup.getBucket();
+        Set<Bucket> toMergeBucketsWithoutId = new LinkedHashSet<>();
+
+        existingBuckets.stream()
+                .map(TO_BUCKET_WITHOUT_ID)
+                .forEach(bucketWithoutId -> toMergeBucketsWithoutId.add(bucketWithoutId));
+
+        newBuckets.stream()
+                .map(TO_BUCKET_WITHOUT_ID)
+                .forEach(bucketWithoutId -> toMergeBucketsWithoutId.add(bucketWithoutId));
+
+        if (toMergeBucketsWithoutId.size() == existingBuckets.size()) {
+            //no new buckets got added
+            //size matched and no extra buckets in existing buckets , rewrite the group
+            LOG.debug("Buckets did not change group {}. Skipping merge operation", groupIdInfo);
+            return;
+        }
+        LOG.debug("Old group buckets size {} New group buckets size {} Dpn id {} Group id {} ",
+                existingBuckets.size(), toMergeBucketsWithoutId.size(), dpnId, groupIdInfo);
+        AtomicLong bucketIdValue = new AtomicLong(-1);
+        //Change the bucket id of existing buckets
+        List<Bucket> bucketsToBeAdded = toMergeBucketsWithoutId.stream()
+                .map(bucketWithoutId -> TO_BUCKET_WITH_ID.apply(bucketWithoutId, bucketIdValue))
+                .collect(Collectors.toList());
+
+        Group group = MDSALUtil.buildGroup(newGroup.getGroupId().getValue(), newGroup.getGroupName(),
+                GroupTypes.GroupAll, MDSALUtil.buildBucketLists(bucketsToBeAdded));
+        mdsalManager.addGroup(confTx, dpnId, group);
+        LOG.trace("Installed remote BC group for node {} with group {}", nodeDpn, group);
+    }
+
     static InstanceIdentifier<Subnetmaps> buildSubnetMapsWildCardPath() {
         return InstanceIdentifier.create(Subnetmaps.class);
     }
@@ -1730,6 +1734,8 @@ public class ElanUtils {
         return InstanceIdentifier.builder(Nodes.class).child(Node.class, new NodeKey(new NodeId("openflow:" + dpnId)))
                 .augmentation(FlowCapableNode.class).child(Group.class, new GroupKey(new GroupId(groupId))).build();
     }
-}
-
 
+    public static String getBcGroupUpdateKey(String elanName) {
+        return "bc.group.update." + elanName;
+    }
+}