MRI version bumpup for Aluminium
[netvirt.git] / elanmanager / impl / src / main / java / org / opendaylight / netvirt / elan / utils / ElanUtils.java
index 853f8b5c45fa8e5d8d2790845d8295882a7fdaac..975c12d8806cf10401f5469e8dfae825619c7794 100755 (executable)
@@ -8,15 +8,14 @@
 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 java.util.Collections.emptyMap;
 import static org.opendaylight.genius.infra.Datastore.CONFIGURATION;
 
-import com.google.common.base.Optional;
 import com.google.common.base.Preconditions;
 import com.google.common.base.Strings;
 import com.google.common.collect.Lists;
 import com.google.common.primitives.Ints;
-import com.google.common.util.concurrent.CheckedFuture;
+import com.google.common.util.concurrent.FluentFuture;
 import com.google.common.util.concurrent.FutureCallback;
 import com.google.common.util.concurrent.Futures;
 import com.google.common.util.concurrent.ListenableFuture;
@@ -26,9 +25,13 @@ import java.math.BigInteger;
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.Collections;
+import java.util.HashMap;
 import java.util.LinkedHashSet;
 import java.util.List;
+import java.util.Locale;
+import java.util.Map;
 import java.util.Objects;
+import java.util.Optional;
 import java.util.Set;
 import java.util.concurrent.ExecutionException;
 import java.util.concurrent.Future;
@@ -41,12 +44,7 @@ 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;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
-import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
+import org.opendaylight.genius.datastoreutils.SingleTransactionDataBroker;
 import org.opendaylight.genius.infra.Datastore;
 import org.opendaylight.genius.infra.Datastore.Configuration;
 import org.opendaylight.genius.infra.Datastore.Operational;
@@ -82,6 +80,12 @@ import org.opendaylight.genius.mdsalutil.packet.IPv4;
 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.mdsal.binding.api.DataBroker;
+import org.opendaylight.mdsal.binding.api.ReadTransaction;
+import org.opendaylight.mdsal.binding.api.WriteTransaction;
+import org.opendaylight.mdsal.common.api.CommitInfo;
+import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
+import org.opendaylight.mdsal.common.api.TransactionCommitFailedException;
 import org.opendaylight.netvirt.elan.arp.responder.ArpResponderUtil;
 import org.opendaylight.netvirt.elan.cache.ElanInterfaceCache;
 import org.opendaylight.netvirt.elan.internal.ElanGroupCache;
@@ -102,6 +106,7 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.ta
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowKey;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.Instruction;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.InstructionKey;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdInput;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdInputBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdOutput;
@@ -178,6 +183,7 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan
 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.ElanInstance;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.ElanInstanceBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.elan.instance.ElanSegments;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.elan.instance.ElanSegmentsKey;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.ElanInterface;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.ElanInterfaceKey;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.elan._interface.StaticMacEntries;
