Elan Junit Testcases
[netvirt.git] / vpnservice / elanmanager / elanmanager-impl / src / main / java / org / opendaylight / netvirt / elan / utils / ElanUtils.java
index 4b31da4c6468418d8989cd6766e13dbb70562c86..ad0ce127bae043cbeda3ce632d70504907c5f9c2 100755 (executable)
@@ -16,6 +16,7 @@ import com.google.common.util.concurrent.CheckedFuture;
 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 java.math.BigInteger;
 import java.util.ArrayList;
@@ -28,13 +29,15 @@ import java.util.Set;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.ExecutionException;
 import java.util.concurrent.Future;
+
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
 import javax.inject.Inject;
 import javax.inject.Singleton;
 import org.apache.commons.lang3.StringUtils;
 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.clustering.EntityOwnershipService;
 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;
@@ -47,7 +50,6 @@ import org.opendaylight.genius.mdsalutil.FlowEntity;
 import org.opendaylight.genius.mdsalutil.FlowEntityBuilder;
 import org.opendaylight.genius.mdsalutil.InstructionInfo;
 import org.opendaylight.genius.mdsalutil.MDSALUtil;
-import org.opendaylight.genius.mdsalutil.MDSALUtil.MdsalOp;
 import org.opendaylight.genius.mdsalutil.MatchInfo;
 import org.opendaylight.genius.mdsalutil.MetaDataUtil;
 import org.opendaylight.genius.mdsalutil.NWUtil;
@@ -63,13 +65,10 @@ 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.genius.utils.ServiceIndex;
 import org.opendaylight.netvirt.elan.ElanException;
+import org.opendaylight.netvirt.elan.arp.responder.ArpResponderUtil;
 import org.opendaylight.netvirt.elan.internal.ElanInstanceManager;
-import org.opendaylight.netvirt.elan.internal.ElanInterfaceManager;
 import org.opendaylight.netvirt.elan.l2gw.utils.ElanL2GatewayMulticastUtils;
-import org.opendaylight.netvirt.elan.l2gw.utils.ElanL2GatewayUtils;
-import org.opendaylight.netvirt.elan.l2gw.utils.L2GatewayConnectionUtils;
 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;
@@ -80,9 +79,12 @@ import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress;
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.PhysAddress;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableKey;
 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.FlowBuilder;
+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.genius.idmanager.rev160406.AllocateIdInput;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdInputBuilder;
@@ -97,8 +99,6 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev
 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.ParentRefs;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelTypeBase;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelTypeVxlan;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetDpidFromInterfaceInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetDpidFromInterfaceOutput;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetEgressActionsForInterfaceInput;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetEgressActionsForInterfaceInputBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetEgressActionsForInterfaceOutput;
@@ -116,18 +116,13 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.ser
 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.ExternalTunnelList;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.external.tunnel.list.ExternalTunnel;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.external.tunnel.list.ExternalTunnelKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.GetExternalTunnelInterfaceNameInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.GetExternalTunnelInterfaceNameInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.GetExternalTunnelInterfaceNameOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.GetTunnelInterfaceNameInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.GetTunnelInterfaceNameInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.GetTunnelInterfaceNameOutput;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.ItmRpcService;
 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.inventory.rev130819.NodeId;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.config.rev150710.ElanConfig;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInstance;
@@ -195,11 +190,11 @@ public class ElanUtils {
     private final ElanInstanceManager elanInstanceManager;
     private final OdlInterfaceRpcService interfaceManagerRpcService;
     private final ItmRpcService itmRpcService;
-    private final ElanL2GatewayUtils elanL2GatewayUtils;
     private final ElanL2GatewayMulticastUtils elanL2GatewayMulticastUtils;
-    private final L2GatewayConnectionUtils l2GatewayConnectionUtils;
     private final IInterfaceManager interfaceManager;
     private final ElanConfig elanConfig;
+    private final ElanItmUtils elanItmUtils;
+    private final ElanEtreeUtils elanEtreeUtils;
 
     public static final FutureCallback<Void> DEFAULT_CALLBACK = new FutureCallback<Void>() {
         @Override
@@ -216,8 +211,10 @@ public class ElanUtils {
     @Inject
     public ElanUtils(DataBroker dataBroker, IMdsalApiManager mdsalManager, ElanInstanceManager elanInstanceManager,
                      OdlInterfaceRpcService interfaceManagerRpcService, ItmRpcService itmRpcService,
-                     ElanInterfaceManager elanInterfaceManager, ElanConfig elanConfig,
-                     EntityOwnershipService entityOwnershipService, IInterfaceManager interfaceManager) {
+                     ElanConfig elanConfig,
+                     IInterfaceManager interfaceManager,
+                     ElanL2GatewayMulticastUtils elanL2GatewayMulticastUtils, ElanEtreeUtils elanEtreeUtils,
+                     ElanItmUtils elanItmUtils) {
         this.broker = dataBroker;
         this.mdsalManager = mdsalManager;
         this.elanInstanceManager = elanInstanceManager;
@@ -226,33 +223,18 @@ public class ElanUtils {
         this.interfaceManager = interfaceManager;
         this.elanConfig = elanConfig;
 
-        elanL2GatewayMulticastUtils =
-                new ElanL2GatewayMulticastUtils(broker, elanInstanceManager, elanInterfaceManager, this);
-        elanL2GatewayUtils = new ElanL2GatewayUtils(broker, itmRpcService, this,
-                entityOwnershipService, elanL2GatewayMulticastUtils);
-        elanL2GatewayMulticastUtils.setEElanL2GatewayUtils(elanL2GatewayUtils);
-        l2GatewayConnectionUtils = new L2GatewayConnectionUtils(broker,
-                elanInstanceManager, entityOwnershipService, this);
-    }
-
-    public void close() {
-        elanL2GatewayUtils.close();
-    }
-
-    public ElanL2GatewayUtils getElanL2GatewayUtils() {
-        return elanL2GatewayUtils;
+        this.elanL2GatewayMulticastUtils = elanL2GatewayMulticastUtils;
+        this.elanEtreeUtils = elanEtreeUtils;
+        this.elanItmUtils = elanItmUtils;
     }
 
     public ElanL2GatewayMulticastUtils getElanL2GatewayMulticastUtils() {
         return elanL2GatewayMulticastUtils;
     }
 
-    public L2GatewayConnectionUtils getL2GatewayConnectionUtils() {
-        return l2GatewayConnectionUtils;
-    }
-
     public final Boolean isOpenStackVniSemanticsEnforced() {
-        return elanConfig.isOpenstackVniSemanticsEnforced();
+        return elanConfig.isOpenstackVniSemanticsEnforced() != null
+                ? elanConfig.isOpenstackVniSemanticsEnforced() : false;
     }
 
     public static void addElanInstanceIntoCache(String elanInstanceName, ElanInstance elanInstance) {
@@ -324,10 +306,9 @@ public class ElanUtils {
      */
     @Deprecated
     @SuppressWarnings("checkstyle:IllegalCatch")
-    public <T extends DataObject> Optional<T> read(DataBroker broker, LogicalDatastoreType datastoreType,
-            InstanceIdentifier<T> path) {
-        try (ReadOnlyTransaction tx = broker != null ? broker.newReadOnlyTransaction()
-                : this.broker.newReadOnlyTransaction()) {
+    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();
         } catch (Exception e) {
             throw new RuntimeException(e);
@@ -346,14 +327,14 @@ public class ElanUtils {
             InstanceIdentifier<T> path) {
         WriteTransaction tx = broker.newWriteOnlyTransaction();
         tx.delete(datastoreType, path);
-        Futures.addCallback(tx.submit(), DEFAULT_CALLBACK);
+        Futures.addCallback(tx.submit(), DEFAULT_CALLBACK, MoreExecutors.directExecutor());
     }
 
     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);
+        Futures.addCallback(tx.submit(), callback, MoreExecutors.directExecutor());
     }
 
     public static InstanceIdentifier<ElanInstance> getElanInstanceIdentifier() {
@@ -451,9 +432,14 @@ public class ElanUtils {
 
     // elan-interface-forwarding-entries Operational container
     public ElanInterfaceMac getElanInterfaceMacByInterfaceName(String interfaceName) {
+        return getElanInterfaceMacByInterfaceName(broker, interfaceName);
+    }
+
+    @Nullable
+    public static ElanInterfaceMac getElanInterfaceMacByInterfaceName(DataBroker dataBroker, String interfaceName) {
         InstanceIdentifier<ElanInterfaceMac> elanInterfaceId = getElanInterfaceMacEntriesOperationalDataPath(
                 interfaceName);
-        return read(broker, LogicalDatastoreType.OPERATIONAL, elanInterfaceId).orNull();
+        return read(dataBroker, LogicalDatastoreType.OPERATIONAL, elanInterfaceId).orNull();
     }
 
     /**
@@ -523,17 +509,6 @@ public class ElanUtils {
         return existingElanInfo.orNull();
     }
 
-    public EtreeLeafTagName getEtreeLeafTagByElanTag(long elanTag) {
-        InstanceIdentifier<ElanTagName> elanId = getElanInfoEntriesOperationalDataPath(elanTag);
-        Optional<ElanTagName> existingElanInfo = read(broker,
-                LogicalDatastoreType.OPERATIONAL, elanId);
-        if (existingElanInfo.isPresent()) {
-            ElanTagName elanTagName = existingElanInfo.get();
-            return elanTagName.getAugmentation(EtreeLeafTagName.class);
-        }
-        return null;
-    }
-
     public static InstanceIdentifier<ElanTagName> getElanInfoEntriesOperationalDataPath(long elanTag) {
         return InstanceIdentifier.builder(ElanTagNameMap.class).child(ElanTagName.class, new ElanTagNameKey(elanTag))
                 .build();
@@ -635,8 +610,13 @@ public class ElanUtils {
      * @return the elan mac table
      */
     public MacTable getElanMacTable(String elanName) {
+        return getElanMacTable(broker, elanName);
+    }
+
+    @Nullable
+    public static MacTable getElanMacTable(DataBroker dataBroker, String elanName) {
         InstanceIdentifier<MacTable> elanMacTableId = getElanMacTableOperationalDataPath(elanName);
-        return read(broker, LogicalDatastoreType.OPERATIONAL, elanMacTableId).orNull();
+        return read(dataBroker, LogicalDatastoreType.OPERATIONAL, elanMacTableId).orNull();
     }
 
     public static long getElanLocalBCGId(long elanTag) {
@@ -655,23 +635,11 @@ public class ElanUtils {
         return ElanConstants.ELAN_GID_MIN + etreeLeafTag % ElanConstants.ELAN_GID_MIN * 2;
     }
 
-    public static BigInteger getElanMetadataLabel(long elanTag) {
-        return MetaDataUtil.getElanTagMetadata(elanTag);
-    }
-
     public static BigInteger getElanMetadataLabel(long elanTag, boolean isSHFlagSet) {
         int shBit = isSHFlagSet ? 1 : 0;
         return BigInteger.valueOf(elanTag).shiftLeft(24).or(BigInteger.valueOf(shBit));
     }
 
-    public static BigInteger getElanMetadataLabel(long elanTag, int lportTag) {
-        return getElanMetadataLabel(elanTag).or(MetaDataUtil.getLportTagMetaData(lportTag));
-    }
-
-    public static BigInteger getElanMetadataMask() {
-        return MetaDataUtil.METADATA_MASK_SERVICE.or(MetaDataUtil.METADATA_MASK_LPORT_TAG);
-    }
-
     /**
      * Setting SMAC, DMAC, UDMAC in this DPN and optionally in other DPNs.
      *
@@ -727,7 +695,8 @@ public class ElanUtils {
         int lportTag = interfaceInfo.getInterfaceTag();
         // Matching metadata and eth_src fields
         List<MatchInfo> mkMatches = new ArrayList<>();
-        mkMatches.add(new MatchMetadata(getElanMetadataLabel(elanInfo.getElanTag(), lportTag), getElanMetadataMask()));
+        mkMatches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanInfo.getElanTag(), lportTag),
+                ElanHelper.getElanMetadataMask()));
         mkMatches.add(new MatchEthernetSource(new MacAddress(macAddress)));
         List<InstructionInfo> mkInstructions = new ArrayList<>();
         mkInstructions.add(new InstructionGotoTable(NwConstants.ELAN_DMAC_TABLE));
@@ -863,7 +832,7 @@ public class ElanUtils {
                     .getEgressActionsForInterface(getEgressActionInput);
             RpcResult<GetEgressActionsForInterfaceOutput> rpcResult = result.get();
             if (!rpcResult.isSuccessful()) {
-                LOG.warn("RPC Call to Get egress actions for interface {} returned with Errors {}", ifName,
+                LOG.debug("RPC Call to Get egress actions for interface {} returned with Errors {}", ifName,
                         rpcResult.getErrors());
             } else {
                 List<Action> actions = rpcResult.getResult().getAction();
@@ -927,13 +896,8 @@ public class ElanUtils {
         // TODO: Make sure that the same is performed against the ElanDevices.
     }
 
-    @SuppressWarnings("unchecked")
     public List<DpnInterfaces> getInvolvedDpnsInElan(String elanName) {
-        List<DpnInterfaces> dpns = elanInstanceManager.getElanDPNByName(elanName);
-        if (dpns == null) {
-            return Collections.emptyList();
-        }
-        return dpns;
+        return elanInstanceManager.getElanDPNByName(elanName);
     }
 
     private void setupLocalDmacFlow(long elanTag, BigInteger dpId, String ifName, String macAddress,
@@ -949,7 +913,7 @@ public class ElanUtils {
         EtreeInterface etreeInterface = getEtreeInterfaceByElanInterfaceName(broker, ifName);
         if (etreeInterface != null) {
             if (etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
-                EtreeLeafTagName etreeTagName = getEtreeLeafTagByElanTag(elanTag);
+                EtreeLeafTagName etreeTagName = elanEtreeUtils.getEtreeLeafTagByElanTag(elanTag);
                 if (etreeTagName == null) {
                     LOG.warn("Interface {} seems like it belongs to Etree but etreeTagName from elanTag {} is null",
                              ifName, elanTag);
@@ -1010,7 +974,7 @@ public class ElanUtils {
             ElanInstance elanInfo, long ifTag) {
 
         List<MatchInfo> mkMatches = new ArrayList<>();
-        mkMatches.add(new MatchMetadata(getElanMetadataLabel(elanTag), MetaDataUtil.METADATA_MASK_SERVICE));
+        mkMatches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanTag), MetaDataUtil.METADATA_MASK_SERVICE));
         mkMatches.add(new MatchEthernetDestination(new MacAddress(macAddress)));
 
         List<Instruction> mkInstructions = new ArrayList<>();
@@ -1035,8 +999,8 @@ public class ElanUtils {
         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 : ((isVxlan(elanInstance))
-                ? elanInstance.getSegmentationId() : 0);
+        long lportTagOrVni = !isOpenStackVniSemanticsEnforced() ? lportTag : isVxlan(elanInstance)
+                ? elanInstance.getSegmentationId() : 0;
         flowEntity = buildRemoteDmacFlowEntry(srcDpId, destDpId, lportTagOrVni, elanTag, macAddress, displayName,
                 elanInstance);
         mdsalManager.addFlowToTx(srcDpId, flowEntity, writeFlowGroupTx);
@@ -1052,7 +1016,7 @@ public class ElanUtils {
         EtreeInterface etreeInterface = getEtreeInterfaceByElanInterfaceName(broker, interfaceName);
         if (etreeInterface != null) {
             if (etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
-                EtreeLeafTagName etreeTagName = getEtreeLeafTagByElanTag(elanTag);
+                EtreeLeafTagName etreeTagName = elanEtreeUtils.getEtreeLeafTagByElanTag(elanTag);
                 if (etreeTagName == null) {
                     LOG.warn("Interface " + interfaceName
                             + " seems like it belongs to Etree but etreeTagName from elanTag " + elanTag + " is null.");
@@ -1090,7 +1054,7 @@ public class ElanUtils {
     public Flow buildRemoteDmacFlowEntry(BigInteger srcDpId, BigInteger destDpId, long lportTagOrVni, long elanTag,
             String macAddress, String displayName, ElanInstance elanInstance) throws ElanException {
         List<MatchInfo> mkMatches = new ArrayList<>();
-        mkMatches.add(new MatchMetadata(getElanMetadataLabel(elanTag), MetaDataUtil.METADATA_MASK_SERVICE));
+        mkMatches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanTag), MetaDataUtil.METADATA_MASK_SERVICE));
         mkMatches.add(new MatchEthernetDestination(new MacAddress(macAddress)));
 
         List<Instruction> mkInstructions = new ArrayList<>();
@@ -1101,12 +1065,12 @@ public class ElanUtils {
             if (isVlan(elanInstance) || isFlat(elanInstance)) {
                 String interfaceName = getExternalElanInterface(elanInstance.getElanInstanceName(), srcDpId);
                 if (null == interfaceName) {
-                    LOG.error("buildRemoteDmacFlowEntry: Could not find interfaceName for {} {}", srcDpId,
-                            elanInstance);
+                    LOG.info("buildRemoteDmacFlowEntry: Could not find interfaceName for {} {}", srcDpId,
+                        elanInstance);
                 }
                 actions = getEgressActionsForInterface(interfaceName, null);
             } else if (isVxlan(elanInstance)) {
-                actions = getInternalTunnelItmEgressAction(srcDpId, destDpId, lportTagOrVni);
+                actions = elanItmUtils.getInternalTunnelItmEgressAction(srcDpId, destDpId, lportTagOrVni);
             }
             mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
         } catch (Exception e) {
@@ -1160,7 +1124,7 @@ public class ElanUtils {
     private void executeEtreeDeleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
             boolean deleteSmac, String elanInstanceName, BigInteger srcdpId, Long elanTag, BigInteger dstDpId,
             WriteTransaction deleteFlowGroupTx) {
-        EtreeLeafTagName etreeLeafTag = getEtreeLeafTagByElanTag(elanTag);
+        EtreeLeafTagName etreeLeafTag = elanEtreeUtils.getEtreeLeafTagByElanTag(elanTag);
         if (etreeLeafTag != null) {
             executeDeleteMacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, elanInstanceName, srcdpId,
                     etreeLeafTag.getEtreeLeafTag().getValue(), dstDpId, deleteFlowGroupTx);
@@ -1234,18 +1198,19 @@ public class ElanUtils {
 
         // Add the ElanState in the elan-state operational data-store
         tx.put(LogicalDatastoreType.OPERATIONAL, getElanInstanceOperationalDataPath(elanInstanceName),
-                elanInfo, true);
+                elanInfo, WriteTransaction.CREATE_MISSING_PARENTS);
 
         // Add the ElanMacTable in the elan-mac-table operational data-store
         MacTable elanMacTable = new MacTableBuilder().setKey(new MacTableKey(elanInstanceName)).build();
         tx.put(LogicalDatastoreType.OPERATIONAL, getElanMacTableOperationalDataPath(elanInstanceName),
-                elanMacTable, true);
+                elanMacTable, WriteTransaction.CREATE_MISSING_PARENTS);
 
         ElanTagNameBuilder elanTagNameBuilder = new ElanTagNameBuilder().setElanTag(elanTag)
                 .setKey(new ElanTagNameKey(elanTag)).setName(elanInstanceName);
         long etreeLeafTag = -1;
         if (isEtreeInstance(elanInstanceAdded)) {
-            etreeLeafTag = retrieveNewElanTag(idManager, elanInstanceName + ElanConstants.LEAVES_POSTFIX);
+            etreeLeafTag = retrieveNewElanTag(idManager,elanInstanceName + ElanConstants
+                    .LEAVES_POSTFIX);
             EtreeLeafTagName etreeLeafTagName = new EtreeLeafTagNameBuilder()
                     .setEtreeLeafTag(new EtreeLeafTag(etreeLeafTag)).build();
             elanTagNameBuilder.addAugmentation(EtreeLeafTagName.class, etreeLeafTagName);
@@ -1296,32 +1261,9 @@ public class ElanUtils {
         return read(broker, LogicalDatastoreType.CONFIGURATION, node).isPresent();
     }
 
-    public static ServicesInfo getServiceInfo(String elanInstanceName, long elanTag, String interfaceName) {
-        int priority = ElanConstants.ELAN_SERVICE_PRIORITY;
-        int instructionKey = 0;
-        List<Instruction> instructions = new ArrayList<>();
-        instructions.add(MDSALUtil.buildAndGetWriteMetadaInstruction(getElanMetadataLabel(elanTag),
-                MetaDataUtil.METADATA_MASK_SERVICE, ++instructionKey));
-        instructions.add(MDSALUtil.buildAndGetGotoTableInstruction(NwConstants.ELAN_SMAC_TABLE, ++instructionKey));
-
-        short serviceIndex = ServiceIndex.getIndex(NwConstants.ELAN_SERVICE_NAME, NwConstants.ELAN_SERVICE_INDEX);
-        ServicesInfo serviceInfo = InterfaceServiceUtil.buildServiceInfo(
-                String.format("%s.%s", elanInstanceName, interfaceName), serviceIndex, priority,
-                NwConstants.COOKIE_ELAN_INGRESS_TABLE, instructions);
-        return serviceInfo;
-    }
-
-    public static <T extends DataObject> void syncWrite(DataBroker broker, LogicalDatastoreType datastoreType,
-            InstanceIdentifier<T> path, T data) {
-        WriteTransaction tx = broker.newWriteOnlyTransaction();
-        tx.put(datastoreType, path, data, true);
-        CheckedFuture<Void, TransactionCommitFailedException> futures = tx.submit();
-        try {
-            futures.get();
-        } catch (InterruptedException | ExecutionException e) {
-            LOG.error("Error writing to datastore (path, data) : ({}, {})", path, data);
-            throw new RuntimeException(e.getMessage());
-        }
+    public static ServicesInfo getServiceInfo(String elanInstanceName, String interfaceName) {
+        return InterfaceServiceUtil.buildServiceInfo(elanInstanceName + "." + interfaceName,
+                ElanConstants.ELAN_SERVICE_PRIORITY);
     }
 
     public static BoundServices getBoundServices(String serviceName, short servicePriority, int flowPriority,
@@ -1339,171 +1281,6 @@ public class ElanUtils {
                 .child(BoundServices.class, new BoundServicesKey(serviceIndex)).build();
     }
 
-    /**
-     * Builds the list of actions to be taken when sending the packet over a VxLan Tunnel Interface, such as setting
-     * the network VNI in the tunnel_id field.
-     *
-     * @param tunnelIfaceName
-     *            the tunnel iface name
-     * @param tunnelKey
-     *            the tunnel key
-     * @return the list
-     */
-    public List<Action> buildTunnelItmEgressActions(String tunnelIfaceName, Long tunnelKey) {
-        if (tunnelIfaceName != null && !tunnelIfaceName.isEmpty()) {
-            return buildItmEgressActions(tunnelIfaceName, tunnelKey);
-        }
-
-        return Collections.emptyList();
-    }
-
-    /**
-     * Builds the list of actions to be taken when sending the packet over external port such as tunnel, physical
-     * port etc.
-     *
-     * @param interfaceName
-     *            the interface name
-     * @param tunnelKey
-     *            can be VNI for VxLAN tunnel interfaces, Gre Key for GRE
-     *            tunnels, etc.
-     * @return the list
-     */
-    @SuppressWarnings("checkstyle:IllegalCatch")
-    public List<Action> buildItmEgressActions(String interfaceName, Long tunnelKey) {
-        List<Action> result = Collections.emptyList();
-        try {
-            GetEgressActionsForInterfaceInput getEgressActInput = new GetEgressActionsForInterfaceInputBuilder()
-                    .setIntfName(interfaceName).setTunnelKey(tunnelKey).build();
-
-            Future<RpcResult<GetEgressActionsForInterfaceOutput>> egressActionsOutputFuture = interfaceManagerRpcService
-                    .getEgressActionsForInterface(getEgressActInput);
-            if (egressActionsOutputFuture.get().isSuccessful()) {
-                GetEgressActionsForInterfaceOutput egressActionsOutput = egressActionsOutputFuture.get().getResult();
-                result = egressActionsOutput.getAction();
-            }
-        } catch (Exception e) {
-            LOG.error("Error in RPC call getEgressActionsForInterface {}", e);
-        }
-
-        if (result == null || result.size() == 0) {
-            LOG.warn("Could not build Egress actions for interface {} and tunnelId {}", interfaceName, tunnelKey);
-        }
-        return result;
-    }
-
-    /**
-     * Builds the list of actions to be taken when sending the packet over an
-     * external VxLan tunnel interface, such as stamping the VNI on the VxLAN
-     * header, setting the vlanId if it proceeds and output the packet over the
-     * right port.
-     *
-     * @param srcDpnId
-     *            Dpn where the tunnelInterface is located
-     * @param torNode
-     *            NodeId of the ExternalDevice where the packet must be sent to.
-     * @param vni
-     *            Vni to be stamped on the VxLAN Header.
-     * @return the external itm egress action
-     */
-    public List<Action> getExternalTunnelItmEgressAction(BigInteger srcDpnId, NodeId torNode, long vni) {
-        List<Action> result = Collections.emptyList();
-
-        GetExternalTunnelInterfaceNameInput input = new GetExternalTunnelInterfaceNameInputBuilder()
-                .setDestinationNode(torNode.getValue()).setSourceNode(srcDpnId.toString())
-                .setTunnelType(TunnelTypeVxlan.class).build();
-        Future<RpcResult<GetExternalTunnelInterfaceNameOutput>> output = itmRpcService
-                .getExternalTunnelInterfaceName(input);
-        try {
-            if (output.get().isSuccessful()) {
-                GetExternalTunnelInterfaceNameOutput tunnelInterfaceNameOutput = output.get().getResult();
-                String tunnelIfaceName = tunnelInterfaceNameOutput.getInterfaceName();
-                LOG.debug("Received tunnelInterfaceName from getTunnelInterfaceName RPC {}", tunnelIfaceName);
-
-                result = buildTunnelItmEgressActions(tunnelIfaceName, vni);
-            }
-
-        } catch (InterruptedException | ExecutionException e) {
-            LOG.error("Error in RPC call getTunnelInterfaceName {}", e);
-        }
-
-        return result;
-    }
-
-    public List<Action> getExternalTunnelItmEgressAction(BigInteger srcDpnId, String nexthopIP, long vni) {
-        List<Action> result = Collections.emptyList();
-
-        GetExternalTunnelInterfaceNameInput input = new GetExternalTunnelInterfaceNameInputBuilder()
-                .setDestinationNode(nexthopIP).setSourceNode(srcDpnId.toString())
-                .setTunnelType(TunnelTypeVxlan.class).build();
-        Future<RpcResult<GetExternalTunnelInterfaceNameOutput>> output = itmRpcService
-                .getExternalTunnelInterfaceName(input);
-        try {
-            if (output.get().isSuccessful()) {
-                GetExternalTunnelInterfaceNameOutput tunnelInterfaceNameOutput = output.get().getResult();
-                String tunnelIfaceName = tunnelInterfaceNameOutput.getInterfaceName();
-                LOG.debug("Received tunnelInterfaceName from getTunnelInterfaceName RPC {}", tunnelIfaceName);
-
-                result = buildTunnelItmEgressActions(tunnelIfaceName, vni);
-            }
-
-        } catch (InterruptedException | ExecutionException e) {
-            LOG.error("Error in RPC call getTunnelInterfaceName {}", e);
-        }
-
-        return result;
-    }
-
-    /**
-     * Builds the list of actions to be taken when sending the packet over an internal VxLAN tunnel interface, such
-     * as setting the serviceTag/segmentationID on the VNI field of the VxLAN header, setting the vlanId if it proceeds
-     * and output the packet over the right port.
-     *
-     * @param sourceDpnId
-     *            Dpn where the tunnelInterface is located
-     * @param destinationDpnId
-     *            Dpn where the packet must be sent to. It is used here in order
-     *            to select the right tunnel interface.
-     * @param tunnelKey
-     *            Tunnel key to be sent on the VxLAN header.
-     * @return the internal itm egress action
-     */
-    public List<Action> getInternalTunnelItmEgressAction(BigInteger sourceDpnId, BigInteger destinationDpnId, long
-            tunnelKey) {
-        List<Action> result = Collections.emptyList();
-        LOG.trace("In getInternalItmEgressAction Action source {}, destination {}, serviceTag/Vni {}", sourceDpnId,
-                destinationDpnId, tunnelKey);
-        Class<? extends TunnelTypeBase> tunType = TunnelTypeVxlan.class;
-        GetTunnelInterfaceNameInput input = new GetTunnelInterfaceNameInputBuilder()
-                .setDestinationDpid(destinationDpnId).setSourceDpid(sourceDpnId).setTunnelType(tunType).build();
-        Future<RpcResult<GetTunnelInterfaceNameOutput>> output = itmRpcService.getTunnelInterfaceName(input);
-        try {
-            if (output.get().isSuccessful()) {
-                GetTunnelInterfaceNameOutput tunnelInterfaceNameOutput = output.get().getResult();
-                String tunnelIfaceName = tunnelInterfaceNameOutput.getInterfaceName();
-                LOG.info("Received tunnelInterfaceName from getTunnelInterfaceName RPC {}", tunnelIfaceName);
-                result = buildTunnelItmEgressActions(tunnelIfaceName, tunnelKey);
-            } else {
-                LOG.trace("Tunnel interface doesn't exist between srcDpId {} dstDpId {}", sourceDpnId,
-                        destinationDpnId);
-            }
-        } catch (InterruptedException | ExecutionException e) {
-            LOG.error("Error in RPC call getTunnelInterfaceName {}", e);
-        }
-        return result;
-    }
-
-    /**
-     * Build the list of actions to be taken when sending the packet to external
-     * (physical) port.
-     *
-     * @param interfaceName
-     *            Interface name
-     * @return the external port itm egress actions
-     */
-    public List<Action> getExternalPortItmEgressAction(String interfaceName) {
-        return buildItmEgressActions(interfaceName, null);
-    }
-
     public static List<MatchInfo> getTunnelMatchesForServiceId(int elanTag) {
         List<MatchInfo> mkMatches = new ArrayList<>();
         // Matching metadata
@@ -1580,94 +1357,10 @@ public class ElanUtils {
      */
     public List<ExternalTunnel> getAllExternalTunnels(LogicalDatastoreType datastoreType) {
         InstanceIdentifier<ExternalTunnelList> iid = InstanceIdentifier.builder(ExternalTunnelList.class).build();
-        return read(broker, datastoreType, iid).transform(ExternalTunnelList::getExternalTunnel).or(
+        return read(broker, datastoreType, iid).toJavaUtil().map(ExternalTunnelList::getExternalTunnel).orElse(
                 Collections.emptyList());
     }
 
-    /**
-     * Installs a Flow in the specified DPN's DMAC table. The flow is for a MAC
-     * that is connected remotely in an External Device (TOR) and that is
-     * accessible through an external tunnel. It also installs the flow for
-     * dropping the packet if it came over an ITM tunnel (that is, if the
-     * Split-Horizon flag is set)
-     *
-     * @param dpnId
-     *            Id of the DPN where the flow must be installed
-     * @param extDeviceNodeId
-     *            the ext device node id
-     * @param elanTag
-     *            the elan tag
-     * @param vni
-     *            the vni
-     * @param macAddress
-     *            the mac address
-     * @param displayName
-     *            the display name
-     * @param interfaceName
-     *            the interface name
-     *
-     * @return the dmac flows
-     * @throws ElanException in case of issues creating the flow objects
-     */
-    public List<ListenableFuture<Void>> installDmacFlowsToExternalRemoteMac(BigInteger dpnId,
-            String extDeviceNodeId, Long elanTag, Long vni, String macAddress, String displayName,
-            String interfaceName) throws ElanException {
-        List<ListenableFuture<Void>> futures = new ArrayList<>();
-        synchronized (getElanMacDPNKey(elanTag, macAddress, dpnId)) {
-            Flow flow = buildDmacFlowForExternalRemoteMac(dpnId, extDeviceNodeId, elanTag, vni, macAddress,
-                    displayName);
-            futures.add(mdsalManager.installFlow(dpnId, flow));
-
-            Flow dropFlow = buildDmacFlowDropIfPacketComingFromTunnel(dpnId, extDeviceNodeId, elanTag, macAddress);
-            futures.add(mdsalManager.installFlow(dpnId, dropFlow));
-            installEtreeDmacFlowsToExternalRemoteMac(dpnId, extDeviceNodeId, elanTag, vni, macAddress, displayName,
-                    interfaceName, futures);
-        }
-        return futures;
-    }
-
-    private void installEtreeDmacFlowsToExternalRemoteMac(BigInteger dpnId, String extDeviceNodeId, Long elanTag,
-            Long vni, String macAddress, String displayName, String interfaceName,
-            List<ListenableFuture<Void>> futures) throws ElanException {
-        EtreeLeafTagName etreeLeafTag = getEtreeLeafTagByElanTag(elanTag);
-        if (etreeLeafTag != null) {
-            buildEtreeDmacFlowDropIfPacketComingFromTunnel(dpnId, extDeviceNodeId, elanTag, macAddress, futures,
-                    etreeLeafTag);
-            buildEtreeDmacFlowForExternalRemoteMac(dpnId, extDeviceNodeId, vni, macAddress, displayName, interfaceName,
-                    futures, etreeLeafTag);
-        }
-    }
-
-    private void buildEtreeDmacFlowForExternalRemoteMac(BigInteger dpnId, String extDeviceNodeId, Long vni,
-            String macAddress, String displayName, String interfaceName, List<ListenableFuture<Void>> futures,
-            EtreeLeafTagName etreeLeafTag) throws ElanException {
-        boolean isRoot = false;
-        if (interfaceName == null) {
-            isRoot = true;
-        } else {
-            EtreeInterface etreeInterface = getEtreeInterfaceByElanInterfaceName(broker, interfaceName);
-            if (etreeInterface != null) {
-                if (etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
-                    isRoot = true;
-                }
-            }
-        }
-        if (isRoot) {
-            Flow flow = buildDmacFlowForExternalRemoteMac(dpnId, extDeviceNodeId,
-                    etreeLeafTag.getEtreeLeafTag().getValue(), vni, macAddress, displayName);
-            futures.add(mdsalManager.installFlow(dpnId, flow));
-        }
-    }
-
-    private void buildEtreeDmacFlowDropIfPacketComingFromTunnel(BigInteger dpnId, String extDeviceNodeId,
-            Long elanTag, String macAddress, List<ListenableFuture<Void>> futures, EtreeLeafTagName etreeLeafTag) {
-        if (etreeLeafTag != null) {
-            Flow dropFlow = buildDmacFlowDropIfPacketComingFromTunnel(dpnId, extDeviceNodeId,
-                    etreeLeafTag.getEtreeLeafTag().getValue(), macAddress);
-            futures.add(mdsalManager.installFlow(dpnId, dropFlow));
-        }
-    }
-
     public static List<MatchInfo> buildMatchesForElanTagShFlagAndDstMac(long elanTag, boolean shFlag, String macAddr) {
         List<MatchInfo> mkMatches = new ArrayList<>();
         mkMatches.add(
@@ -1676,194 +1369,6 @@ public class ElanUtils {
         return mkMatches;
     }
 
-    /**
-     * Builds a Flow to be programmed in a DPN's DMAC table. This method must be
-     * used when the MAC is located in an External Device (TOR). The flow
-     * matches on the specified MAC and 1) sends the packet over the CSS-TOR
-     * tunnel if SHFlag is not set, or 2) drops it if SHFlag is set (what means
-     * the packet came from an external tunnel)
-     *
-     * @param dpId
-     *            DPN whose DMAC table is going to be modified
-     * @param extDeviceNodeId
-     *            Hwvtep node where the mac is attached to
-     * @param elanTag
-     *            ElanId to which the MAC is being added to
-     * @param vni
-     *            the vni
-     * @param dstMacAddress
-     *            The mac address to be programmed
-     * @param displayName
-     *            the display name
-     * @return the flow
-     * @throws ElanException in case of issues creating the flow objects
-     */
-    @SuppressWarnings("checkstyle:IllegalCatch")
-    public Flow buildDmacFlowForExternalRemoteMac(BigInteger dpId, String extDeviceNodeId, long elanTag,
-            Long vni, String dstMacAddress, String displayName) throws ElanException {
-        List<MatchInfo> mkMatches = buildMatchesForElanTagShFlagAndDstMac(elanTag, /* shFlag */ false, dstMacAddress);
-        List<Instruction> mkInstructions = new ArrayList<>();
-        try {
-            List<Action> actions = getExternalTunnelItmEgressAction(dpId, new NodeId(extDeviceNodeId), vni);
-            mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
-        } catch (Exception e) {
-            LOG.error("Could not get Egress Actions for DpId=" + dpId + ", externalNode=" + extDeviceNodeId, e);
-        }
-
-        Flow flow = MDSALUtil.buildFlowNew(NwConstants.ELAN_DMAC_TABLE,
-                getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, extDeviceNodeId, dstMacAddress, elanTag,
-                        false),
-                20, /* prio */
-                displayName, 0, /* idleTimeout */
-                0, /* hardTimeout */
-                ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(BigInteger.valueOf(elanTag)), mkMatches, mkInstructions);
-
-        return flow;
-    }
-
-    /**
-     * Builds the flow that drops the packet if it came through an external
-     * tunnel, that is, if the Split-Horizon flag is set.
-     *
-     * @param dpnId
-     *            DPN whose DMAC table is going to be modified
-     * @param extDeviceNodeId
-     *            Hwvtep node where the mac is attached to
-     * @param elanTag
-     *            ElanId to which the MAC is being added to
-     * @param dstMacAddress
-     *            The mac address to be programmed
-     */
-    private static Flow buildDmacFlowDropIfPacketComingFromTunnel(BigInteger dpnId, String extDeviceNodeId,
-            Long elanTag, String dstMacAddress) {
-        List<MatchInfo> mkMatches = buildMatchesForElanTagShFlagAndDstMac(elanTag, /* shFlag */ true, dstMacAddress);
-        List<Instruction> mkInstructions = MDSALUtil.buildInstructionsDrop();
-        String flowId = getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpnId, extDeviceNodeId, dstMacAddress,
-                elanTag, true);
-        Flow flow = MDSALUtil.buildFlowNew(NwConstants.ELAN_DMAC_TABLE, flowId, 20, /* prio */
-                "Drop", 0, /* idleTimeout */
-                0, /* hardTimeout */
-                ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(BigInteger.valueOf(elanTag)), mkMatches, mkInstructions);
-
-        return flow;
-    }
-
-    private static String getDmacDropFlowId(Long elanTag, String dstMacAddress) {
-        return new StringBuilder(NwConstants.ELAN_DMAC_TABLE).append(elanTag).append(dstMacAddress).append("Drop")
-                .toString();
-    }
-
-    /**
-     * Installs or removes flows in DMAC table for MACs that are/were located in
-     * an external Elan Device.
-     *
-     * @param dpId
-     *            Id of the DPN where the DMAC table is going to be modified
-     * @param extNodeId
-     *            Id of the External Device where the MAC is located
-     * @param elanTag
-     *            Id of the ELAN
-     * @param vni
-     *            VNI of the LogicalSwitch to which the MAC belongs to, and that
-     *            is associated with the ELAN
-     * @param macAddress
-     *            the mac address
-     * @param elanInstanceName
-     *            the elan instance name
-     * @param addOrRemove
-     *            Indicates if flows must be installed or removed.
-     * @param interfaceName
-     *            the interface name
-     * @throws ElanException in case of issues creating the flow objects
-     * @see org.opendaylight.genius.mdsalutil.MDSALUtil.MdsalOp
-     */
-    public void setupDmacFlowsToExternalRemoteMac(BigInteger dpId, String extNodeId, Long elanTag, Long vni,
-            String macAddress, String elanInstanceName, MdsalOp addOrRemove, String interfaceName)
-            throws ElanException {
-        if (addOrRemove == MdsalOp.CREATION_OP) {
-            installDmacFlowsToExternalRemoteMac(dpId, extNodeId, elanTag, vni, macAddress, elanInstanceName,
-                    interfaceName);
-        } else if (addOrRemove == MdsalOp.REMOVAL_OP) {
-            deleteDmacFlowsToExternalMac(elanTag, dpId, extNodeId, macAddress);
-        }
-    }
-
-    /**
-     * Delete dmac flows to external mac.
-     *
-     * @param elanTag
-     *            the elan tag
-     * @param dpId
-     *            the dp id
-     * @param extDeviceNodeId
-     *            the ext device node id
-     * @param macToRemove
-     *            the mac to remove
-     * @return dmac flow
-     */
-    public List<ListenableFuture<Void>> deleteDmacFlowsToExternalMac(long elanTag, BigInteger dpId,
-            String extDeviceNodeId, String macToRemove) {
-        List<ListenableFuture<Void>> futures = new ArrayList<>();
-        synchronized (getElanMacDPNKey(elanTag, macToRemove, dpId)) {
-            // Removing the flows that sends the packet on an external tunnel
-            removeFlowThatSendsThePacketOnAnExternalTunnel(elanTag, dpId, extDeviceNodeId, macToRemove, futures);
-
-            // And now removing the drop flow
-            removeTheDropFlow(elanTag, dpId, extDeviceNodeId, macToRemove, futures);
-
-            deleteEtreeDmacFlowsToExternalMac(elanTag, dpId, extDeviceNodeId, macToRemove, futures);
-        }
-        return futures;
-    }
-
-    private void deleteEtreeDmacFlowsToExternalMac(long elanTag, BigInteger dpId, String extDeviceNodeId,
-            String macToRemove, List<ListenableFuture<Void>> futures) {
-        EtreeLeafTagName etreeLeafTag = getEtreeLeafTagByElanTag(elanTag);
-        if (etreeLeafTag != null) {
-            removeFlowThatSendsThePacketOnAnExternalTunnel(etreeLeafTag.getEtreeLeafTag().getValue(), dpId,
-                    extDeviceNodeId, macToRemove, futures);
-            removeTheDropFlow(etreeLeafTag.getEtreeLeafTag().getValue(), dpId, extDeviceNodeId, macToRemove, futures);
-        }
-    }
-
-    private void removeTheDropFlow(long elanTag, BigInteger dpId, String extDeviceNodeId, String macToRemove,
-            List<ListenableFuture<Void>> futures) {
-        String flowId = getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, extDeviceNodeId, macToRemove,
-                elanTag, true);
-        Flow flowToRemove = new FlowBuilder().setId(new FlowId(flowId)).setTableId(NwConstants.ELAN_DMAC_TABLE).build();
-        futures.add(mdsalManager.removeFlow(dpId, flowToRemove));
-    }
-
-    private void removeFlowThatSendsThePacketOnAnExternalTunnel(long elanTag, BigInteger dpId,
-            String extDeviceNodeId, String macToRemove, List<ListenableFuture<Void>> futures) {
-        String flowId = getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, extDeviceNodeId, macToRemove,
-                elanTag, false);
-        Flow flowToRemove = new FlowBuilder().setId(new FlowId(flowId)).setTableId(NwConstants.ELAN_DMAC_TABLE).build();
-        futures.add(mdsalManager.removeFlow(dpId, flowToRemove));
-    }
-
-    /**
-     * Gets the dpid from interface.
-     *
-     * @param interfaceName
-     *            the interface name
-     * @return the dpid from interface
-     */
-    public BigInteger getDpidFromInterface(String interfaceName) {
-        BigInteger dpId = null;
-        Future<RpcResult<GetDpidFromInterfaceOutput>> output = interfaceManagerRpcService
-                .getDpidFromInterface(new GetDpidFromInterfaceInputBuilder().setIntfName(interfaceName).build());
-        try {
-            RpcResult<GetDpidFromInterfaceOutput> rpcResult = output.get();
-            if (rpcResult.isSuccessful()) {
-                dpId = rpcResult.getResult().getDpid();
-            }
-        } catch (NullPointerException | InterruptedException | ExecutionException e) {
-            LOG.error("Failed to get the DPN ID: {} for interface {}: {} ", dpId, interfaceName, e);
-        }
-        return dpId;
-    }
-
     /**
      * Checks if is interface operational.
      *
@@ -1936,7 +1441,7 @@ public class ElanUtils {
 
     public static boolean isVxlanNetwork(DataBroker broker, String elanInstanceName) {
         ElanInstance elanInstance = getElanInstanceByName(broker, elanInstanceName);
-        return (elanInstance != null && isVxlan(elanInstance));
+        return elanInstance != null && isVxlan(elanInstance);
     }
 
     public static boolean isVxlan(ElanInstance elanInstance) {
@@ -1995,25 +1500,27 @@ public class ElanUtils {
                 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeFlat.class);
     }
 
-    public void handleDmacRedirectToDispatcherFlows(Long elanTag, String displayName,
-            String macAddress, int addOrRemove, List<BigInteger> dpnIds) {
+    public void addDmacRedirectToDispatcherFlows(Long elanTag, String displayName,
+            String macAddress, List<BigInteger> dpnIds) {
         for (BigInteger dpId : dpnIds) {
-            if (addOrRemove == NwConstants.ADD_FLOW) {
-                WriteTransaction writeTx = broker.newWriteOnlyTransaction();
-                mdsalManager.addFlowToTx(buildDmacRedirectToDispatcherFlow(dpId, macAddress, displayName, elanTag),
-                        writeTx);
-                writeTx.submit();
-            } else {
-                String flowId = getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, macAddress, elanTag);
-                mdsalManager.removeFlow(dpId, MDSALUtil.buildFlow(NwConstants.ELAN_DMAC_TABLE, flowId));
-            }
+            WriteTransaction writeTx = broker.newWriteOnlyTransaction();
+            mdsalManager.addFlowToTx(buildDmacRedirectToDispatcherFlow(dpId, macAddress, displayName, elanTag),
+                    writeTx);
+            writeTx.submit();
+        }
+    }
+
+    public void removeDmacRedirectToDispatcherFlows(Long elanTag, String macAddress, List<BigInteger> dpnIds) {
+        for (BigInteger dpId : dpnIds) {
+            String flowId = getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, macAddress, elanTag);
+            mdsalManager.removeFlow(dpId, MDSALUtil.buildFlow(NwConstants.ELAN_DMAC_TABLE, flowId));
         }
     }
 
     public static FlowEntity buildDmacRedirectToDispatcherFlow(BigInteger dpId, String dstMacAddress,
             String displayName, long elanTag) {
         List<MatchInfo> matches = new ArrayList<>();
-        matches.add(new MatchMetadata(getElanMetadataLabel(elanTag), MetaDataUtil.METADATA_MASK_SERVICE));
+        matches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanTag), MetaDataUtil.METADATA_MASK_SERVICE));
         matches.add(new MatchEthernetDestination(new MacAddress(dstMacAddress)));
         List<InstructionInfo> instructions = new ArrayList<>();
         List<ActionInfo> actions = new ArrayList<>();
@@ -2032,7 +1539,7 @@ public class ElanUtils {
      * Install SMAC and DMAC flows.
      */
     public void addMacEntryToDsAndSetupFlows(IInterfaceManager interfaceManager, String interfaceName,
-            String macAddress, String elanName, WriteTransaction tx, WriteTransaction flowWritetx, int macTimeOut)
+            String macAddress, String elanName, WriteTransaction interfaceTx, WriteTransaction flowTx, int macTimeOut)
             throws ElanException {
         LOG.trace("Adding mac address {} and interface name {} to ElanInterfaceForwardingEntries and "
             + "ElanForwardingTables DS", macAddress, interfaceName);
@@ -2043,12 +1550,12 @@ public class ElanUtils {
                 .setIsStaticAddress(false).build();
         InstanceIdentifier<MacEntry> macEntryId = ElanUtils
                 .getInterfaceMacEntriesIdentifierOperationalDataPath(interfaceName, physAddress);
-        tx.put(LogicalDatastoreType.OPERATIONAL, macEntryId, macEntry);
+        interfaceTx.put(LogicalDatastoreType.OPERATIONAL, macEntryId, macEntry);
         InstanceIdentifier<MacEntry> elanMacEntryId = ElanUtils.getMacEntryOperationalDataPath(elanName, physAddress);
-        tx.put(LogicalDatastoreType.OPERATIONAL, elanMacEntryId, macEntry);
+        interfaceTx.put(LogicalDatastoreType.OPERATIONAL, elanMacEntryId, macEntry);
         ElanInstance elanInstance = ElanUtils.getElanInstanceByName(broker, elanName);
         setupMacFlows(elanInstance, interfaceManager.getInterfaceInfo(interfaceName), macTimeOut, macAddress, true,
-                flowWritetx);
+                flowTx);
     }
 
     /**
@@ -2056,18 +1563,18 @@ public class ElanUtils {
      * Remove SMAC and DMAC flows.
      */
     public void deleteMacEntryFromDsAndRemoveFlows(IInterfaceManager interfaceManager, String interfaceName,
-            String macAddress, String elanName, WriteTransaction tx, WriteTransaction deleteFlowTx) {
+            String macAddress, String elanName, WriteTransaction interfaceTx, WriteTransaction flowTx) {
         LOG.trace("Deleting mac address {} and interface name {} from ElanInterfaceForwardingEntries "
                 + "and ElanForwardingTables DS", macAddress, interfaceName);
         PhysAddress physAddress = new PhysAddress(macAddress);
         MacEntry macEntry = getInterfaceMacEntriesOperationalDataPath(interfaceName, physAddress);
         InterfaceInfo interfaceInfo = interfaceManager.getInterfaceInfo(interfaceName);
         if (macEntry != null && interfaceInfo != null) {
-            deleteMacFlows(ElanUtils.getElanInstanceByName(broker, elanName), interfaceInfo, macEntry, deleteFlowTx);
+            deleteMacFlows(ElanUtils.getElanInstanceByName(broker, elanName), interfaceInfo, macEntry, flowTx);
         }
-        tx.delete(LogicalDatastoreType.OPERATIONAL,
+        interfaceTx.delete(LogicalDatastoreType.OPERATIONAL,
                 ElanUtils.getInterfaceMacEntriesIdentifierOperationalDataPath(interfaceName, physAddress));
-        tx.delete(LogicalDatastoreType.OPERATIONAL,
+        interfaceTx.delete(LogicalDatastoreType.OPERATIONAL,
                 ElanUtils.getMacEntryOperationalDataPath(elanName, physAddress));
     }
 
@@ -2098,7 +1605,7 @@ public class ElanUtils {
         return elanMacKey.intern();
     }
 
-
+    // TODO This should return a collection of futures
     public static void addToListenableFutureIfTxException(RuntimeException exception,
             List<ListenableFuture<Void>> futures) {
         Throwable cause = exception.getCause();
@@ -2242,12 +1749,58 @@ public class ElanUtils {
 
     public static void removeElanInterfaceToElanInstanceCache(String elanInstanceName, String interfaceName) {
         Set<String> elanInterfaces = elanInstanceToInterfacesCache.get(elanInstanceName);
-        if (!elanInterfaces.isEmpty()) {
-            elanInterfaces.remove(interfaceName);
+        if (elanInterfaces == null || elanInterfaces.isEmpty()) {
+            return;
+        }
+        elanInterfaces.remove(interfaceName);
+    }
+
+    @Nonnull public static Set<String> removeAndGetElanInterfaces(String elanInstanceName) {
+        Set<String> removed = elanInstanceToInterfacesCache.remove(elanInstanceName);
+        return removed != null ? removed : Collections.emptySet();
+    }
+
+    public static InstanceIdentifier<Flow> getFlowIid(Flow flow, BigInteger dpnId) {
+        FlowKey flowKey = new FlowKey(new FlowId(flow.getId()));
+        org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId nodeId =
+                new org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId("openflow:" + dpnId);
+        org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node nodeDpn =
+                new NodeBuilder().setId(nodeId).setKey(new NodeKey(nodeId)).build();
+        return InstanceIdentifier.builder(Nodes.class)
+                .child(org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node.class,
+                        nodeDpn.getKey()).augmentation(FlowCapableNode.class)
+                .child(Table.class, new TableKey(flow.getTableId())).child(Flow.class, flowKey).build();
+    }
+
+    public static String getElanInterfaceJobKey(String interfaceName) {
+        return "elaninterface-" + interfaceName;
+    }
+
+    public void addArpResponderFlow(BigInteger dpnId, String ingressInterfaceName, String ipAddress, String macAddress,
+            int lportTag, List<Instruction> instructions) {
+        LOG.info("Installing the ARP responder flow on DPN {} for Interface {} with MAC {} & IP {}", dpnId,
+                ingressInterfaceName, macAddress, ipAddress);
+        ElanInterface elanIface = getElanInterfaceByElanInterfaceName(broker, ingressInterfaceName);
+        ElanInstance elanInstance = getElanInstanceByName(broker, elanIface.getElanInstanceName());
+        if (elanInstance == null) {
+            LOG.debug("addArpResponderFlow: elanInstance is null, Failed to install arp responder flow for Interface {}"
+                      + " with MAC {} & IP {}", dpnId,
+                ingressInterfaceName, macAddress, ipAddress);
+            return;
         }
+        String flowId = ArpResponderUtil.getFlowId(lportTag, ipAddress);
+        ArpResponderUtil.installFlow(mdsalManager, dpnId, flowId, flowId, NwConstants.DEFAULT_ARP_FLOW_PRIORITY,
+                ArpResponderUtil.generateCookie(lportTag, ipAddress),
+                ArpResponderUtil.getMatchCriteria(lportTag, elanInstance, ipAddress), instructions);
+        LOG.info("Installed the ARP Responder flow for Interface {}", ingressInterfaceName);
     }
 
-    public static Set<String> removeAndGetElanInterfaces(String elanInstanceName) {
-        return elanInstanceToInterfacesCache.remove(elanInstanceName);
+    public void removeArpResponderFlow(BigInteger dpnId, String ingressInterfaceName, String ipAddress,
+            int lportTag) {
+        LOG.info("Removing the ARP responder flow on DPN {} of Interface {} with IP {}", dpnId, ingressInterfaceName,
+                ipAddress);
+        ArpResponderUtil.removeFlow(mdsalManager, dpnId, ArpResponderUtil.getFlowId(lportTag, ipAddress));
     }
 }
+
+