@@ -259,9 +265,9 @@ public class ElanUtils {
             .setBucketId(new BucketId(id.incrementAndGet()))
             .build();
 
-    public static final FutureCallback<Void> DEFAULT_CALLBACK = new FutureCallback<Void>() {
+    public static final FutureCallback<CommitInfo> DEFAULT_CALLBACK = new FutureCallback<CommitInfo>() {
         @Override
-        public void onSuccess(Void result) {
+        public void onSuccess(CommitInfo result) {
             LOG.debug("Success in Datastore operation");
         }
 
@@ -313,7 +319,7 @@ public class ElanUtils {
             Future<RpcResult<AllocateIdOutput>> result = idManager.allocateId(getIdInput);
             RpcResult<AllocateIdOutput> rpcResult = result.get();
             if (rpcResult.isSuccessful()) {
-                return Uint32.valueOf(rpcResult.getResult().getIdValue().longValue());
+                return rpcResult.getResult().getIdValue();
             } else {
                 LOG.warn("RPC Call to Allocate Id returned with Errors {}", rpcResult.getErrors());
             }
@@ -343,27 +349,28 @@ public class ElanUtils {
     @SuppressWarnings("checkstyle:IllegalCatch")
     public static <T extends DataObject> Optional<T> read(@NonNull DataBroker broker,
             LogicalDatastoreType datastoreType, InstanceIdentifier<T> path) {
-        try (ReadOnlyTransaction tx = broker.newReadOnlyTransaction()) {
+        try (ReadTransaction tx = broker.newReadOnlyTransaction()) {
             return tx.read(datastoreType, path).get();
-        } catch (Exception e) {
+        } catch (ExecutionException | InterruptedException  e) {
             throw new RuntimeException(e);
         }
     }
 
     public <T extends DataObject> Optional<T> read2(LogicalDatastoreType datastoreType, InstanceIdentifier<T> path)
-            throws ReadFailedException {
-        try (ReadOnlyTransaction tx = broker.newReadOnlyTransaction()) {
-            CheckedFuture<Optional<T>, ReadFailedException> checkedFuture = tx.read(datastoreType, path);
-            return checkedFuture.checkedGet();
+            throws InterruptedException, ExecutionException {
+        try (ReadTransaction tx = broker.newReadOnlyTransaction()) {
+            FluentFuture<Optional<T>> checkedFuture = tx.read(datastoreType, path);
+            return checkedFuture.get();
         }
     }
 
     @SuppressWarnings("checkstyle:ForbidCertainMethod")
     public static <T extends DataObject> void delete(DataBroker broker, LogicalDatastoreType datastoreType,
-            InstanceIdentifier<T> path) {
+                                                            InstanceIdentifier<T> path) {
         WriteTransaction tx = broker.newWriteOnlyTransaction();
         tx.delete(datastoreType, path);
-        Futures.addCallback(tx.submit(), DEFAULT_CALLBACK, MoreExecutors.directExecutor());
+        FluentFuture<? extends @NonNull CommitInfo> future = tx.commit();
+        future.addCallback(DEFAULT_CALLBACK, MoreExecutors.directExecutor());
     }
 
     public static InstanceIdentifier<ElanInterface> getElanInterfaceConfigurationDataPathId(String interfaceName) {
@@ -375,13 +382,20 @@ public class ElanUtils {
     @Nullable
     public static Elan getElanByName(DataBroker broker, String elanInstanceName) {
         InstanceIdentifier<Elan> elanIdentifier = getElanInstanceOperationalDataPath(elanInstanceName);
-        return MDSALUtil.read(broker, LogicalDatastoreType.OPERATIONAL, elanIdentifier).orNull();
+        try {
+            return SingleTransactionDataBroker.syncReadOptional(broker, LogicalDatastoreType.OPERATIONAL,
+                    elanIdentifier).orElse(null);
+        } catch (ExecutionException | InterruptedException e) {
+            LOG.error("getElanByName: Exception while reading elan-instance DS for the elan instance {}",
+                    elanInstanceName, e);
+            return null;
+        }
     }
 
     @Nullable
     public static Elan getElanByName(TypedReadTransaction<Operational> tx, String elanInstanceName)
             throws ExecutionException, InterruptedException {
-        return tx.read(getElanInstanceOperationalDataPath(elanInstanceName)).get().orNull();
+        return tx.read(getElanInstanceOperationalDataPath(elanInstanceName)).get().orElse(null);
     }
 
     public static InstanceIdentifier<Elan> getElanInstanceOperationalDataPath(String elanInstanceName) {
@@ -393,13 +407,13 @@ public class ElanUtils {
     public MacEntry getInterfaceMacEntriesOperationalDataPath(String interfaceName, PhysAddress physAddress) {
         InstanceIdentifier<MacEntry> existingMacEntryId = getInterfaceMacEntriesIdentifierOperationalDataPath(
                 interfaceName, physAddress);
-        return read(broker, LogicalDatastoreType.OPERATIONAL, existingMacEntryId).orNull();
+        return read(broker, LogicalDatastoreType.OPERATIONAL, existingMacEntryId).orElse(null);
     }
 
     @Nullable
     public MacEntry getInterfaceMacEntriesOperationalDataPathFromId(TypedReadTransaction<Operational> tx,
             InstanceIdentifier<MacEntry> identifier) throws ExecutionException, InterruptedException {
-        return tx.read(identifier).get().orNull();
+        return tx.read(identifier).get().orElse(null);
     }
 
     public static InstanceIdentifier<MacEntry> getInterfaceMacEntriesIdentifierOperationalDataPath(String interfaceName,
@@ -425,7 +439,7 @@ public class ElanUtils {
     @Nullable
     public MacEntry getMacEntryFromElanMacId(TypedReadTransaction<Operational> tx,
             InstanceIdentifier<MacEntry> identifier) throws ExecutionException, InterruptedException {
-        return tx.read(identifier).get().orNull();
+        return tx.read(identifier).get().orElse(null);
     }
 
     public static InstanceIdentifier<MacEntry> getMacEntryOperationalDataPath(String elanName,
@@ -448,7 +462,7 @@ public class ElanUtils {
     public static ElanInterfaceMac getElanInterfaceMacByInterfaceName(DataBroker dataBroker, String interfaceName) {
         InstanceIdentifier<ElanInterfaceMac> elanInterfaceId = getElanInterfaceMacEntriesOperationalDataPath(
                 interfaceName);
-        return read(dataBroker, LogicalDatastoreType.OPERATIONAL, elanInterfaceId).orNull();
+        return read(dataBroker, LogicalDatastoreType.OPERATIONAL, elanInterfaceId).orElse(null);
     }
 
     public static InstanceIdentifier<ElanInterfaceMac> getElanInterfaceMacEntriesOperationalDataPath(
@@ -471,7 +485,7 @@ public class ElanUtils {
     public DpnInterfaces getElanInterfaceInfoByElanDpn(String elanInstanceName, Uint64 dpId) {
         InstanceIdentifier<DpnInterfaces> elanDpnInterfacesId = getElanDpnInterfaceOperationalDataPath(elanInstanceName,
                 dpId);
-        return read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfacesId).orNull();
+        return read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfacesId).orElse(null);
     }
 
     /**
@@ -498,7 +512,7 @@ public class ElanUtils {
         InstanceIdentifier<ElanTagName> elanId = getElanInfoEntriesOperationalDataPath(elanTag);
         Optional<ElanTagName> existingElanInfo = read(broker,
                 LogicalDatastoreType.OPERATIONAL, elanId);
-        return existingElanInfo.orNull();
+        return existingElanInfo.orElse(null);
     }
 
     public static InstanceIdentifier<ElanTagName> getElanInfoEntriesOperationalDataPath(Uint32 elanTag) {
@@ -526,14 +540,14 @@ public class ElanUtils {
     @Nullable
     public ElanDpnInterfacesList getElanDpnInterfacesList(String elanName) {
         InstanceIdentifier<ElanDpnInterfacesList> elanDpnInterfaceId = getElanDpnOperationDataPath(elanName);
-        return read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId).orNull();
+        return read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId).orElse(null);
     }
 
     @Nullable
     public ElanDpnInterfaces getElanDpnInterfacesList() {
         InstanceIdentifier<ElanDpnInterfaces> elanDpnInterfaceId = InstanceIdentifier.builder(ElanDpnInterfaces.class)
                 .build();
-        return read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId).orNull();
+        return read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId).orElse(null);
     }
 
     /**
@@ -554,8 +568,8 @@ public class ElanUtils {
         if (!existingElanDpnInterfaces.isPresent()) {
             return dpIds;
         }
-        List<DpnInterfaces> dpnInterfaces = existingElanDpnInterfaces.get().nonnullDpnInterfaces();
-        for (DpnInterfaces dpnInterface : dpnInterfaces) {
+        Map<DpnInterfacesKey, DpnInterfaces> dpnInterfaces = existingElanDpnInterfaces.get().nonnullDpnInterfaces();
+        for (DpnInterfaces dpnInterface : dpnInterfaces.values()) {
             dpIds.add(dpnInterface.getDpId());
         }
         return dpIds;
@@ -580,7 +594,7 @@ public class ElanUtils {
     @Nullable
     public static MacTable getElanMacTable(DataBroker dataBroker, String elanName) {
         InstanceIdentifier<MacTable> elanMacTableId = getElanMacTableOperationalDataPath(elanName);
-        return read(dataBroker, LogicalDatastoreType.OPERATIONAL, elanMacTableId).orNull();
+        return read(dataBroker, LogicalDatastoreType.OPERATIONAL, elanMacTableId).orElse(null);
     }
 
     public static long getElanLocalBCGId(long elanTag) {
@@ -670,7 +684,7 @@ public class ElanUtils {
         return new FlowEntityBuilder()
             .setDpnId(dpId)
             .setTableId(NwConstants.ELAN_SMAC_TABLE)
-            .setFlowId(getKnownDynamicmacFlowRef(NwConstants.ELAN_SMAC_TABLE, dpId, lportTag, macAddress, elanTag))
+            .setFlowId(getKnownDynamicmacFlowRef(elanTag, macAddress))
             .setPriority(20)
             .setFlowName(elanInfo.getDescription())
             .setIdleTimeOut((int) macTimeout)
@@ -685,7 +699,8 @@ public class ElanUtils {
     }
 
     private Uint32 getElanTag(ElanInstance elanInfo, InterfaceInfo interfaceInfo) {
-        EtreeInterface etreeInterface = elanInterfaceCache.getEtreeInterface(interfaceInfo.getInterfaceName()).orNull();
+        EtreeInterface etreeInterface = elanInterfaceCache
+            .getEtreeInterface(interfaceInfo.getInterfaceName()).orElse(null);
         if (etreeInterface == null || etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
             return elanInfo.getElanTag();
         } else { // Leaf
@@ -765,11 +780,12 @@ public class ElanUtils {
      *            external)
      * @return the Instruction
      */
-    public List<Instruction> getInstructionsInPortForOutGroup(String ifName) {
-        List<Instruction> mkInstructions = new ArrayList<>();
+    public Map<InstructionKey, Instruction> getInstructionsInPortForOutGroup(String ifName) {
+        int instructionsKey = 0;
+        Map<InstructionKey, Instruction> mkInstructions = new HashMap<>();
         List<Action> actions = getEgressActionsForInterface(ifName, /* tunnelKey */ null);
 
-        mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
+        mkInstructions.put(new InstructionKey(++instructionsKey), MDSALUtil.buildApplyActionsInstruction(actions));
         return mkInstructions;
     }
 
@@ -801,7 +817,7 @@ public class ElanUtils {
                 LOG.debug("RPC Call to Get egress actions for interface {} returned with Errors {}", ifName,
                         rpcResult.getErrors());
             } else {
-                listAction = rpcResult.getResult().nonnullAction();
+                listAction = new ArrayList<Action>(rpcResult.getResult().nonnullAction().values());
             }
         } catch (Exception e) {
             LOG.warn("Exception when egress actions for interface {}", ifName, e);
@@ -864,8 +880,15 @@ public class ElanUtils {
     @NonNull
     public List<DpnInterfaces> getElanDPNByName(String elanInstanceName) {
         InstanceIdentifier<ElanDpnInterfacesList> elanIdentifier = getElanDpnOperationDataPath(elanInstanceName);
-        return MDSALUtil.read(broker, LogicalDatastoreType.OPERATIONAL, elanIdentifier).toJavaUtil().map(
-                ElanDpnInterfacesList::getDpnInterfaces).orElse(emptyList());
+        try {
+            return new ArrayList<DpnInterfaces>((SingleTransactionDataBroker.syncReadOptional(broker,
+                    LogicalDatastoreType.OPERATIONAL, elanIdentifier).map(ElanDpnInterfacesList::getDpnInterfaces)
+                    .orElse(emptyMap())).values());
+        } catch (ExecutionException | InterruptedException e) {
+            LOG.error("getElanDPNByName: Exception while reading elanDpnInterfaceList DS for the elan "
+                    + "instance {}", elanInstanceName, e);
+            return emptyList();
+        }
     }
 
     private void setupLocalDmacFlow(Uint32 elanTag, Uint64 dpId, String ifName, String macAddress,
@@ -878,7 +901,7 @@ public class ElanUtils {
 
     private void installEtreeLocalDmacFlow(Uint32 elanTag, Uint64 dpId, String ifName, String macAddress,
             ElanInstance elanInfo, long ifTag, TypedWriteTransaction<Configuration> writeFlowGroupTx) {
-        EtreeInterface etreeInterface = elanInterfaceCache.getEtreeInterface(ifName).orNull();
+        EtreeInterface etreeInterface = elanInterfaceCache.getEtreeInterface(ifName).orElse(null);
         if (etreeInterface != null && etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
             EtreeLeafTagName etreeTagName = elanEtreeUtils.getEtreeLeafTagByElanTag(elanTag.longValue());
             if (etreeTagName == null) {
@@ -892,18 +915,8 @@ public class ElanUtils {
         }
     }
 
-    public static String getKnownDynamicmacFlowRef(short tableId, Uint64 dpId, long lporTag, String macAddress,
-            Uint32 elanTag) {
-        return String.valueOf(tableId) + elanTag + dpId + lporTag + macAddress;
-    }
-
-    public static String getKnownDynamicmacFlowRef(short tableId, Uint64 dpId, Uint64 remoteDpId,
-            String macAddress, Uint32 elanTag) {
-        return String.valueOf(tableId) + elanTag + dpId + remoteDpId + macAddress;
-    }
-
-    public static String getKnownDynamicmacFlowRef(short tableId, Uint64 dpId, String macAddress, Uint32 elanTag) {
-        return String.valueOf(tableId) + elanTag + dpId + macAddress;
+    public static String getKnownDynamicmacFlowRef(Uint32 elanTag, String macAddress) {
+        return new StringBuffer().append(elanTag).append(macAddress.toLowerCase(Locale.getDefault())).toString();
     }
 
     public static String getKnownDynamicmacFlowRef(short elanDmacTable, Uint64 dpId, String extDeviceNodeId,
@@ -941,11 +954,11 @@ public class ElanUtils {
             MetaDataUtil.METADATA_MASK_SERVICE));
         mkMatches.add(new MatchEthernetDestination(new MacAddress(macAddress)));
 
-        List<Instruction> mkInstructions = new ArrayList<>();
+        Map<InstructionKey, Instruction> mkInstructions = new HashMap<>();
         List<Action> actions = getEgressActionsForInterface(ifName, /* tunnelKey */ null);
-        mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
+        mkInstructions.put(new InstructionKey(0), MDSALUtil.buildApplyActionsInstruction(actions));
         Flow flow = MDSALUtil.buildFlowNew(NwConstants.ELAN_DMAC_TABLE,
-                getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, ifTag, macAddress, elanTag), 20,
+                getKnownDynamicmacFlowRef(elanTag, macAddress), 20,
                 elanInfo.getElanInstanceName(), 0, 0,
                 Uint64.valueOf(ElanConstants.COOKIE_ELAN_KNOWN_DMAC.longValue() + elanTag.longValue()),
                 mkMatches, mkInstructions);
@@ -961,12 +974,11 @@ public class ElanUtils {
                     macAddress, interfaceName, elanInstance.getElanInstanceName());
             return;
         }
-        Flow flowEntity;
         // if openstack-vni-semantics are enforced, segmentation ID is passed as network VNI for VxLAN based provider
         // networks, 0 otherwise
         long lportTagOrVni = !isOpenstackVniSemanticsEnforced() ? lportTag : isVxlanNetworkOrVxlanSegment(elanInstance)
                 ? getVxlanSegmentationId(elanInstance).longValue() : 0;
-        flowEntity = buildRemoteDmacFlowEntry(srcDpId, destDpId, lportTagOrVni, elanTag, macAddress, displayName,
+        Flow flowEntity = buildRemoteDmacFlowEntry(srcDpId, destDpId, lportTagOrVni, elanTag, macAddress, displayName,
                 elanInstance);
         mdsalManager.addFlow(writeFlowGroupTx, srcDpId, flowEntity);
         setupEtreeRemoteDmacFlow(srcDpId, destDpId, lportTagOrVni, elanTag, macAddress, displayName, interfaceName,
@@ -978,7 +990,7 @@ public class ElanUtils {
                                           TypedWriteTransaction<Configuration> writeFlowGroupTx,
                                           ElanInstance elanInstance) {
         Flow flowEntity;
-        EtreeInterface etreeInterface = elanInterfaceCache.getEtreeInterface(interfaceName).orNull();
+        EtreeInterface etreeInterface = elanInterfaceCache.getEtreeInterface(interfaceName).orElse(null);
         if (etreeInterface != null && etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
             EtreeLeafTagName etreeTagName = elanEtreeUtils.getEtreeLeafTagByElanTag(elanTag.longValue());
             if (etreeTagName == null) {
@@ -1022,7 +1034,7 @@ public class ElanUtils {
             MetaDataUtil.METADATA_MASK_SERVICE));
         mkMatches.add(new MatchEthernetDestination(new MacAddress(macAddress)));
 
-        List<Instruction> mkInstructions = new ArrayList<>();
+        Map<InstructionKey, Instruction> mkInstructions = new HashMap<>();
 
         // List of Action for the provided Source and Destination DPIDs
         try {
@@ -1037,14 +1049,14 @@ public class ElanUtils {
                 }
                 actions = getEgressActionsForInterface(interfaceName, null);
             }
-            mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
+            mkInstructions.put(new InstructionKey(0), MDSALUtil.buildApplyActionsInstruction(actions));
         } catch (Exception e) {
             LOG.error("Could not get egress actions to add to flow for srcDpId {}, destDpId {}, lportTag/VNI {}",
                     srcDpId,  destDpId, lportTagOrVni, e);
         }
 
         Flow flow = MDSALUtil.buildFlowNew(NwConstants.ELAN_DMAC_TABLE,
-                getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, srcDpId, destDpId, macAddress, elanTag),
+                getKnownDynamicmacFlowRef(elanTag, macAddress),
                 20, /* prio */
                 displayName, 0, /* idleTimeout */
                 0, /* hardTimeout */
@@ -1110,30 +1122,39 @@ public class ElanUtils {
         } else if (isDpnPresent(dstDpId)) {
             mdsalManager
                 .removeFlow(flowTx, dstDpId,
-                    MDSALUtil.buildFlow(NwConstants.ELAN_DMAC_TABLE, getKnownDynamicmacFlowRef(
-                        NwConstants.ELAN_DMAC_TABLE, dstDpId, srcdpId, macAddress, elanTag)));
+                    MDSALUtil.buildFlow(NwConstants.ELAN_DMAC_TABLE, getKnownDynamicmacFlowRef(elanTag, macAddress)));
             LOG.debug("Dmac flow entry deleted for elan:{}, logical interface port:{} and mac address:{} on dpn:{}",
                     elanInstanceName, interfaceInfo.getPortName(), macAddress, dstDpId);
         }
         return isFlowsRemovedInSrcDpn;
     }
 
+    public void deleteSmacFlowOnly(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
+                                   TypedReadWriteTransaction<Configuration> flowTx) throws ExecutionException,
+            InterruptedException {
+        Uint64 srcdpId = interfaceInfo.getDpId();
+        Uint32 elanTag = elanInfo.getElanTag();
+        LOG.debug("Deleting SMAC flow with id {}", getKnownDynamicmacFlowRef(elanTag, macAddress));
+        mdsalManager.removeFlow(flowTx, srcdpId,
+                MDSALUtil.buildFlow(NwConstants.ELAN_SMAC_TABLE, getKnownDynamicmacFlowRef(elanTag, macAddress)));
+    }
+
     private void deleteSmacAndDmacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
             boolean deleteSmac, TypedReadWriteTransaction<Configuration> flowTx)
             throws ExecutionException, InterruptedException {
         String elanInstanceName = elanInfo.getElanInstanceName();
-        long ifTag = interfaceInfo.getInterfaceTag();
         Uint64 srcdpId = interfaceInfo.getDpId();
         Uint32 elanTag = elanInfo.getElanTag();
         if (deleteSmac) {
+            LOG.debug("Deleting SMAC flow with id {}", getKnownDynamicmacFlowRef(elanTag, macAddress));
             mdsalManager
                     .removeFlow(flowTx, srcdpId,
-                            MDSALUtil.buildFlow(NwConstants.ELAN_SMAC_TABLE, getKnownDynamicmacFlowRef(
-                                    NwConstants.ELAN_SMAC_TABLE, srcdpId, ifTag, macAddress, elanTag)));
+                            MDSALUtil.buildFlow(NwConstants.ELAN_SMAC_TABLE,
+                                    getKnownDynamicmacFlowRef(elanTag, macAddress)));
         }
         mdsalManager.removeFlow(flowTx, srcdpId,
             MDSALUtil.buildFlow(NwConstants.ELAN_DMAC_TABLE,
-                getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, srcdpId, ifTag, macAddress, elanTag)));
+                getKnownDynamicmacFlowRef(elanTag, macAddress)));
         LOG.debug("All the required flows deleted for elan:{}, logical Interface port:{} and MAC address:{} on dpn:{}",
                 elanInstanceName, interfaceInfo.getPortName(), macAddress, srcdpId);
     }
@@ -1161,15 +1182,20 @@ public class ElanUtils {
         if (elanTag == null || elanTag.longValue() == 0L) {
             elanTag = retrieveNewElanTag(idManager, elanInstanceName);
         }
+        if (elanTag.longValue() == 0L) {
+            LOG.error("ELAN tag creation failed for elan instance {}. Not updating the ELAN DS. "
+                    + "Recreate network for recovery", elanInstanceName);
+            return null;
+        }
         Elan elanInfo = new ElanBuilder().setName(elanInstanceName).setElanInterfaces(elanInterfaces)
                 .withKey(new ElanKey(elanInstanceName)).build();
 
         // Add the ElanState in the elan-state operational data-store
-        operTx.put(getElanInstanceOperationalDataPath(elanInstanceName), elanInfo, CREATE_MISSING_PARENTS);
+        operTx.mergeParentStructurePut(getElanInstanceOperationalDataPath(elanInstanceName), elanInfo);
 
         // Add the ElanMacTable in the elan-mac-table operational data-store
         MacTable elanMacTable = new MacTableBuilder().withKey(new MacTableKey(elanInstanceName)).build();
-        operTx.put(getElanMacTableOperationalDataPath(elanInstanceName), elanMacTable, CREATE_MISSING_PARENTS);
+        operTx.mergeParentStructurePut(getElanMacTableOperationalDataPath(elanInstanceName), elanMacTable);
 
         ElanTagNameBuilder elanTagNameBuilder = new ElanTagNameBuilder().setElanTag(elanTag)
                 .withKey(new ElanTagNameKey(elanTag)).setName(elanInstanceName);
@@ -1190,7 +1216,8 @@ public class ElanUtils {
 
         // Updates the ElanInstance Config DS by setting the just acquired
         // elanTag
-        ElanInstanceBuilder elanInstanceBuilder = new ElanInstanceBuilder().setElanInstanceName(elanInstanceName)
+        ElanInstanceBuilder elanInstanceBuilder = new ElanInstanceBuilder(elanInstanceAdded)
+                .setElanInstanceName(elanInstanceName)
                 .setDescription(elanInstanceAdded.getDescription())
                 .setMacTimeout(elanInstanceAdded.getMacTimeout() == null
                         ? Uint32.valueOf(ElanConstants.DEFAULT_MAC_TIME_OUT) : elanInstanceAdded.getMacTimeout())
@@ -1203,8 +1230,8 @@ public class ElanUtils {
         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);
+        confTx.mergeParentStructureMerge(ElanHelper.getElanInstanceConfigurationDataPath(elanInstanceName),
+                elanInstanceWithTag);
         return elanInstanceWithTag;
     }
 
@@ -1249,8 +1276,9 @@ public class ElanUtils {
 
     public static List<MatchInfo> getTunnelMatchesForServiceId(Uint32 elanTag) {
         List<MatchInfo> mkMatches = new ArrayList<>();
-        // Matching metadata
-        mkMatches.add(new MatchTunnelId(Uint64.valueOf(elanTag.longValue())));
+
+        // Adding 270000 to avoid collision between LPort and elan tag for broadcast
+        mkMatches.add(new MatchTunnelId(Uint64.valueOf(elanTag.longValue() + ElanConstants.ELAN_TAG_ADDEND)));
 
         return mkMatches;
     }
@@ -1292,7 +1320,7 @@ public class ElanUtils {
         Class<? extends TunnelTypeBase> tunType = TunnelTypeVxlan.class;
         InstanceIdentifier<ExternalTunnel> iid = InstanceIdentifier.builder(ExternalTunnelList.class)
                 .child(ExternalTunnel.class, new ExternalTunnelKey(destinationDevice, sourceDevice, tunType)).build();
-        return read(broker, datastoreType, iid).orNull();
+        return read(broker, datastoreType, iid).orElse(null);
     }
 
     /**
@@ -1326,8 +1354,8 @@ 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(
-                emptyList());
+        return new ArrayList<ExternalTunnel>(read(broker, datastoreType, iid).map(ExternalTunnelList
+                ::getExternalTunnel).orElse(Collections.emptyMap()).values());
     }
 
     public static List<MatchInfo> buildMatchesForElanTagShFlagAndDstMac(long elanTag, boolean shFlag, String macAddr) {
@@ -1369,8 +1397,14 @@ public class ElanUtils {
      */
     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();
+        try {
+            return SingleTransactionDataBroker.syncReadOptional(dataBroker, LogicalDatastoreType.OPERATIONAL,
+                    createInterfaceStateInstanceIdentifier(interfaceName)).orElse(null);
+        } catch (ExecutionException | InterruptedException e) {
+            LOG.error("getInterfaceStateFromOperDS: Exception while reading interface DS for the interface {}",
+                    interfaceName, e);
+            return null;
+        }
     }
 
     /**
@@ -1413,9 +1447,9 @@ public class ElanUtils {
 
     private static boolean isVxlanSegment(@Nullable ElanInstance elanInstance) {
         if (elanInstance != null) {
-            List<ElanSegments> elanSegments = elanInstance.getElanSegments();
+            Map<ElanSegmentsKey, ElanSegments> elanSegments = elanInstance.getElanSegments();
             if (elanSegments != null) {
-                for (ElanSegments segment : elanSegments) {
+                for (ElanSegments segment : elanSegments.values()) {
                     if (segment != null && segment.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
                             && segment.getSegmentationId() != null
                             && segment.getSegmentationId().longValue() != 0) {
@@ -1442,7 +1476,7 @@ public class ElanUtils {
                 && elanInstance.getSegmentationId() != null && elanInstance.getSegmentationId().longValue() != 0) {
             segmentationId = elanInstance.getSegmentationId();
         } else {
-            for (ElanSegments segment: elanInstance.getElanSegments()) {
+            for (ElanSegments segment: elanInstance.getElanSegments().values()) {
                 if (segment != null && segment.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
                     && segment.getSegmentationId() != null
                     && segment.getSegmentationId().longValue() != 0) {
@@ -1478,7 +1512,7 @@ public class ElanUtils {
         LoggingFutures.addErrorLogging(
             txRunner.callWithNewReadWriteTransactionAndSubmit(Datastore.CONFIGURATION, tx -> {
                 for (Uint64 dpId : dpnIds) {
-                    String flowId = getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, macAddress, elanTag);
+                    String flowId = getKnownDynamicmacFlowRef(elanTag, macAddress);
                     mdsalManager.removeFlow(tx, dpId, MDSALUtil.buildFlow(NwConstants.ELAN_DMAC_TABLE, flowId));
                 }
             }), LOG, "Error removing DMAC redirect to dispatcher flows");
@@ -1495,7 +1529,7 @@ public class ElanUtils {
         actions.add(new ActionNxResubmit(NwConstants.LPORT_DISPATCHER_TABLE));
 
         instructions.add(new InstructionApplyActions(actions));
-        String flowId = getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, dstMacAddress, elanTag);
+        String flowId = getKnownDynamicmacFlowRef(elanTag, dstMacAddress);
         return MDSALUtil.buildFlowEntity(dpId, NwConstants.ELAN_DMAC_TABLE, flowId, 20, displayName, 0, 0,
                 Uint64.valueOf(ElanConstants.COOKIE_ELAN_KNOWN_DMAC.longValue() + elanTag.longValue()),
                 matches, instructions);
@@ -1583,7 +1617,7 @@ public class ElanUtils {
     }
 
     public Optional<IpAddress> getSourceIpAddress(Ethernet ethernet) {
-        Optional<IpAddress> srcIpAddress = Optional.absent();
+        Optional<IpAddress> srcIpAddress = Optional.empty();
         if (ethernet.getPayload() == null) {
             return srcIpAddress;
         }
@@ -1606,7 +1640,7 @@ public class ElanUtils {
         if (macTable == null) {
             return emptyList();
         }
-        return macTable.getMacEntry();
+        return new ArrayList<MacEntry>(macTable.getMacEntry().values());
     }
 
     public boolean isTunnelInLogicalGroup(String interfaceName) {
@@ -1657,7 +1691,7 @@ public class ElanUtils {
         Optional<Subnetmaps> subnetMapsData =
                 read(dataBroker, LogicalDatastoreType.CONFIGURATION, buildSubnetMapsWildCardPath());
         if (subnetMapsData.isPresent()) {
-            List<Subnetmap> subnetMapList = subnetMapsData.get().getSubnetmap();
+            List<Subnetmap> subnetMapList = new ArrayList<>(subnetMapsData.get().getSubnetmap().values());
             if (subnetMapList != null && !subnetMapList.isEmpty()) {
                 for (Subnetmap subnet : subnetMapList) {
                     if (subnet.getNetworkId().getValue().equals(elanInstanceName)) {
@@ -1704,8 +1738,8 @@ public class ElanUtils {
             LOG.debug("Buckets are not sent for group {}. Skipping merge operation", groupIdInfo);
             return;
         }
-        List<Bucket> newBuckets = newGroup.getBuckets().getBucket();
-        List<Bucket> existingBuckets = existingGroup.getBucket();
+        List<Bucket> newBuckets = new ArrayList<Bucket>(newGroup.getBuckets().getBucket().values());
+        List<Bucket> existingBuckets = new ArrayList<Bucket>(existingGroup.getBucket().values());
         Set<Bucket> toMergeBucketsWithoutId = new LinkedHashSet<>();
 
         existingBuckets.stream()