Optional clean-up
[netvirt.git] / vpnservice / elanmanager / elanmanager-impl / src / main / java / org / opendaylight / netvirt / elan / utils / ElanUtils.java
old mode 100644 (file)
new mode 100755 (executable)
index 4c57ee6..18b3876
@@ -12,22 +12,31 @@ 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 java.math.BigInteger;
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.ExecutionException;
 import java.util.concurrent.Future;
+
 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;
 import org.opendaylight.genius.interfacemanager.globals.InterfaceInfo;
 import org.opendaylight.genius.interfacemanager.globals.InterfaceServiceUtil;
+import org.opendaylight.genius.interfacemanager.interfaces.IInterfaceManager;
 import org.opendaylight.genius.itm.globals.ITMConstants;
+import org.opendaylight.genius.mdsalutil.ActionInfo;
+import org.opendaylight.genius.mdsalutil.ActionType;
 import org.opendaylight.genius.mdsalutil.FlowEntity;
 import org.opendaylight.genius.mdsalutil.InstructionInfo;
 import org.opendaylight.genius.mdsalutil.InstructionType;
@@ -38,9 +47,13 @@ import org.opendaylight.genius.mdsalutil.MatchInfo;
 import org.opendaylight.genius.mdsalutil.MetaDataUtil;
 import org.opendaylight.genius.mdsalutil.NwConstants;
 import org.opendaylight.genius.mdsalutil.interfaces.IMdsalApiManager;
+import org.opendaylight.genius.utils.ServiceIndex;
+import org.opendaylight.netvirt.elan.ElanException;
 import org.opendaylight.netvirt.elan.internal.ElanInstanceManager;
-import org.opendaylight.netvirt.elan.internal.ElanServiceProvider;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.Interfaces;
+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.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.InterfacesState;
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface;
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface.AdminStatus;
@@ -60,7 +73,6 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.
 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406.IfIndexesInterfaceMap;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406._if.indexes._interface.map.IfIndexInterface;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406._if.indexes._interface.map.IfIndexInterfaceKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.IfExternal;
 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;
@@ -68,6 +80,7 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpc
 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;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.OdlInterfaceRpcService;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceBindings;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceModeIngress;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceTypeFlowBased;
@@ -90,12 +103,20 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.G
 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.NodeKey;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInstance;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInstanceBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInterface;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInterface.EtreeInterfaceType;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeLeafTag;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeLeafTagName;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeLeafTagNameBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanDpnInterfaces;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanForwardingTables;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInstances;
@@ -127,6 +148,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.tag.name.map.ElanTagNameBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.tag.name.map.ElanTagNameKey;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.forwarding.entries.MacEntry;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.forwarding.entries.MacEntryBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.forwarding.entries.MacEntryKey;
 import org.opendaylight.yangtools.yang.binding.DataObject;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
@@ -137,16 +159,20 @@ import org.slf4j.LoggerFactory;
 
 public class ElanUtils {
 
-    private static ElanServiceProvider elanServiceProvider;
     private static final Logger LOG = LoggerFactory.getLogger(ElanUtils.class);
 
-    public static void setElanServiceProvider(ElanServiceProvider serviceProvider) {
-        elanServiceProvider = serviceProvider;
-    }
+    private static Map<String, ElanInstance> elanInstanceLocalCache = new ConcurrentHashMap<>();
+    private static Map<String, ElanInterface> elanInterfaceLocalCache = new ConcurrentHashMap<>();
 
-    public static ElanServiceProvider getElanServiceProvider() {
-        return elanServiceProvider;
-    }
+    private final DataBroker broker;
+    private final IMdsalApiManager mdsalManager;
+    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;
 
     public static final FutureCallback<Void> DEFAULT_CALLBACK = new FutureCallback<Void>() {
         @Override
@@ -160,6 +186,66 @@ public class ElanUtils {
         }
     };
 
+    public ElanUtils(DataBroker dataBroker, IMdsalApiManager mdsalManager, ElanInstanceManager elanInstanceManager,
+                     OdlInterfaceRpcService interfaceManagerRpcService, ItmRpcService itmRpcService,
+                     ElanInterfaceManager elanInterfaceManager,
+                     EntityOwnershipService entityOwnershipService, IInterfaceManager interfaceManager) {
+        this.broker = dataBroker;
+        this.mdsalManager = mdsalManager;
+        this.elanInstanceManager = elanInstanceManager;
+        this.interfaceManagerRpcService = interfaceManagerRpcService;
+        this.itmRpcService = itmRpcService;
+        this.interfaceManager = interfaceManager;
+
+        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 ElanL2GatewayUtils getElanL2GatewayUtils() {
+        return elanL2GatewayUtils;
+    }
+
+    public ElanL2GatewayMulticastUtils getElanL2GatewayMulticastUtils() {
+        return elanL2GatewayMulticastUtils;
+    }
+
+    public L2GatewayConnectionUtils getL2GatewayConnectionUtils() {
+        return l2GatewayConnectionUtils;
+    }
+
+    public static void addElanInstanceIntoCache(String elanInstanceName, ElanInstance elanInstance) {
+        elanInstanceLocalCache.put(elanInstanceName, elanInstance);
+    }
+
+    public static void removeElanInstanceFromCache(String elanInstanceName) {
+        elanInstanceLocalCache.remove(elanInstanceName);
+    }
+
+    public static ElanInstance getElanInstanceFromCache(String elanInstanceName) {
+        return elanInstanceLocalCache.get(elanInstanceName);
+    }
+
+    public static Set<String> getAllElanNames() {
+        return elanInstanceLocalCache.keySet();
+    }
+
+    public static void addElanInterfaceIntoCache(String interfaceName, ElanInterface elanInterface) {
+        elanInterfaceLocalCache.put(interfaceName, elanInterface);
+    }
+
+    public static void removeElanInterfaceFromCache(String interfaceName) {
+        elanInterfaceLocalCache.remove(interfaceName);
+    }
+
+    public static ElanInterface getElanInterfaceFromCache(String interfaceName) {
+        return elanInterfaceLocalCache.get(interfaceName);
+    }
+
     /**
      * Uses the IdManager to retrieve a brand new ElanTag.
      *
@@ -193,21 +279,42 @@ public class ElanUtils {
         Future<RpcResult<Void>> result = idManager.releaseId(releaseIdInput);
     }
 
-    public static <T extends DataObject> Optional<T> read(DataBroker broker, LogicalDatastoreType datastoreType,
+    /**
+     * Read utility.
+     *
+     * @deprecated Consider using {@link #read2(LogicalDatastoreType, InstanceIdentifier)} with proper exception
+     *             handling instead
+     */
+    @Deprecated
+    @SuppressWarnings("checkstyle:IllegalCatch")
+    public <T extends DataObject> Optional<T> read(DataBroker broker, LogicalDatastoreType datastoreType,
             InstanceIdentifier<T> path) {
-        ReadOnlyTransaction tx = (broker != null) ? broker.newReadOnlyTransaction()
-                : elanServiceProvider.getBroker().newReadOnlyTransaction();
+        ReadOnlyTransaction tx = broker != null ? broker.newReadOnlyTransaction()
+                : this.broker.newReadOnlyTransaction();
         Optional<T> result = Optional.absent();
         try {
             CheckedFuture<Optional<T>, ReadFailedException> checkedFuture = tx.read(datastoreType, path);
             result = checkedFuture.get();
         } catch (Exception e) {
             throw new RuntimeException(e);
+        } finally {
+            tx.close();
         }
 
         return result;
     }
 
+    public <T extends DataObject> Optional<T> read2(LogicalDatastoreType datastoreType, InstanceIdentifier<T> path)
+            throws ReadFailedException {
+        ReadOnlyTransaction tx = broker.newReadOnlyTransaction();
+        try {
+            CheckedFuture<Optional<T>, ReadFailedException> checkedFuture = tx.read(datastoreType, path);
+            return checkedFuture.checkedGet();
+        } finally {
+            tx.close();
+        }
+    }
+
     public static <T extends DataObject> void delete(DataBroker broker, LogicalDatastoreType datastoreType,
             InstanceIdentifier<T> path) {
         WriteTransaction tx = broker.newWriteOnlyTransaction();
@@ -215,19 +322,25 @@ public class ElanUtils {
         Futures.addCallback(tx.submit(), DEFAULT_CALLBACK);
     }
 
+    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);
+    }
+
     public static InstanceIdentifier<ElanInstance> getElanInstanceIdentifier() {
         return InstanceIdentifier.builder(ElanInstances.class).child(ElanInstance.class).build();
     }
 
     // elan-instances config container
-    public static ElanInstance getElanInstanceByName(String elanInstanceName) {
-        InstanceIdentifier<ElanInstance> elanIdentifierId = getElanInstanceConfigurationDataPath(elanInstanceName);
-        Optional<ElanInstance> elanInstance = read(elanServiceProvider.getBroker(), LogicalDatastoreType.CONFIGURATION,
-                elanIdentifierId);
-        if (elanInstance.isPresent()) {
-            return elanInstance.get();
+    public static ElanInstance getElanInstanceByName(DataBroker broker, String elanInstanceName) {
+        ElanInstance elanObj = getElanInstanceFromCache(elanInstanceName);
+        if (elanObj != null) {
+            return elanObj;
         }
-        return null;
+        InstanceIdentifier<ElanInstance> elanIdentifierId = getElanInstanceConfigurationDataPath(elanInstanceName);
+        return MDSALUtil.read(broker, LogicalDatastoreType.CONFIGURATION, elanIdentifierId).orNull();
     }
 
     public static InstanceIdentifier<ElanInstance> getElanInstanceConfigurationDataPath(String elanInstanceName) {
@@ -236,14 +349,18 @@ public class ElanUtils {
     }
 
     // elan-interfaces Config Container
-    public static ElanInterface getElanInterfaceByElanInterfaceName(String elanInterfaceName) {
-        InstanceIdentifier<ElanInterface> elanInterfaceId = getElanInterfaceConfigurationDataPathId(elanInterfaceName);
-        Optional<ElanInterface> existingElanInterface = read(elanServiceProvider.getBroker(),
-                LogicalDatastoreType.CONFIGURATION, elanInterfaceId);
-        if (existingElanInterface.isPresent()) {
-            return existingElanInterface.get();
+    public static ElanInterface getElanInterfaceByElanInterfaceName(DataBroker broker, String elanInterfaceName) {
+        ElanInterface elanInterfaceObj = getElanInterfaceFromCache(elanInterfaceName);
+        if (elanInterfaceObj != null) {
+            return elanInterfaceObj;
         }
-        return null;
+        InstanceIdentifier<ElanInterface> elanInterfaceId = getElanInterfaceConfigurationDataPathId(elanInterfaceName);
+        return MDSALUtil.read(broker, LogicalDatastoreType.CONFIGURATION, elanInterfaceId).orNull();
+    }
+
+    public static EtreeInterface getEtreeInterfaceByElanInterfaceName(DataBroker broker, String elanInterfaceName) {
+        ElanInterface elanInterface = getElanInterfaceByElanInterfaceName(broker, elanInterfaceName);
+        return elanInterface.getAugmentation(EtreeInterface.class);
     }
 
     public static InstanceIdentifier<ElanInterface> getElanInterfaceConfigurationDataPathId(String interfaceName) {
@@ -252,14 +369,9 @@ public class ElanUtils {
     }
 
     // elan-state Operational container
-    public static Elan getElanByName(String elanInstanceName) {
+    public static Elan getElanByName(DataBroker broker, String elanInstanceName) {
         InstanceIdentifier<Elan> elanIdentifier = getElanInstanceOperationalDataPath(elanInstanceName);
-        Optional<Elan> elanInstance = read(elanServiceProvider.getBroker(), LogicalDatastoreType.OPERATIONAL,
-                elanIdentifier);
-        if (elanInstance.isPresent()) {
-            return elanInstance.get();
-        }
-        return null;
+        return MDSALUtil.read(broker, LogicalDatastoreType.OPERATIONAL, elanIdentifier).orNull();
     }
 
     public static InstanceIdentifier<Elan> getElanInstanceOperationalDataPath(String elanInstanceName) {
@@ -267,24 +379,16 @@ public class ElanUtils {
     }
 
     // grouping of forwarding-entries
-    public static MacEntry getInterfaceMacEntriesOperationalDataPath(String interfaceName, PhysAddress physAddress) {
+    public MacEntry getInterfaceMacEntriesOperationalDataPath(String interfaceName, PhysAddress physAddress) {
         InstanceIdentifier<MacEntry> existingMacEntryId = getInterfaceMacEntriesIdentifierOperationalDataPath(
                 interfaceName, physAddress);
-        Optional<MacEntry> existingInterfaceMacEntry = read(elanServiceProvider.getBroker(),
-                LogicalDatastoreType.OPERATIONAL, existingMacEntryId);
-        if (existingInterfaceMacEntry.isPresent()) {
-            return existingInterfaceMacEntry.get();
-        }
-        return null;
+        return read(broker, LogicalDatastoreType.OPERATIONAL, existingMacEntryId).orNull();
     }
 
-    public static MacEntry getInterfaceMacEntriesOperationalDataPathFromId(InstanceIdentifier identifier) {
-        Optional<MacEntry> existingInterfaceMacEntry = read(elanServiceProvider.getBroker(),
+    public MacEntry getInterfaceMacEntriesOperationalDataPathFromId(InstanceIdentifier identifier) {
+        Optional<MacEntry> existingInterfaceMacEntry = read(broker,
                 LogicalDatastoreType.OPERATIONAL, identifier);
-        if (existingInterfaceMacEntry.isPresent()) {
-            return existingInterfaceMacEntry.get();
-        }
-        return null;
+        return existingInterfaceMacEntry.orNull();
     }
 
     public static InstanceIdentifier<MacEntry> getInterfaceMacEntriesIdentifierOperationalDataPath(String interfaceName,
@@ -296,23 +400,15 @@ public class ElanUtils {
     }
 
     // elan-forwarding-tables Operational container
-    public static MacEntry getMacTableByElanName(String elanName, PhysAddress physAddress) {
+    public Optional<MacEntry> getMacEntryForElanInstance(String elanName, PhysAddress physAddress) {
         InstanceIdentifier<MacEntry> macId = getMacEntryOperationalDataPath(elanName, physAddress);
-        Optional<MacEntry> existingElanMacEntry = read(elanServiceProvider.getBroker(),
-                LogicalDatastoreType.OPERATIONAL, macId);
-        if (existingElanMacEntry.isPresent()) {
-            return existingElanMacEntry.get();
-        }
-        return null;
+        return read(broker, LogicalDatastoreType.OPERATIONAL, macId);
     }
 
-    public static MacEntry getMacEntryFromElanMacId(InstanceIdentifier identifier) {
-        Optional<MacEntry> existingInterfaceMacEntry = read(elanServiceProvider.getBroker(),
+    public MacEntry getMacEntryFromElanMacId(InstanceIdentifier identifier) {
+        Optional<MacEntry> existingInterfaceMacEntry = read(broker,
                 LogicalDatastoreType.OPERATIONAL, identifier);
-        if (existingInterfaceMacEntry.isPresent()) {
-            return existingInterfaceMacEntry.get();
-        }
-        return null;
+        return existingInterfaceMacEntry.orNull();
     }
 
     public static InstanceIdentifier<MacEntry> getMacEntryOperationalDataPath(String elanName,
@@ -327,15 +423,10 @@ public class ElanUtils {
     }
 
     // elan-interface-forwarding-entries Operational container
-    public static ElanInterfaceMac getElanInterfaceMacByInterfaceName(String interfaceName) {
+    public ElanInterfaceMac getElanInterfaceMacByInterfaceName(String interfaceName) {
         InstanceIdentifier<ElanInterfaceMac> elanInterfaceId = getElanInterfaceMacEntriesOperationalDataPath(
                 interfaceName);
-        Optional<ElanInterfaceMac> existingElanInterface = read(elanServiceProvider.getBroker(),
-                LogicalDatastoreType.OPERATIONAL, elanInterfaceId);
-        if (existingElanInterface.isPresent()) {
-            return existingElanInterface.get();
-        }
-        return null;
+        return read(broker, LogicalDatastoreType.OPERATIONAL, elanInterfaceId).orNull();
     }
 
     /**
@@ -345,9 +436,9 @@ public class ElanUtils {
      *            the interface name
      * @return the elan interface mac addresses
      */
-    public static List<PhysAddress> getElanInterfaceMacAddresses(String interfaceName) {
-        List<PhysAddress> macAddresses = new ArrayList<PhysAddress>();
-        ElanInterfaceMac elanInterfaceMac = ElanUtils.getElanInterfaceMacByInterfaceName(interfaceName);
+    public List<PhysAddress> getElanInterfaceMacAddresses(String interfaceName) {
+        List<PhysAddress> macAddresses = new ArrayList<>();
+        ElanInterfaceMac elanInterfaceMac = getElanInterfaceMacByInterfaceName(interfaceName);
         if (elanInterfaceMac != null && elanInterfaceMac.getMacEntry() != null) {
             List<MacEntry> macEntries = elanInterfaceMac.getMacEntry();
             for (MacEntry macEntry : macEntries) {
@@ -373,15 +464,10 @@ public class ElanUtils {
      *            Id of the DPN where the interfaces are located
      * @return the elan interface Info
      */
-    public static DpnInterfaces getElanInterfaceInfoByElanDpn(String elanInstanceName, BigInteger dpId) {
+    public DpnInterfaces getElanInterfaceInfoByElanDpn(String elanInstanceName, BigInteger dpId) {
         InstanceIdentifier<DpnInterfaces> elanDpnInterfacesId = getElanDpnInterfaceOperationalDataPath(elanInstanceName,
                 dpId);
-        Optional<DpnInterfaces> elanDpnInterfaces = read(elanServiceProvider.getBroker(),
-                LogicalDatastoreType.OPERATIONAL, elanDpnInterfacesId);
-        if (elanDpnInterfaces.isPresent()) {
-            return elanDpnInterfaces.get();
-        }
-        return null;
+        return read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfacesId).orNull();
     }
 
     /**
@@ -403,12 +489,20 @@ public class ElanUtils {
     }
 
     // elan-tag-name-map Operational Container
-    public static ElanTagName getElanInfoByElanTag(long elanTag) {
+    public ElanTagName getElanInfoByElanTag(long elanTag) {
+        InstanceIdentifier<ElanTagName> elanId = getElanInfoEntriesOperationalDataPath(elanTag);
+        Optional<ElanTagName> existingElanInfo = read(broker,
+                LogicalDatastoreType.OPERATIONAL, elanId);
+        return existingElanInfo.orNull();
+    }
+
+    public EtreeLeafTagName getEtreeLeafTagByElanTag(long elanTag) {
         InstanceIdentifier<ElanTagName> elanId = getElanInfoEntriesOperationalDataPath(elanTag);
-        Optional<ElanTagName> existingElanInfo = ElanUtils.read(elanServiceProvider.getBroker(),
+        Optional<ElanTagName> existingElanInfo = read(broker,
                 LogicalDatastoreType.OPERATIONAL, elanId);
         if (existingElanInfo.isPresent()) {
-            return existingElanInfo.get();
+            ElanTagName elanTagName = existingElanInfo.get();
+            return elanTagName.getAugmentation(EtreeLeafTagName.class);
         }
         return null;
     }
@@ -419,9 +513,9 @@ public class ElanUtils {
     }
 
     // interface-index-tag operational container
-    public static Optional<IfIndexInterface> getInterfaceInfoByInterfaceTag(long interfaceTag) {
+    public Optional<IfIndexInterface> getInterfaceInfoByInterfaceTag(long interfaceTag) {
         InstanceIdentifier<IfIndexInterface> interfaceId = getInterfaceInfoEntriesOperationalDataPath(interfaceTag);
-        return ElanUtils.read(elanServiceProvider.getBroker(), LogicalDatastoreType.OPERATIONAL, interfaceId);
+        return read(broker, LogicalDatastoreType.OPERATIONAL, interfaceId);
     }
 
     public static InstanceIdentifier<IfIndexInterface> getInterfaceInfoEntriesOperationalDataPath(long interfaceTag) {
@@ -434,14 +528,15 @@ public class ElanUtils {
                 .child(ElanDpnInterfacesList.class, new ElanDpnInterfacesListKey(elanInstanceName)).build();
     }
 
-    public static ElanDpnInterfacesList getElanDpnInterfacesList(String elanName) {
+    public ElanDpnInterfacesList getElanDpnInterfacesList(String elanName) {
         InstanceIdentifier<ElanDpnInterfacesList> elanDpnInterfaceId = getElanDpnOperationDataPath(elanName);
-        Optional<ElanDpnInterfacesList> existingElanDpnInterfaces = ElanUtils.read(elanServiceProvider.getBroker(),
-                LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId);
-        if (existingElanDpnInterfaces.isPresent()) {
-            return existingElanDpnInterfaces.get();
-        }
-        return null;
+        return read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId).orNull();
+    }
+
+    public ElanDpnInterfaces getElanDpnInterfacesList() {
+        InstanceIdentifier<ElanDpnInterfaces> elanDpnInterfaceId = InstanceIdentifier.builder(ElanDpnInterfaces.class)
+                .build();
+        return read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId).orNull();
     }
 
     /**
@@ -453,10 +548,10 @@ public class ElanUtils {
      *            the elan instance name
      * @return list of dpIds
      */
-    public static List<BigInteger> getParticipatingDPNsInElanInstance(String elanInstanceName) {
-        List<BigInteger> dpIds = new ArrayList<BigInteger>();
+    public List<BigInteger> getParticipatingDpnsInElanInstance(String elanInstanceName) {
+        List<BigInteger> dpIds = new ArrayList<>();
         InstanceIdentifier<ElanDpnInterfacesList> elanDpnInterfaceId = getElanDpnOperationDataPath(elanInstanceName);
-        Optional<ElanDpnInterfacesList> existingElanDpnInterfaces = ElanUtils.read(elanServiceProvider.getBroker(),
+        Optional<ElanDpnInterfacesList> existingElanDpnInterfaces = read(broker,
                 LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId);
         if (!existingElanDpnInterfaces.isPresent()) {
             return dpIds;
@@ -479,44 +574,30 @@ public class ElanUtils {
      *            the elan instance name
      * @return true if dpId is already present, otherwise return false
      */
-    public static boolean isDpnAlreadyPresentInElanInstance(BigInteger dpId, String elanInstanceName) {
-        boolean isDpIdPresent = false;
+    public boolean isDpnAlreadyPresentInElanInstance(BigInteger dpId, String elanInstanceName) {
         InstanceIdentifier<ElanDpnInterfacesList> elanDpnInterfaceId = getElanDpnOperationDataPath(elanInstanceName);
-        Optional<ElanDpnInterfacesList> existingElanDpnInterfaces = ElanUtils.read(elanServiceProvider.getBroker(),
+        Optional<ElanDpnInterfacesList> existingElanDpnInterfaces = read(broker,
                 LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId);
         if (!existingElanDpnInterfaces.isPresent()) {
-            return isDpIdPresent;
+            return false;
         }
         List<DpnInterfaces> dpnInterfaces = existingElanDpnInterfaces.get().getDpnInterfaces();
         for (DpnInterfaces dpnInterface : dpnInterfaces) {
             if (dpnInterface.getDpId().equals(dpId)) {
-                isDpIdPresent = true;
-                break;
+                return true;
             }
         }
-        return isDpIdPresent;
+        return false;
     }
 
-    public static ElanDpnInterfaces getElanDpnInterfacesList() {
-        InstanceIdentifier<ElanDpnInterfaces> elanDpnInterfaceId = InstanceIdentifier.builder(ElanDpnInterfaces.class)
-                .build();
-        Optional<ElanDpnInterfaces> existingElanDpnInterfaces = ElanUtils.read(elanServiceProvider.getBroker(),
-                LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId);
-        if (existingElanDpnInterfaces.isPresent()) {
-            return existingElanDpnInterfaces.get();
-        }
-        return null;
-    }
-
-    public static ElanForwardingTables getElanForwardingList() {
+    public ElanForwardingTables getElanForwardingList() {
         InstanceIdentifier<ElanForwardingTables> elanForwardingTableId = InstanceIdentifier
                 .builder(ElanForwardingTables.class).build();
-        Optional<ElanForwardingTables> existingElanForwardingList = ElanUtils.read(elanServiceProvider.getBroker(),
-                LogicalDatastoreType.OPERATIONAL, elanForwardingTableId);
-        if (existingElanForwardingList.isPresent()) {
-            return existingElanForwardingList.get();
-        }
-        return null;
+        return read(broker, LogicalDatastoreType.OPERATIONAL, elanForwardingTableId).orNull();
+    }
+
+    public static long getElanRemoteBroadCastGroupID(long elanTag) {
+        return ElanConstants.ELAN_GID_MIN + (((elanTag % ElanConstants.ELAN_GID_MIN) * 2));
     }
 
     /**
@@ -526,31 +607,34 @@ public class ElanUtils {
      *            the elan name
      * @return the elan mac table
      */
-    public static MacTable getElanMacTable(String elanName) {
+    public MacTable getElanMacTable(String elanName) {
         InstanceIdentifier<MacTable> elanMacTableId = getElanMacTableOperationalDataPath(elanName);
-        Optional<MacTable> existingElanMacTable = ElanUtils.read(elanServiceProvider.getBroker(),
-                LogicalDatastoreType.OPERATIONAL, elanMacTableId);
-        if (existingElanMacTable.isPresent()) {
-            return existingElanMacTable.get();
-        }
-        return null;
+        return read(broker, LogicalDatastoreType.OPERATIONAL, elanMacTableId).orNull();
     }
 
-    public static long getElanLocalBCGID(long elanTag) {
-        return ElanConstants.ELAN_GID_MIN + (((elanTag % ElanConstants.ELAN_GID_MIN) * 2) - 1);
+    public static long getElanLocalBCGId(long elanTag) {
+        return ElanConstants.ELAN_GID_MIN + (elanTag % ElanConstants.ELAN_GID_MIN * 2 - 1);
     }
 
-    public static long getElanRemoteBCGID(long elanTag) {
-        return ElanConstants.ELAN_GID_MIN + (((elanTag % ElanConstants.ELAN_GID_MIN) * 2));
+    public static long getElanRemoteBCGId(long elanTag) {
+        return ElanConstants.ELAN_GID_MIN + elanTag % ElanConstants.ELAN_GID_MIN * 2;
+    }
+
+    public static long getEtreeLeafLocalBCGId(long etreeLeafTag) {
+        return ElanConstants.ELAN_GID_MIN + (etreeLeafTag % ElanConstants.ELAN_GID_MIN * 2 - 1);
+    }
+
+    public static long getEtreeLeafRemoteBCGId(long etreeLeafTag) {
+        return ElanConstants.ELAN_GID_MIN + etreeLeafTag % ElanConstants.ELAN_GID_MIN * 2;
     }
 
     public static BigInteger getElanMetadataLabel(long elanTag) {
-        return (BigInteger.valueOf(elanTag)).shiftLeft(24);
+        return BigInteger.valueOf(elanTag).shiftLeft(24);
     }
 
     public static BigInteger getElanMetadataLabel(long elanTag, boolean isSHFlagSet) {
-        int shBit = (isSHFlagSet) ? 1 : 0;
-        return (BigInteger.valueOf(elanTag)).shiftLeft(24).or(BigInteger.valueOf(shBit));
+        int shBit = isSHFlagSet ? 1 : 0;
+        return BigInteger.valueOf(elanTag).shiftLeft(24).or(BigInteger.valueOf(shBit));
     }
 
     public static BigInteger getElanMetadataLabel(long elanTag, int lportTag) {
@@ -562,8 +646,7 @@ public class ElanUtils {
     }
 
     /**
-     * Setting INTERNAL_TUNNEL_TABLE, SMAC, DMAC, UDMAC in this DPN and also in
-     * other DPNs.
+     * Setting INTERNAL_TUNNEL_TABLE, SMAC, DMAC, UDMAC in this DPN and optionally in other DPNs.
      *
      * @param elanInfo
      *            the elan info
@@ -573,24 +656,27 @@ public class ElanUtils {
      *            the mac timeout
      * @param macAddress
      *            the mac address
+     * @param configureRemoteFlows
+     *            true if remote dmac flows should be configured as well
      * @param writeFlowGroupTx
      *            the flow group tx
+     * @throws ElanException in case of issues creating the flow objects
      */
-    public static void setupMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, long macTimeout,
-            String macAddress, WriteTransaction writeFlowGroupTx) {
-        synchronized (macAddress) {
-            LOG.info("Acquired lock for mac : " + macAddress + ". Proceeding with install operation.");
-            setupKnownSmacFlow(elanInfo, interfaceInfo, macTimeout, macAddress, elanServiceProvider.getMdsalManager(),
-                    writeFlowGroupTx);
-            setupOrigDmacFlows(elanInfo, interfaceInfo, macAddress, elanServiceProvider.getMdsalManager(),
-                    elanServiceProvider.getBroker(), writeFlowGroupTx);
+    public void setupMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo,
+                              long macTimeout, String macAddress, boolean configureRemoteFlows,
+                              WriteTransaction writeFlowGroupTx) throws ElanException {
+        synchronized (getElanMacKey(elanInfo.getElanTag(), macAddress)) {
+            setupKnownSmacFlow(elanInfo, interfaceInfo, macTimeout, macAddress, mdsalManager,
+                writeFlowGroupTx);
+            setupOrigDmacFlows(elanInfo, interfaceInfo, macAddress, configureRemoteFlows, mdsalManager,
+                broker, writeFlowGroupTx);
         }
     }
 
-    public static void setupDMacFlowonRemoteDpn(ElanInstance elanInfo, InterfaceInfo interfaceInfo, BigInteger dstDpId,
-            String macAddress, WriteTransaction writeFlowTx) {
-        synchronized (macAddress) {
-            LOG.info("Acquired lock for mac : " + macAddress + "Proceeding with install operation.");
+    public void setupDMacFlowonRemoteDpn(ElanInstance elanInfo, InterfaceInfo interfaceInfo, BigInteger dstDpId,
+            String macAddress, WriteTransaction writeFlowTx) throws ElanException {
+        synchronized (getElanMacKey(elanInfo.getElanTag(), macAddress)) {
+            LOG.debug("Acquired lock for mac : " + macAddress + ". Proceeding with install operation.");
             setupOrigDmacFlowsonRemoteDpn(elanInfo, interfaceInfo, dstDpId, macAddress, writeFlowTx);
         }
     }
@@ -598,36 +684,28 @@ public class ElanUtils {
     /**
      * Inserts a Flow in SMAC table to state that the MAC has already been
      * learnt.
-     *
-     * @param elanInfo
-     * @param interfaceInfo
-     * @param macTimeout
-     * @param macAddress
-     * @param mdsalApiManager
      */
-    private static void setupKnownSmacFlow(ElanInstance elanInfo, InterfaceInfo interfaceInfo, long macTimeout,
+    private void setupKnownSmacFlow(ElanInstance elanInfo, InterfaceInfo interfaceInfo, long macTimeout,
             String macAddress, IMdsalApiManager mdsalApiManager, WriteTransaction writeFlowGroupTx) {
         FlowEntity flowEntity = buildKnownSmacFlow(elanInfo, interfaceInfo, macTimeout, macAddress);
         mdsalApiManager.addFlowToTx(flowEntity, writeFlowGroupTx);
-        if (LOG.isDebugEnabled()) {
-            LOG.debug("Known Smac flow entry created for elan Name:{}, logical Interface port:{} and mac address:{}",
-                    elanInfo.getElanInstanceName(), elanInfo.getDescription(), macAddress);
-        }
+        LOG.debug("Known Smac flow entry created for elan Name:{}, logical Interface port:{} and mac address:{}",
+                elanInfo.getElanInstanceName(), elanInfo.getDescription(), macAddress);
     }
 
-    public static FlowEntity buildKnownSmacFlow(ElanInstance elanInfo, InterfaceInfo interfaceInfo, long macTimeout,
+    public FlowEntity buildKnownSmacFlow(ElanInstance elanInfo, InterfaceInfo interfaceInfo, long macTimeout,
             String macAddress) {
-        BigInteger dpId = interfaceInfo.getDpId();
         int lportTag = interfaceInfo.getInterfaceTag();
-        long elanTag = elanInfo.getElanTag();
         // Matching metadata and eth_src fields
-        List<MatchInfo> mkMatches = new ArrayList<MatchInfo>();
+        List<MatchInfo> mkMatches = new ArrayList<>();
         mkMatches.add(new MatchInfo(MatchFieldType.metadata, new BigInteger[] {
-                ElanUtils.getElanMetadataLabel(elanInfo.getElanTag(), lportTag), ElanUtils.getElanMetadataMask() }));
+                getElanMetadataLabel(elanInfo.getElanTag(), lportTag), getElanMetadataMask() }));
         mkMatches.add(new MatchInfo(MatchFieldType.eth_src, new String[] { macAddress }));
-        List<InstructionInfo> mkInstructions = new ArrayList<InstructionInfo>();
+        List<InstructionInfo> mkInstructions = new ArrayList<>();
         mkInstructions.add(new InstructionInfo(InstructionType.goto_table, new long[] { NwConstants.ELAN_DMAC_TABLE }));
 
+        BigInteger dpId = interfaceInfo.getDpId();
+        long elanTag = getElanTag(broker, elanInfo, interfaceInfo);
         FlowEntity flowEntity = MDSALUtil.buildFlowEntity(dpId, NwConstants.ELAN_SMAC_TABLE,
                 getKnownDynamicmacFlowRef(NwConstants.ELAN_SMAC_TABLE, dpId, lportTag, macAddress, elanTag), 20,
                 elanInfo.getDescription(), (int) macTimeout, 0,
@@ -641,10 +719,26 @@ public class ElanUtils {
         return flowEntity;
     }
 
+    private static Long getElanTag(DataBroker broker, ElanInstance elanInfo, InterfaceInfo interfaceInfo) {
+        EtreeInterface etreeInterface = getEtreeInterfaceByElanInterfaceName(broker, interfaceInfo.getInterfaceName());
+        if (etreeInterface == null || etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
+            return elanInfo.getElanTag();
+        } else { // Leaf
+            EtreeInstance etreeInstance = elanInfo.getAugmentation(EtreeInstance.class);
+            if (etreeInstance == null) {
+                LOG.warn("EtreeInterface {} is connected to a non-Etree network: {}",
+                         interfaceInfo.getInterfaceName(), elanInfo.getElanInstanceName());
+                return elanInfo.getElanTag();
+            } else {
+                return etreeInstance.getEtreeLeafTagVal().getValue();
+            }
+        }
+    }
+
     /**
      * Installs a Flow in INTERNAL_TUNNEL_TABLE of the affected DPN that sends
      * the packet through the specified interface if the tunnel_id matches the
-     * interface's lportTag
+     * interface's lportTag.
      *
      * @param interfaceInfo
      *            the interface info
@@ -653,7 +747,7 @@ public class ElanUtils {
      * @param writeFlowGroupTx
      *            the writeFLowGroup tx
      */
-    public static void setupTermDmacFlows(InterfaceInfo interfaceInfo, IMdsalApiManager mdsalApiManager,
+    public void setupTermDmacFlows(InterfaceInfo interfaceInfo, IMdsalApiManager mdsalApiManager,
             WriteTransaction writeFlowGroupTx) {
         BigInteger dpId = interfaceInfo.getDpId();
         int lportTag = interfaceInfo.getInterfaceTag();
@@ -664,10 +758,8 @@ public class ElanUtils {
                 getTunnelIdMatchForFilterEqualsLPortTag(lportTag),
                 getInstructionsInPortForOutGroup(interfaceInfo.getInterfaceName()));
         mdsalApiManager.addFlowToTx(dpId, flow, writeFlowGroupTx);
-        if (LOG.isDebugEnabled()) {
-            LOG.debug("Terminating service table flow entry created on dpn:{} for logical Interface port:{}", dpId,
-                    interfaceInfo.getPortName());
-        }
+        LOG.debug("Terminating service table flow entry created on dpn:{} for logical Interface port:{}", dpId,
+                interfaceInfo.getPortName());
     }
 
     /**
@@ -686,21 +778,21 @@ public class ElanUtils {
 
     /**
      * Constructs the Matches that checks that the tunnel_id field contains a
-     * specific lportTag
+     * specific lportTag.
      *
      * @param lportTag
      *            lportTag that must be checked against the tunnel_id field
      * @return the list of match Info
      */
     public static List<MatchInfo> getTunnelIdMatchForFilterEqualsLPortTag(int lportTag) {
-        List<MatchInfo> mkMatches = new ArrayList<MatchInfo>();
+        List<MatchInfo> mkMatches = new ArrayList<>();
         // Matching metadata
         mkMatches.add(new MatchInfo(MatchFieldType.tunnel_id, new BigInteger[] { BigInteger.valueOf(lportTag) }));
         return mkMatches;
     }
 
     /**
-     * Constructs the Instructions that take the packet over a given interface
+     * Constructs the Instructions that take the packet over a given interface.
      *
      * @param ifName
      *            Name of the interface where the packet must be sent over. It
@@ -708,9 +800,9 @@ public class ElanUtils {
      *            external)
      * @return the Instruction
      */
-    public static List<Instruction> getInstructionsInPortForOutGroup(String ifName) {
-        List<Instruction> mkInstructions = new ArrayList<Instruction>();
-        List<Action> actions = ElanUtils.getEgressActionsForInterface(ifName, /* tunnelKey */ null);
+    public List<Instruction> getInstructionsInPortForOutGroup(String ifName) {
+        List<Instruction> mkInstructions = new ArrayList<>();
+        List<Action> actions = getEgressActionsForInterface(ifName, /* tunnelKey */ null);
 
         mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
         return mkInstructions;
@@ -730,77 +822,83 @@ public class ElanUtils {
      *            the tunnel key
      * @return the egress actions for interface
      */
-    public static List<Action> getEgressActionsForInterface(String ifName, Long tunnelKey) {
-        List<Action> listAction = new ArrayList<Action>();
+    @SuppressWarnings("checkstyle:IllegalCatch")
+    public List<Action> getEgressActionsForInterface(String ifName, Long tunnelKey) {
+        List<Action> listAction = new ArrayList<>();
         try {
             GetEgressActionsForInterfaceInput getEgressActionInput = new GetEgressActionsForInterfaceInputBuilder()
                     .setIntfName(ifName).setTunnelKey(tunnelKey).build();
-            Future<RpcResult<GetEgressActionsForInterfaceOutput>> result = elanServiceProvider
-                    .getInterfaceManagerRpcService().getEgressActionsForInterface(getEgressActionInput);
+            Future<RpcResult<GetEgressActionsForInterfaceOutput>> result = interfaceManagerRpcService
+                    .getEgressActionsForInterface(getEgressActionInput);
             RpcResult<GetEgressActionsForInterfaceOutput> rpcResult = result.get();
             if (!rpcResult.isSuccessful()) {
                 LOG.warn("RPC Call to Get egress actions for interface {} returned with Errors {}", ifName,
                         rpcResult.getErrors());
             } else {
-                List<org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action> actions = rpcResult
-                        .getResult().getAction();
+                List<Action> actions = rpcResult.getResult().getAction();
                 listAction = actions;
             }
-        } catch (InterruptedException | ExecutionException e) {
+        } catch (Exception e) {
             LOG.warn("Exception when egress actions for interface {}", ifName, e);
         }
         return listAction;
     }
 
-    private static void setupOrigDmacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
-            IMdsalApiManager mdsalApiManager, DataBroker broker, WriteTransaction writeFlowGroupTx) {
+    private void setupOrigDmacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
+                                    boolean configureRemoteFlows, IMdsalApiManager mdsalApiManager,
+                                    DataBroker broker, WriteTransaction writeFlowGroupTx)
+                                    throws ElanException {
         BigInteger dpId = interfaceInfo.getDpId();
         String ifName = interfaceInfo.getInterfaceName();
         long ifTag = interfaceInfo.getInterfaceTag();
         String elanInstanceName = elanInfo.getElanInstanceName();
+
+        Long elanTag = getElanTag(broker, elanInfo, interfaceInfo);
+
+        setupLocalDmacFlow(elanTag, dpId, ifName, macAddress, elanInstanceName, mdsalApiManager, ifTag,
+                writeFlowGroupTx);
+        LOG.debug("Dmac flow entry created for elan Name:{}, logical port Name:{} mand mac address:{} "
+                                    + "on dpn:{}", elanInstanceName, interfaceInfo.getPortName(), macAddress, dpId);
+
+        if (!configureRemoteFlows) {
+            return;
+        }
+
         List<DpnInterfaces> elanDpns = getInvolvedDpnsInElan(elanInstanceName);
-        if (elanDpns != null) {
-            Long elanTag = elanInfo.getElanTag();
-            for (DpnInterfaces elanDpn : elanDpns) {
-                if (elanDpn.getDpId().equals(dpId)) {
-                    // On the local DPN set up a direct output flow
-                    setupLocalDmacFlow(elanTag, dpId, ifName, macAddress, elanInstanceName, mdsalApiManager, ifTag,
-                            writeFlowGroupTx);
-                    LOG.debug(
-                            "Dmac flow entry created for elan Name:{}, logical port Name:{} and mac address:{} on dpn:{}",
-                            elanInstanceName, interfaceInfo.getPortName(), macAddress, dpId);
-                } else {
-                    // Check for the Remote DPN present in Inventory Manager
-                    if (isDpnPresent(elanDpn.getDpId())) {
-                        // For remote DPNs a flow is needed to indicate that
-                        // packets of this ELAN going to this MAC
-                        // need to be forwarded through the appropiated ITM
-                        // tunnel
-                        setupRemoteDmacFlow(elanDpn.getDpId(), // srcDpn (the
-                                                               // remote DPN in
-                                                               // this case)
-                                dpId, // dstDpn (the local DPN)
-                                interfaceInfo.getInterfaceTag(), // lportTag of
-                                                                 // the local
-                                                                 // interface
-                                elanTag, // identifier of the Elan
-                                macAddress, // MAC to be programmed in remote
-                                            // DPN
-                                elanInstanceName, writeFlowGroupTx);
-                        LOG.debug(
-                                "Dmac flow entry created for elan Name:{}, logical port Name:{} and mac address:{} on dpn:{}",
-                                elanInstanceName, interfaceInfo.getPortName(), macAddress, elanDpn.getDpId());
-                    }
-                }
+        if (elanDpns == null) {
+            return;
+        }
+
+        for (DpnInterfaces elanDpn : elanDpns) {
+
+            if (elanDpn.getDpId().equals(dpId)) {
+                continue;
             }
 
-            // TODO: Make sure that the same is performed against the
-            // ElanDevices.
+            // Check for the Remote DPN present in Inventory Manager
+            if (!isDpnPresent(elanDpn.getDpId())) {
+                continue;
+            }
+
+            // For remote DPNs a flow is needed to indicate that
+            // packets of this ELAN going to this MAC
+            // need to be forwarded through the appropiated ITM
+            // tunnel
+            setupRemoteDmacFlow(elanDpn.getDpId(), // srcDpn (the remote DPN in this case)
+                    dpId, // dstDpn (the local DPN)
+                    interfaceInfo.getInterfaceTag(), // lportTag of the local interface
+                    elanTag, // identifier of the Elan
+                    macAddress, // MAC to be programmed in remote DPN
+                    elanInstanceName, writeFlowGroupTx, ifName, elanInfo);
+            LOG.debug("Dmac flow entry created for elan Name:{}, logical port Name:{} and mac address:{} on"
+                        + " dpn:{}", elanInstanceName, interfaceInfo.getPortName(), macAddress, elanDpn.getDpId());
         }
+
+        // TODO: Make sure that the same is performed against the ElanDevices.
     }
 
-    private static void setupOrigDmacFlowsonRemoteDpn(ElanInstance elanInfo, InterfaceInfo interfaceInfo,
-            BigInteger dstDpId, String macAddress, WriteTransaction writeFlowTx) {
+    private void setupOrigDmacFlowsonRemoteDpn(ElanInstance elanInfo, InterfaceInfo interfaceInfo,
+            BigInteger dstDpId, String macAddress, WriteTransaction writeFlowTx) throws ElanException {
         BigInteger dpId = interfaceInfo.getDpId();
         String elanInstanceName = elanInfo.getElanInstanceName();
         List<DpnInterfaces> remoteFEs = getInvolvedDpnsInElan(elanInstanceName);
@@ -809,32 +907,47 @@ public class ElanUtils {
             if (remoteFE.getDpId().equals(dstDpId)) {
                 // Check for the Remote DPN present in Inventory Manager
                 setupRemoteDmacFlow(dstDpId, dpId, interfaceInfo.getInterfaceTag(), elanTag, macAddress,
-                        elanInstanceName, writeFlowTx);
-                if (LOG.isDebugEnabled()) {
-                    LOG.debug(
-                            "Dmac flow entry created for elan Name:{}, logical port Name:{} and mac address {} on dpn:{}",
-                            elanInstanceName, interfaceInfo.getPortName(), macAddress, remoteFE.getDpId());
-                }
+                        elanInstanceName, writeFlowTx, interfaceInfo.getInterfaceName(), elanInfo);
+                LOG.debug("Dmac flow entry created for elan Name:{}, logical port Name:{} and mac address {} on dpn:{}",
+                        elanInstanceName, interfaceInfo.getPortName(), macAddress, remoteFE.getDpId());
                 break;
             }
         }
     }
 
     @SuppressWarnings("unchecked")
-    public static List<DpnInterfaces> getInvolvedDpnsInElan(String elanName) {
-        List<DpnInterfaces> dpns = ElanInstanceManager.getElanInstanceManager(elanServiceProvider)
-                .getElanDPNByName(elanName);
+    public List<DpnInterfaces> getInvolvedDpnsInElan(String elanName) {
+        List<DpnInterfaces> dpns = elanInstanceManager.getElanDPNByName(elanName);
         if (dpns == null) {
             return Collections.emptyList();
         }
         return dpns;
     }
 
-    private static void setupLocalDmacFlow(long elanTag, BigInteger dpId, String ifName, String macAddress,
+    private void setupLocalDmacFlow(long elanTag, BigInteger dpId, String ifName, String macAddress,
             String displayName, IMdsalApiManager mdsalApiManager, long ifTag, WriteTransaction writeFlowGroupTx) {
         Flow flowEntity = buildLocalDmacFlowEntry(elanTag, dpId, ifName, macAddress, displayName, ifTag);
         mdsalApiManager.addFlowToTx(dpId, flowEntity, writeFlowGroupTx);
+        installEtreeLocalDmacFlow(elanTag, dpId, ifName, macAddress, displayName, mdsalApiManager, ifTag,
+                writeFlowGroupTx);
+    }
 
+    private void installEtreeLocalDmacFlow(long elanTag, BigInteger dpId, String ifName, String macAddress,
+            String displayName, IMdsalApiManager mdsalApiManager, long ifTag, WriteTransaction writeFlowGroupTx) {
+        EtreeInterface etreeInterface = getEtreeInterfaceByElanInterfaceName(broker, ifName);
+        if (etreeInterface != null) {
+            if (etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
+                EtreeLeafTagName etreeTagName = getEtreeLeafTagByElanTag(elanTag);
+                if (etreeTagName == null) {
+                    LOG.warn("Interface {} seems like it belongs to Etree but etreeTagName from elanTag {} is null",
+                             ifName, elanTag);
+                } else {
+                    Flow flowEntity = buildLocalDmacFlowEntry(etreeTagName.getEtreeLeafTag().getValue(), dpId, ifName,
+                            macAddress, displayName, ifTag);
+                    mdsalApiManager.addFlowToTx(dpId, flowEntity, writeFlowGroupTx);
+                }
+            }
+        }
     }
 
     public static String getKnownDynamicmacFlowRef(short tableId, BigInteger dpId, long lporTag, String macAddress,
@@ -849,6 +962,10 @@ public class ElanUtils {
                 .toString();
     }
 
+    public static String getKnownDynamicmacFlowRef(short tableId, BigInteger dpId, String macAddress, long elanTag) {
+        return new StringBuffer().append(tableId).append(elanTag).append(dpId).append(macAddress).toString();
+    }
+
     private static String getKnownDynamicmacFlowRef(short elanDmacTable, BigInteger dpId, String extDeviceNodeId,
             String dstMacAddress, long elanTag, boolean shFlag) {
         return new StringBuffer().append(elanDmacTable).append(elanTag).append(dpId).append(extDeviceNodeId)
@@ -859,7 +976,7 @@ public class ElanUtils {
      * Builds the flow to be programmed in the DMAC table of the local DPN (that
      * is, where the MAC is attached to). This flow consists in:
      *
-     * Match: + elanTag in metadata + packet goes to a MAC locally attached
+     * <p>Match: + elanTag in metadata + packet goes to a MAC locally attached
      * Actions: + optionally, pop-vlan + set-vlan-id + output to ifName's
      * portNumber
      *
@@ -877,14 +994,14 @@ public class ElanUtils {
      *            the if tag
      * @return the flow
      */
-    public static Flow buildLocalDmacFlowEntry(long elanTag, BigInteger dpId, String ifName, String macAddress,
+    public Flow buildLocalDmacFlowEntry(long elanTag, BigInteger dpId, String ifName, String macAddress,
             String displayName, long ifTag) {
-        List<MatchInfo> mkMatches = new ArrayList<MatchInfo>();
+        List<MatchInfo> mkMatches = new ArrayList<>();
         mkMatches.add(new MatchInfo(MatchFieldType.metadata,
-                new BigInteger[] { ElanUtils.getElanMetadataLabel(elanTag), MetaDataUtil.METADATA_MASK_SERVICE }));
+                new BigInteger[] { getElanMetadataLabel(elanTag), MetaDataUtil.METADATA_MASK_SERVICE }));
         mkMatches.add(new MatchInfo(MatchFieldType.eth_dst, new String[] { macAddress }));
 
-        List<Instruction> mkInstructions = new ArrayList<Instruction>();
+        List<Instruction> mkInstructions = new ArrayList<>();
         List<Action> actions = getEgressActionsForInterface(ifName, /* tunnelKey */ null);
         mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
         Flow flow = MDSALUtil.buildFlowNew(NwConstants.ELAN_DMAC_TABLE,
@@ -895,10 +1012,34 @@ public class ElanUtils {
         return flow;
     }
 
-    public static void setupRemoteDmacFlow(BigInteger srcDpId, BigInteger destDpId, int lportTag, long elanTag,
-            String macAddress, String displayName, WriteTransaction writeFlowGroupTx) {
-        Flow flowEntity = buildRemoteDmacFlowEntry(srcDpId, destDpId, lportTag, elanTag, macAddress, displayName);
-        elanServiceProvider.getMdsalManager().addFlowToTx(srcDpId, flowEntity, writeFlowGroupTx);
+    public void setupRemoteDmacFlow(BigInteger srcDpId, BigInteger destDpId, int lportTag, long elanTag,
+            String macAddress, String displayName, WriteTransaction writeFlowGroupTx, String interfaceName,
+            ElanInstance elanInstance) throws ElanException {
+        Flow flowEntity = buildRemoteDmacFlowEntry(srcDpId, destDpId, lportTag, elanTag, macAddress, displayName,
+                elanInstance);
+        mdsalManager.addFlowToTx(srcDpId, flowEntity, writeFlowGroupTx);
+        setupEtreeRemoteDmacFlow(srcDpId, destDpId, lportTag, elanTag, macAddress, displayName, interfaceName,
+                writeFlowGroupTx, elanInstance);
+    }
+
+    private void setupEtreeRemoteDmacFlow(BigInteger srcDpId, BigInteger destDpId, int lportTag, long elanTag,
+                                String macAddress, String displayName, String interfaceName,
+                                WriteTransaction writeFlowGroupTx, ElanInstance elanInstance) throws ElanException {
+        Flow flowEntity;
+        EtreeInterface etreeInterface = getEtreeInterfaceByElanInterfaceName(broker, interfaceName);
+        if (etreeInterface != null) {
+            if (etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
+                EtreeLeafTagName etreeTagName = getEtreeLeafTagByElanTag(elanTag);
+                if (etreeTagName == null) {
+                    LOG.warn("Interface " + interfaceName
+                            + " seems like it belongs to Etree but etreeTagName from elanTag " + elanTag + " is null.");
+                } else {
+                    flowEntity = buildRemoteDmacFlowEntry(srcDpId, destDpId, lportTag,
+                            etreeTagName.getEtreeLeafTag().getValue(), macAddress, displayName, elanInstance);
+                    mdsalManager.addFlowToTx(srcDpId, flowEntity, writeFlowGroupTx);
+                }
+            }
+        }
     }
 
     /**
@@ -920,22 +1061,35 @@ public class ElanUtils {
      * @param displayName
      *            display Name
      * @return the flow remote Dmac
+     * @throws ElanException in case of issues creating the flow objects
      */
-    public static Flow buildRemoteDmacFlowEntry(BigInteger srcDpId, BigInteger destDpId, int lportTag, long elanTag,
-            String macAddress, String displayName) {
-        List<MatchInfo> mkMatches = new ArrayList<MatchInfo>();
+    @SuppressWarnings("checkstyle:IllegalCatch")
+    public Flow buildRemoteDmacFlowEntry(BigInteger srcDpId, BigInteger destDpId, int lportTag, long elanTag,
+            String macAddress, String displayName, ElanInstance elanInstance) throws ElanException {
+        List<MatchInfo> mkMatches = new ArrayList<>();
         mkMatches.add(new MatchInfo(MatchFieldType.metadata,
-                new BigInteger[] { ElanUtils.getElanMetadataLabel(elanTag), MetaDataUtil.METADATA_MASK_SERVICE }));
+                new BigInteger[] { getElanMetadataLabel(elanTag), MetaDataUtil.METADATA_MASK_SERVICE }));
         mkMatches.add(new MatchInfo(MatchFieldType.eth_dst, new String[] { macAddress }));
 
-        List<Instruction> mkInstructions = new ArrayList<Instruction>();
+        List<Instruction> mkInstructions = new ArrayList<>();
 
         // List of Action for the provided Source and Destination DPIDs
         try {
-            List<Action> actions = getInternalTunnelItmEgressAction(srcDpId, destDpId, lportTag);
+            List<Action> actions = null;
+            if (isVlan(elanInstance) || isFlat(elanInstance)) {
+                String interfaceName = getExternalElanInterface(elanInstance.getElanInstanceName(), srcDpId);
+                if (null == interfaceName) {
+                    LOG.error("buildRemoteDmacFlowEntry: Could not find interfaceName for {} {}", srcDpId,
+                            elanInstance);
+                }
+                actions = getEgressActionsForInterface(interfaceName, null);
+            } else {
+                actions = getInternalTunnelItmEgressAction(srcDpId, destDpId, lportTag);
+            }
             mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
         } catch (Exception e) {
-            LOG.error("Interface Not Found exception");
+            LOG.error("Could not get egress actions to add to flow for srcDpId=" + srcDpId + ", destDpId=" + destDpId
+                    + ", lportTag=" + lportTag, e);
         }
 
         Flow flow = MDSALUtil.buildFlowNew(NwConstants.ELAN_DMAC_TABLE,
@@ -949,19 +1103,18 @@ public class ElanUtils {
 
     }
 
-    public static void deleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, MacEntry macEntry,
+    public void deleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, MacEntry macEntry,
             WriteTransaction deleteFlowGroupTx) {
         if (elanInfo == null || interfaceInfo == null) {
             return;
         }
         String macAddress = macEntry.getMacAddress().getValue();
-        synchronized (macAddress) {
-            LOG.info("Acquired lock for mac : " + macAddress + "Proceeding with remove operation.");
+        synchronized (getElanMacKey(elanInfo.getElanTag(), macAddress)) {
             deleteMacFlows(elanInfo, interfaceInfo, macAddress, /* alsoDeleteSMAC */ true, deleteFlowGroupTx);
         }
     }
 
-    public static void deleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
+    public void deleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
             boolean deleteSmac, WriteTransaction deleteFlowGroupTx) {
         String elanInstanceName = elanInfo.getElanInstanceName();
         List<DpnInterfaces> remoteFEs = getInvolvedDpnsInElan(elanInstanceName);
@@ -970,48 +1123,66 @@ public class ElanUtils {
         for (DpnInterfaces dpnInterface : remoteFEs) {
             Long elanTag = elanInfo.getElanTag();
             BigInteger dstDpId = dpnInterface.getDpId();
-            if (dstDpId.equals(srcdpId)) {
+            if (executeDeleteMacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, elanInstanceName, srcdpId,
+                    elanTag, dstDpId, deleteFlowGroupTx)) {
                 isFlowsRemovedInSrcDpn = true;
-                deleteSmacAndDmacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, deleteFlowGroupTx);
-            } else if (isDpnPresent(dstDpId)) {
-                elanServiceProvider.getMdsalManager().removeFlowToTx(dstDpId,
-                        MDSALUtil.buildFlow(NwConstants.ELAN_DMAC_TABLE, getKnownDynamicmacFlowRef(
-                                NwConstants.ELAN_DMAC_TABLE, dstDpId, srcdpId, macAddress, elanTag)),
-                        deleteFlowGroupTx);
-                if (LOG.isDebugEnabled()) {
-                    LOG.debug(
-                            "Dmac flow entry deleted for elan:{}, logical interface port:{} and mac address:{} on dpn:{}",
-                            elanInstanceName, interfaceInfo.getPortName(), macAddress, dstDpId);
-                }
             }
+            executeEtreeDeleteMacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, elanInstanceName, srcdpId,
+                    elanTag, dstDpId, deleteFlowGroupTx);
         }
         if (!isFlowsRemovedInSrcDpn) {
             deleteSmacAndDmacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, deleteFlowGroupTx);
         }
     }
 
-    private static void deleteSmacAndDmacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
+    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);
+        if (etreeLeafTag != null) {
+            executeDeleteMacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, elanInstanceName, srcdpId,
+                    etreeLeafTag.getEtreeLeafTag().getValue(), dstDpId, deleteFlowGroupTx);
+        }
+    }
+
+    private boolean executeDeleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
+            boolean deleteSmac, String elanInstanceName, BigInteger srcdpId, Long elanTag, BigInteger dstDpId,
+            WriteTransaction deleteFlowGroupTx) {
+        boolean isFlowsRemovedInSrcDpn = false;
+        if (dstDpId.equals(srcdpId)) {
+            isFlowsRemovedInSrcDpn = true;
+            deleteSmacAndDmacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, deleteFlowGroupTx);
+        } else if (isDpnPresent(dstDpId)) {
+            mdsalManager
+                    .removeFlowToTx(dstDpId,
+                            MDSALUtil.buildFlow(NwConstants.ELAN_DMAC_TABLE, getKnownDynamicmacFlowRef(
+                                    NwConstants.ELAN_DMAC_TABLE, dstDpId, srcdpId, macAddress, elanTag)),
+                            deleteFlowGroupTx);
+            LOG.debug("Dmac flow entry deleted for elan:{}, logical interface port:{} and mac address:{} on dpn:{}",
+                    elanInstanceName, interfaceInfo.getPortName(), macAddress, dstDpId);
+        }
+        return isFlowsRemovedInSrcDpn;
+    }
+
+    private void deleteSmacAndDmacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
             boolean deleteSmac, WriteTransaction deleteFlowGroupTx) {
         String elanInstanceName = elanInfo.getElanInstanceName();
         long ifTag = interfaceInfo.getInterfaceTag();
         BigInteger srcdpId = interfaceInfo.getDpId();
         Long elanTag = elanInfo.getElanTag();
         if (deleteSmac) {
-            elanServiceProvider.getMdsalManager()
+            mdsalManager
                     .removeFlowToTx(srcdpId,
                             MDSALUtil.buildFlow(NwConstants.ELAN_SMAC_TABLE, getKnownDynamicmacFlowRef(
                                     NwConstants.ELAN_SMAC_TABLE, srcdpId, ifTag, macAddress, elanTag)),
                             deleteFlowGroupTx);
         }
-        elanServiceProvider.getMdsalManager().removeFlowToTx(srcdpId,
+        mdsalManager.removeFlowToTx(srcdpId,
                 MDSALUtil.buildFlow(NwConstants.ELAN_DMAC_TABLE,
                         getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, srcdpId, ifTag, macAddress, elanTag)),
                 deleteFlowGroupTx);
-        if (LOG.isDebugEnabled()) {
-            LOG.debug(
-                    "All the required flows deleted for elan:{}, logical Interface port:{} and mac address:{} on dpn:{}",
-                    elanInstanceName, interfaceInfo.getPortName(), macAddress, srcdpId);
-        }
+        LOG.debug("All the required flows deleted for elan:{}, logical Interface port:{} and MAC address:{} on dpn:{}",
+                elanInstanceName, interfaceInfo.getPortName(), macAddress, srcdpId);
     }
 
     /**
@@ -1024,6 +1195,8 @@ public class ElanUtils {
      *            the id manager
      * @param elanInstanceAdded
      *            the elan instance added
+     * @param elanInterfaces
+     *            the elan interfaces
      * @param tx
      *            transaction
      */
@@ -1032,70 +1205,90 @@ public class ElanUtils {
         String elanInstanceName = elanInstanceAdded.getElanInstanceName();
         Long elanTag = elanInstanceAdded.getElanTag();
         if (elanTag == null || elanTag == 0L) {
-            elanTag = ElanUtils.retrieveNewElanTag(idManager, elanInstanceName);
+            elanTag = retrieveNewElanTag(idManager, elanInstanceName);
         }
         Elan elanInfo = new ElanBuilder().setName(elanInstanceName).setElanInterfaces(elanInterfaces)
                 .setKey(new ElanKey(elanInstanceName)).build();
 
         // Add the ElanState in the elan-state operational data-store
-        tx.put(LogicalDatastoreType.OPERATIONAL, ElanUtils.getElanInstanceOperationalDataPath(elanInstanceName),
+        tx.put(LogicalDatastoreType.OPERATIONAL, getElanInstanceOperationalDataPath(elanInstanceName),
                 elanInfo, true);
 
         // Add the ElanMacTable in the elan-mac-table operational data-store
         MacTable elanMacTable = new MacTableBuilder().setKey(new MacTableKey(elanInstanceName)).build();
-        tx.put(LogicalDatastoreType.OPERATIONAL, ElanUtils.getElanMacTableOperationalDataPath(elanInstanceName),
+        tx.put(LogicalDatastoreType.OPERATIONAL, getElanMacTableOperationalDataPath(elanInstanceName),
                 elanMacTable, true);
 
-        ElanTagName elanTagName = new ElanTagNameBuilder().setElanTag(elanTag).setKey(new ElanTagNameKey(elanTag))
-                .setName(elanInstanceName).build();
+        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);
+            EtreeLeafTagName etreeLeafTagName = new EtreeLeafTagNameBuilder()
+                    .setEtreeLeafTag(new EtreeLeafTag(etreeLeafTag)).build();
+            elanTagNameBuilder.addAugmentation(EtreeLeafTagName.class, etreeLeafTagName);
+            addTheLeafTagAsElanTag(broker, elanInstanceName, etreeLeafTag, tx);
+        }
+        ElanTagName elanTagName = elanTagNameBuilder.build();
 
         // Add the ElanTag to ElanName in the elan-tag-name Operational
         // data-store
-        tx.put(LogicalDatastoreType.OPERATIONAL, ElanUtils.getElanInfoEntriesOperationalDataPath(elanTag), elanTagName,
-                true);
+        tx.put(LogicalDatastoreType.OPERATIONAL,
+                getElanInfoEntriesOperationalDataPath(elanTag), elanTagName);
 
-        // Updates the ElanInstance Config DS by setting the just adquired
+        // Updates the ElanInstance Config DS by setting the just acquired
         // elanTag
-        ElanInstance elanInstanceWithTag = new ElanInstanceBuilder().setElanInstanceName(elanInstanceName)
+        ElanInstanceBuilder elanInstanceBuilder = new ElanInstanceBuilder().setElanInstanceName(elanInstanceName)
                 .setDescription(elanInstanceAdded.getDescription())
                 .setMacTimeout(elanInstanceAdded.getMacTimeout() == null ? ElanConstants.DEFAULT_MAC_TIME_OUT
                         : elanInstanceAdded.getMacTimeout())
-                .setKey(elanInstanceAdded.getKey()).setElanTag(elanTag).build();
+                .setKey(elanInstanceAdded.getKey()).setElanTag(elanTag);
+        if (isEtreeInstance(elanInstanceAdded)) {
+            EtreeInstance etreeInstance = new EtreeInstanceBuilder().setEtreeLeafTagVal(new EtreeLeafTag(etreeLeafTag))
+                    .build();
+            elanInstanceBuilder.addAugmentation(EtreeInstance.class, etreeInstance);
+        }
+        ElanInstance elanInstanceWithTag = elanInstanceBuilder.build();
         tx.merge(LogicalDatastoreType.CONFIGURATION, getElanInstanceConfigurationDataPath(elanInstanceName),
                 elanInstanceWithTag, true);
     }
 
-    public static boolean isDpnPresent(BigInteger dpnId) {
+    private static void addTheLeafTagAsElanTag(DataBroker broker, String elanInstanceName, long etreeLeafTag,
+            WriteTransaction tx) {
+        ElanTagName etreeTagAsElanTag = new ElanTagNameBuilder().setElanTag(etreeLeafTag)
+                .setKey(new ElanTagNameKey(etreeLeafTag)).setName(elanInstanceName).build();
+        tx.put(LogicalDatastoreType.OPERATIONAL,
+                getElanInfoEntriesOperationalDataPath(etreeLeafTag), etreeTagAsElanTag);
+    }
+
+    private static boolean isEtreeInstance(ElanInstance elanInstanceAdded) {
+        return elanInstanceAdded.getAugmentation(EtreeInstance.class) != null;
+    }
+
+    public boolean isDpnPresent(BigInteger dpnId) {
         String dpn = String.format("%s:%s", "openflow", dpnId);
         NodeId nodeId = new NodeId(dpn);
 
         InstanceIdentifier<Node> node = InstanceIdentifier.builder(Nodes.class).child(Node.class, new NodeKey(nodeId))
                 .build();
-        Optional<Node> nodePresent = read(elanServiceProvider.getBroker(), LogicalDatastoreType.OPERATIONAL, node);
-        return (nodePresent.isPresent());
+        return read(broker, LogicalDatastoreType.OPERATIONAL, 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<Instruction>();
-        instructions.add(MDSALUtil.buildAndGetWriteMetadaInstruction(ElanUtils.getElanMetadataLabel(elanTag),
+        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), NwConstants.ELAN_SERVICE_INDEX, priority,
+                String.format("%s.%s", elanInstanceName, interfaceName), serviceIndex, priority,
                 NwConstants.COOKIE_ELAN_INGRESS_TABLE, instructions);
         return serviceInfo;
     }
 
-    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);
-    }
-
     public static <T extends DataObject> void syncWrite(DataBroker broker, LogicalDatastoreType datastoreType,
             InstanceIdentifier<T> path, T data) {
         WriteTransaction tx = broker.newWriteOnlyTransaction();
@@ -1135,7 +1328,7 @@ public class ElanUtils {
      *            the tunnel key
      * @return the list
      */
-    public static List<Action> buildTunnelItmEgressActions(String tunnelIfaceName, Long tunnelKey) {
+    public List<Action> buildTunnelItmEgressActions(String tunnelIfaceName, Long tunnelKey) {
         if (tunnelIfaceName != null && !tunnelIfaceName.isEmpty()) {
             return buildItmEgressActions(tunnelIfaceName, tunnelKey);
         }
@@ -1154,19 +1347,20 @@ public class ElanUtils {
      *            tunnels, etc.
      * @return the list
      */
-    public static List<Action> buildItmEgressActions(String interfaceName, Long tunnelKey) {
+    @SuppressWarnings("checkstyle:IllegalCatch")
+    public List<Action> buildItmEgressActions(String interfaceName, Long tunnelKey) {
         List<Action> result = Collections.emptyList();
-        GetEgressActionsForInterfaceInput getEgressActInput = new GetEgressActionsForInterfaceInputBuilder()
-                .setIntfName(interfaceName).setTunnelKey(tunnelKey).build();
-
-        Future<RpcResult<GetEgressActionsForInterfaceOutput>> egressActionsOutputFuture = elanServiceProvider
-                .getInterfaceManagerRpcService().getEgressActionsForInterface(getEgressActInput);
         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 (InterruptedException | ExecutionException e) {
+        } catch (Exception e) {
             LOG.error("Error in RPC call getEgressActionsForInterface {}", e);
         }
 
@@ -1190,20 +1384,19 @@ public class ElanUtils {
      *            Vni to be stamped on the VxLAN Header.
      * @return the external itm egress action
      */
-    public static List<Action> getExternalTunnelItmEgressAction(BigInteger srcDpnId, NodeId torNode, long vni) {
+    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 = elanServiceProvider.getItmRpcService()
+        Future<RpcResult<GetExternalTunnelInterfaceNameOutput>> output = itmRpcService
                 .getExternalTunnelInterfaceName(input);
         try {
             if (output.get().isSuccessful()) {
                 GetExternalTunnelInterfaceNameOutput tunnelInterfaceNameOutput = output.get().getResult();
                 String tunnelIfaceName = tunnelInterfaceNameOutput.getInterfaceName();
-                if (LOG.isDebugEnabled())
-                    LOG.debug("Received tunnelInterfaceName from getTunnelInterfaceName RPC {}", tunnelIfaceName);
+                LOG.debug("Received tunnelInterfaceName from getTunnelInterfaceName RPC {}", tunnelIfaceName);
 
                 result = buildTunnelItmEgressActions(tunnelIfaceName, vni);
             }
@@ -1230,7 +1423,7 @@ public class ElanUtils {
      *            serviceId to be sent on the VxLAN header.
      * @return the internal itm egress action
      */
-    public static List<Action> getInternalTunnelItmEgressAction(BigInteger sourceDpnId, BigInteger destinationDpnId,
+    public List<Action> getInternalTunnelItmEgressAction(BigInteger sourceDpnId, BigInteger destinationDpnId,
             long serviceTag) {
         List<Action> result = Collections.emptyList();
 
@@ -1239,7 +1432,7 @@ public class ElanUtils {
         Class<? extends TunnelTypeBase> tunType = TunnelTypeVxlan.class;
         GetTunnelInterfaceNameInput input = new GetTunnelInterfaceNameInputBuilder()
                 .setDestinationDpid(destinationDpnId).setSourceDpid(sourceDpnId).setTunnelType(tunType).build();
-        Future<RpcResult<GetTunnelInterfaceNameOutput>> output = elanServiceProvider.getItmRpcService()
+        Future<RpcResult<GetTunnelInterfaceNameOutput>> output = itmRpcService
                 .getTunnelInterfaceName(input);
         try {
             if (output.get().isSuccessful()) {
@@ -1258,28 +1451,28 @@ public class ElanUtils {
 
     /**
      * Build the list of actions to be taken when sending the packet to external
-     * (physical) port
+     * (physical) port.
      *
      * @param interfaceName
      *            Interface name
      * @return the external port itm egress actions
      */
-    public static List<Action> getExternalPortItmEgressAction(String interfaceName) {
+    public List<Action> getExternalPortItmEgressAction(String interfaceName) {
         return buildItmEgressActions(interfaceName, null);
     }
 
     public static List<MatchInfo> getTunnelMatchesForServiceId(int elanTag) {
-        List<MatchInfo> mkMatches = new ArrayList<MatchInfo>();
+        List<MatchInfo> mkMatches = new ArrayList<>();
         // Matching metadata
         mkMatches.add(new MatchInfo(MatchFieldType.tunnel_id, new BigInteger[] { BigInteger.valueOf(elanTag) }));
 
         return mkMatches;
     }
 
-    public static void removeTerminatingServiceAction(BigInteger destDpId, int serviceId) {
+    public void removeTerminatingServiceAction(BigInteger destDpId, int serviceId) {
         RemoveTerminatingServiceActionsInput input = new RemoveTerminatingServiceActionsInputBuilder()
                 .setDpnId(destDpId).setServiceId(serviceId).build();
-        Future<RpcResult<Void>> futureObject = elanServiceProvider.getItmRpcService()
+        Future<RpcResult<Void>> futureObject = itmRpcService
                 .removeTerminatingServiceActions(input);
         try {
             RpcResult<Void> result = futureObject.get();
@@ -1293,24 +1486,19 @@ public class ElanUtils {
         }
     }
 
-    public static void createTerminatingServiceActions(BigInteger destDpId, int serviceId, List<Action> actions) {
-        List<Instruction> mkInstructions = new ArrayList<Instruction>();
+    public void createTerminatingServiceActions(BigInteger destDpId, int serviceId, List<Action> actions) {
+        List<Instruction> mkInstructions = new ArrayList<>();
         mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
         CreateTerminatingServiceActionsInput input = new CreateTerminatingServiceActionsInputBuilder()
                 .setDpnId(destDpId).setServiceId(serviceId).setInstruction(mkInstructions).build();
 
-        elanServiceProvider.getItmRpcService().createTerminatingServiceActions(input);
+        itmRpcService.createTerminatingServiceActions(input);
     }
 
     public static TunnelList buildInternalTunnel(DataBroker broker) {
         InstanceIdentifier<TunnelList> tunnelListInstanceIdentifier = InstanceIdentifier.builder(TunnelList.class)
                 .build();
-        Optional<TunnelList> tunnelList = read(broker, LogicalDatastoreType.CONFIGURATION,
-                tunnelListInstanceIdentifier);
-        if (tunnelList.isPresent()) {
-            return tunnelList.get();
-        }
-        return null;
+        return MDSALUtil.read(broker, LogicalDatastoreType.CONFIGURATION, tunnelListInstanceIdentifier).orNull();
     }
 
     /**
@@ -1324,17 +1512,12 @@ public class ElanUtils {
      *            the datastore type
      * @return the external tunnel
      */
-    public static ExternalTunnel getExternalTunnel(String sourceDevice, String destinationDevice,
+    public ExternalTunnel getExternalTunnel(String sourceDevice, String destinationDevice,
             LogicalDatastoreType datastoreType) {
-        ExternalTunnel externalTunnel = null;
         Class<? extends TunnelTypeBase> tunType = TunnelTypeVxlan.class;
         InstanceIdentifier<ExternalTunnel> iid = InstanceIdentifier.builder(ExternalTunnelList.class)
                 .child(ExternalTunnel.class, new ExternalTunnelKey(destinationDevice, sourceDevice, tunType)).build();
-        Optional<ExternalTunnel> tunnelList = read(elanServiceProvider.getBroker(), datastoreType, iid);
-        if (tunnelList.isPresent()) {
-            externalTunnel = tunnelList.get();
-        }
-        return externalTunnel;
+        return read(broker, datastoreType, iid).orNull();
     }
 
     /**
@@ -1346,7 +1529,7 @@ public class ElanUtils {
      *            the datastore type
      * @return the external tunnel
      */
-    public static ExternalTunnel getExternalTunnel(String interfaceName, LogicalDatastoreType datastoreType) {
+    public ExternalTunnel getExternalTunnel(String interfaceName, LogicalDatastoreType datastoreType) {
         ExternalTunnel externalTunnel = null;
         List<ExternalTunnel> externalTunnels = getAllExternalTunnels(datastoreType);
         for (ExternalTunnel tunnel : externalTunnels) {
@@ -1365,17 +1548,10 @@ public class ElanUtils {
      *            the data store type
      * @return the all external tunnels
      */
-    public static List<ExternalTunnel> getAllExternalTunnels(LogicalDatastoreType datastoreType) {
-        List<ExternalTunnel> result = null;
+    public List<ExternalTunnel> getAllExternalTunnels(LogicalDatastoreType datastoreType) {
         InstanceIdentifier<ExternalTunnelList> iid = InstanceIdentifier.builder(ExternalTunnelList.class).build();
-        Optional<ExternalTunnelList> tunnelList = read(elanServiceProvider.getBroker(), datastoreType, iid);
-        if (tunnelList.isPresent()) {
-            result = tunnelList.get().getExternalTunnel();
-        }
-        if (result == null) {
-            result = Collections.emptyList();
-        }
-        return result;
+        return read(broker, datastoreType, iid).transform(ExternalTunnelList::getExternalTunnel).or(
+                Collections.emptyList());
     }
 
     /**
@@ -1396,12 +1572,13 @@ public class ElanUtils {
      *            MAC to be installed in remoteDpId's DMAC table
      * @param displayName
      *            the display name
+     * @throws ElanException in case of issues creating the flow objects
      */
-    public static void installDmacFlowsToInternalRemoteMac(BigInteger localDpId, BigInteger remoteDpId, long lportTag,
-            long elanTag, String macAddress, String displayName) {
+    public void installDmacFlowsToInternalRemoteMac(BigInteger localDpId, BigInteger remoteDpId, int lportTag,
+            long elanTag, String macAddress, String displayName) throws ElanException {
         Flow flow = buildDmacFlowForInternalRemoteMac(localDpId, remoteDpId, lportTag, elanTag, macAddress,
                 displayName);
-        elanServiceProvider.getMdsalManager().installFlow(remoteDpId, flow);
+        mdsalManager.installFlow(remoteDpId, flow);
     }
 
     /**
@@ -1423,27 +1600,75 @@ public class ElanUtils {
      *            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 static List<ListenableFuture<Void>> installDmacFlowsToExternalRemoteMac(BigInteger dpnId,
-            String extDeviceNodeId, Long elanTag, Long vni, String macAddress, String displayName) {
+    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 (macAddress) {
+        synchronized (getElanMacKey(elanTag, macAddress)) {
             Flow flow = buildDmacFlowForExternalRemoteMac(dpnId, extDeviceNodeId, elanTag, vni, macAddress,
                     displayName);
-            futures.add(elanServiceProvider.getMdsalManager().installFlow(dpnId, flow));
+            futures.add(mdsalManager.installFlow(dpnId, flow));
 
             Flow dropFlow = buildDmacFlowDropIfPacketComingFromTunnel(dpnId, extDeviceNodeId, elanTag, macAddress);
-            futures.add(elanServiceProvider.getMdsalManager().installFlow(dpnId, dropFlow));
+            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<MatchInfo>();
+        List<MatchInfo> mkMatches = new ArrayList<>();
         mkMatches.add(new MatchInfo(MatchFieldType.metadata, new BigInteger[] {
-                ElanUtils.getElanMetadataLabel(elanTag, shFlag), MetaDataUtil.METADATA_MASK_SERVICE_SH_FLAG }));
+                getElanMetadataLabel(elanTag, shFlag), MetaDataUtil.METADATA_MASK_SERVICE_SH_FLAG }));
         mkMatches.add(new MatchInfo(MatchFieldType.eth_dst, new String[] { macAddr }));
 
         return mkMatches;
@@ -1469,16 +1694,18 @@ public class ElanUtils {
      * @param displayName
      *            the display name
      * @return the flow
+     * @throws ElanException in case of issues creating the flow objects
      */
-    public static Flow buildDmacFlowForExternalRemoteMac(BigInteger dpId, String extDeviceNodeId, long elanTag,
-            Long vni, String dstMacAddress, String displayName) {
+    @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<Instruction>();
+        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={}  externalNode={}", dpId, extDeviceNodeId);
+            LOG.error("Could not get Egress Actions for DpId=" + dpId + ", externalNode=" + extDeviceNodeId, e);
         }
 
         Flow flow = MDSALUtil.buildFlowNew(NwConstants.ELAN_DMAC_TABLE,
@@ -1504,8 +1731,6 @@ public class ElanUtils {
      *            ElanId to which the MAC is being added to
      * @param dstMacAddress
      *            The mac address to be programmed
-     * @param displayName
-     * @return
      */
     private static Flow buildDmacFlowDropIfPacketComingFromTunnel(BigInteger dpnId, String extDeviceNodeId,
             Long elanTag, String dstMacAddress) {
@@ -1530,7 +1755,7 @@ public class ElanUtils {
      * Builds a Flow to be programmed in a remote DPN's DMAC table. This method
      * must be used when the MAC is located in another CSS.
      *
-     * This flow consists in: Match: + elanTag in packet's metadata + packet
+     * <p>This flow consists in: Match: + elanTag in packet's metadata + packet
      * going to a MAC known to be located in another DPN Actions: +
      * set_tunnel_id(lportTag) + output on ITM internal tunnel interface with
      * the other DPN
@@ -1548,20 +1773,22 @@ public class ElanUtils {
      * @param displayName
      *            the display name
      * @return the flow
+     * @throws ElanException in case of issues creating the flow objects
      */
-    public static Flow buildDmacFlowForInternalRemoteMac(BigInteger localDpId, BigInteger remoteDpId, long lportTag,
-            long elanTag, String macAddress, String displayName) {
+    @SuppressWarnings("checkstyle:IllegalCatch")
+    public Flow buildDmacFlowForInternalRemoteMac(BigInteger localDpId, BigInteger remoteDpId, int lportTag,
+            long elanTag, String macAddress, String displayName) throws ElanException {
         List<MatchInfo> mkMatches = buildMatchesForElanTagShFlagAndDstMac(elanTag, /* shFlag */ false, macAddress);
 
-        List<Instruction> mkInstructions = new ArrayList<Instruction>();
+        List<Instruction> mkInstructions = new ArrayList<>();
 
         try {
             // List of Action for the provided Source and Destination DPIDs
             List<Action> actions = getInternalTunnelItmEgressAction(localDpId, remoteDpId, lportTag);
             mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
         } catch (Exception e) {
-            LOG.error("Could not get Egress Actions for localDpId={}  remoteDpId={}   lportTag={}", localDpId,
-                    remoteDpId, lportTag);
+            LOG.error("Could not get Egress Actions for localDpId=" + localDpId + ", remoteDpId="
+                    + remoteDpId + ", lportTag=" + lportTag, e);
         }
 
         Flow flow = MDSALUtil.buildFlowNew(NwConstants.ELAN_DMAC_TABLE,
@@ -1594,14 +1821,19 @@ public class ElanUtils {
      *            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 static void setupDmacFlowsToExternalRemoteMac(BigInteger dpId, String extNodeId, Long elanTag, Long vni,
-            String macAddress, String elanInstanceName, MdsalOp addOrRemove) {
+    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) {
-            ElanUtils.installDmacFlowsToExternalRemoteMac(dpId, extNodeId, elanTag, vni, macAddress, elanInstanceName);
+            installDmacFlowsToExternalRemoteMac(dpId, extNodeId, elanTag, vni, macAddress, elanInstanceName,
+                    interfaceName);
         } else if (addOrRemove == MdsalOp.REMOVAL_OP) {
-            ElanUtils.deleteDmacFlowsToExternalMac(elanTag, dpId, extNodeId, macAddress);
+            deleteDmacFlowsToExternalMac(elanTag, dpId, extNodeId, macAddress);
         }
     }
 
@@ -1618,26 +1850,47 @@ public class ElanUtils {
      *            the mac to remove
      * @return dmac flow
      */
-    public static List<ListenableFuture<Void>> deleteDmacFlowsToExternalMac(long elanTag, BigInteger dpId,
+    public List<ListenableFuture<Void>> deleteDmacFlowsToExternalMac(long elanTag, BigInteger dpId,
             String extDeviceNodeId, String macToRemove) {
         List<ListenableFuture<Void>> futures = new ArrayList<>();
-        synchronized (macToRemove) {
+        synchronized (getElanMacKey(elanTag, macToRemove)) {
             // Removing the flows that sends the packet on an external tunnel
-            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(elanServiceProvider.getMdsalManager().removeFlow(dpId, flowToRemove));
+            removeFlowThatSendsThePacketOnAnExternalTunnel(elanTag, dpId, extDeviceNodeId, macToRemove, futures);
 
             // And now removing the drop flow
-            flowId = getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, extDeviceNodeId, macToRemove, elanTag,
-                    true);
-            flowToRemove = new FlowBuilder().setId(new FlowId(flowId)).setTableId(NwConstants.ELAN_DMAC_TABLE).build();
-            futures.add(elanServiceProvider.getMdsalManager().removeFlow(dpId, flowToRemove));
+            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.
      *
@@ -1645,9 +1898,9 @@ public class ElanUtils {
      *            the interface name
      * @return the dpid from interface
      */
-    public static BigInteger getDpidFromInterface(String interfaceName) {
+    public BigInteger getDpidFromInterface(String interfaceName) {
         BigInteger dpId = null;
-        Future<RpcResult<GetDpidFromInterfaceOutput>> output = elanServiceProvider.getInterfaceManagerRpcService()
+        Future<RpcResult<GetDpidFromInterfaceOutput>> output = interfaceManagerRpcService
                 .getDpidFromInterface(new GetDpidFromInterfaceInputBuilder().setIntfName(interfaceName).build());
         try {
             RpcResult<GetDpidFromInterfaceOutput> rpcResult = output.get();
@@ -1677,7 +1930,7 @@ public class ElanUtils {
         if (ifState == null) {
             return false;
         }
-        return ((ifState.getOperStatus() == OperStatus.Up) && (ifState.getAdminStatus() == AdminStatus.Up));
+        return ifState.getOperStatus() == OperStatus.Up && ifState.getAdminStatus() == AdminStatus.Up;
     }
 
     /**
@@ -1689,37 +1942,13 @@ public class ElanUtils {
      *            the data broker
      * @return the interface state from oper ds
      */
-    public static org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface getInterfaceStateFromOperDS(
-            String interfaceName, DataBroker dataBroker) {
-        InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface> ifStateId = createInterfaceStateInstanceIdentifier(
-                interfaceName);
-        Optional<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface> ifStateOptional = MDSALUtil
-                .read(dataBroker, LogicalDatastoreType.OPERATIONAL, ifStateId);
-        if (ifStateOptional.isPresent()) {
-            return ifStateOptional.get();
-        }
-        return null;
-    }
-
-    /**
-     * Gets the interface from config ds.
-     *
-     * @param interfaceName
-     *            the interface name
-     * @param dataBroker
-     *            the data broker
-     * @return the interface from config ds
-     */
-    public static org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.Interface getInterfaceFromConfigDS(
+    public static org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
+        .ietf.interfaces.rev140508.interfaces.state.Interface getInterfaceStateFromOperDS(
             String interfaceName, DataBroker dataBroker) {
-        InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.Interface> ifaceId = createInterfaceInstanceIdentifier(
+        InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
+            .ietf.interfaces.rev140508.interfaces.state.Interface> ifStateId = createInterfaceStateInstanceIdentifier(
                 interfaceName);
-        Optional<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.Interface> iface = MDSALUtil
-                .read(dataBroker, LogicalDatastoreType.CONFIGURATION, ifaceId);
-        if (iface.isPresent()) {
-            return iface.get();
-        }
-        return null;
+        return MDSALUtil.read(dataBroker, LogicalDatastoreType.OPERATIONAL, ifStateId).orNull();
     }
 
     /**
@@ -1729,40 +1958,29 @@ public class ElanUtils {
      *            the interface name
      * @return the instance identifier
      */
-    public static InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface> createInterfaceStateInstanceIdentifier(
+    public static InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
+        .ietf.interfaces.rev140508.interfaces.state.Interface> createInterfaceStateInstanceIdentifier(
             String interfaceName) {
-        InstanceIdentifierBuilder<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface> idBuilder = InstanceIdentifier
+        InstanceIdentifierBuilder<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
+            .ietf.interfaces.rev140508.interfaces.state.Interface> idBuilder = InstanceIdentifier
                 .builder(InterfacesState.class)
-                .child(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface.class,
-                        new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.InterfaceKey(
+                .child(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
+                        .ietf.interfaces.rev140508.interfaces.state.Interface.class,
+                        new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
+                            .ietf.interfaces.rev140508.interfaces.state.InterfaceKey(
                                 interfaceName));
         return idBuilder.build();
     }
 
-    /**
-     * Creates the interface instance identifier.
-     *
-     * @param interfaceName
-     *            the interface name
-     * @return the instance identifier
-     */
-    public static InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.Interface> createInterfaceInstanceIdentifier(
-            String interfaceName) {
-        InstanceIdentifierBuilder<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.Interface> idBuilder = InstanceIdentifier
-                .builder(Interfaces.class)
-                .child(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.Interface.class,
-                        new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.InterfaceKey(
-                                interfaceName));
-        return idBuilder.build();
-    }
-
-    public static void waitForTransactionToComplete(WriteTransaction tx) {
+    public static CheckedFuture<Void, TransactionCommitFailedException> waitForTransactionToComplete(
+            WriteTransaction tx) {
         CheckedFuture<Void, TransactionCommitFailedException> futures = tx.submit();
         try {
             futures.get();
         } catch (InterruptedException | ExecutionException e) {
             LOG.error("Error writing to datastore {}", e);
         }
+        return futures;
     }
 
     public static boolean isVxlan(ElanInstance elanInstance) {
@@ -1782,17 +2000,124 @@ public class ElanUtils {
                 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeFlat.class);
     }
 
-    public static boolean isExternal(String interfaceName) {
-        return isExternal(getInterfaceFromConfigDS(interfaceName, elanServiceProvider.getBroker()));
+    public static boolean isEtreeRootInterfaceByInterfaceName(DataBroker broker, String interfaceName) {
+        EtreeInterface etreeInterface = getEtreeInterfaceByElanInterfaceName(broker, interfaceName);
+        if (etreeInterface != null && etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
+            return true;
+        }
+        return false;
     }
 
-    public static boolean isExternal(
-            org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.Interface iface) {
-        if (iface == null) {
-            return false;
+    public void handleDmacRedirectToDispatcherFlows(Long elanTag, String displayName,
+            String macAddress, int addOrRemove, 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));
+            }
         }
+    }
+
+    public static FlowEntity buildDmacRedirectToDispatcherFlow(BigInteger dpId, String dstMacAddress,
+            String displayName, long elanTag) {
+        List<MatchInfo> matches = new ArrayList<MatchInfo>();
+        matches.add(new MatchInfo(MatchFieldType.metadata,
+                new BigInteger[] { getElanMetadataLabel(elanTag), MetaDataUtil.METADATA_MASK_SERVICE }));
+        matches.add(new MatchInfo(MatchFieldType.eth_dst, new String[] { dstMacAddress }));
+        List<InstructionInfo> instructions = new ArrayList<InstructionInfo>();
+        List<ActionInfo> actions = new ArrayList<ActionInfo>();
+        actions.add(new ActionInfo(ActionType.nx_resubmit,
+                new String[] { String.valueOf(NwConstants.LPORT_DISPATCHER_TABLE) }));
+
+        instructions.add(new InstructionInfo(InstructionType.apply_actions, actions));
+        String flowId = getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, dstMacAddress, elanTag);
+        FlowEntity flow  = MDSALUtil.buildFlowEntity(dpId, NwConstants.ELAN_DMAC_TABLE, flowId, 20, displayName, 0, 0,
+                ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(BigInteger.valueOf(elanTag)),
+                matches, instructions);
+        return flow;
+    }
+
+    public static FlowEntity buildDmacRedirectToDispatcherFlowMacNoActions(BigInteger dpId, String dstMacAddress,
+            String displayName, long elanTag) {
+        List<MatchInfo> matches = new ArrayList<MatchInfo>();
+        matches.add(new MatchInfo(MatchFieldType.metadata,
+                new BigInteger[] { getElanMetadataLabel(elanTag), MetaDataUtil.METADATA_MASK_SERVICE }));
+        matches.add(new MatchInfo(MatchFieldType.eth_dst, new String[] { dstMacAddress }));
+
+        String flowId = getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, dstMacAddress, elanTag);
+        FlowEntity flow  = MDSALUtil.buildFlowEntity(dpId, NwConstants.ELAN_DMAC_TABLE, flowId, 20, displayName, 0, 0,
+                ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(BigInteger.valueOf(elanTag)),
+                matches, new ArrayList<InstructionInfo>());
+        return flow;
+    }
+
+    /**
+     * Add Mac Address to ElanInterfaceForwardingEntries and ElanForwardingTables
+     * Install SMAC and DMAC flows.
+     */
+    public void addMacEntryToDsAndSetupFlows(IInterfaceManager interfaceManager, String interfaceName,
+            String macAddress, String elanName, WriteTransaction tx, WriteTransaction flowWritetx, int macTimeOut)
+            throws ElanException {
+        LOG.trace("Adding mac address {} and interface name {} to ElanInterfaceForwardingEntries and "
+            + "ElanForwardingTables DS", macAddress, interfaceName);
+        BigInteger timeStamp = new BigInteger(String.valueOf(System.currentTimeMillis()));
+        PhysAddress physAddress = new PhysAddress(macAddress);
+        MacEntry macEntry = new MacEntryBuilder().setInterface(interfaceName).setMacAddress(physAddress)
+                .setKey(new MacEntryKey(physAddress)).setControllerLearnedForwardingEntryTimestamp(timeStamp)
+                .setIsStaticAddress(false).build();
+        InstanceIdentifier<MacEntry> macEntryId = ElanUtils
+                .getInterfaceMacEntriesIdentifierOperationalDataPath(interfaceName, physAddress);
+        tx.put(LogicalDatastoreType.OPERATIONAL, macEntryId, macEntry);
+        InstanceIdentifier<MacEntry> elanMacEntryId = ElanUtils.getMacEntryOperationalDataPath(elanName, physAddress);
+        tx.put(LogicalDatastoreType.OPERATIONAL, elanMacEntryId, macEntry);
+        ElanInstance elanInstance = ElanUtils.getElanInstanceByName(broker, elanName);
+        setupMacFlows(elanInstance, interfaceManager.getInterfaceInfo(interfaceName), macTimeOut, macAddress, true,
+                flowWritetx);
+    }
+
+    /**
+     * Remove Mac Address from ElanInterfaceForwardingEntries and ElanForwardingTables
+     * Remove SMAC and DMAC flows.
+     */
+    public void deleteMacEntryFromDsAndRemoveFlows(IInterfaceManager interfaceManager, String interfaceName,
+            String macAddress, String elanName, WriteTransaction tx, WriteTransaction deleteFlowTx) {
+        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);
+        }
+        tx.delete(LogicalDatastoreType.OPERATIONAL,
+                ElanUtils.getInterfaceMacEntriesIdentifierOperationalDataPath(interfaceName, physAddress));
+        tx.delete(LogicalDatastoreType.OPERATIONAL,
+                ElanUtils.getMacEntryOperationalDataPath(elanName, physAddress));
+    }
+
+    public String getExternalElanInterface(String elanInstanceName, BigInteger dpnId) {
+        DpnInterfaces dpnInterfaces = getElanInterfaceInfoByElanDpn(elanInstanceName, dpnId);
+        if (dpnInterfaces == null || dpnInterfaces.getInterfaces() == null) {
+            LOG.trace("Elan {} does not have interfaces in DPN {}", elanInstanceName, dpnId);
+            return null;
+        }
+
+        for (String dpnInterface : dpnInterfaces.getInterfaces()) {
+            if (interfaceManager.isExternalInterface(dpnInterface)) {
+                return dpnInterface;
+            }
+        }
+
+        LOG.trace("Elan {} does not have any external interace attached to DPN {}", elanInstanceName, dpnId);
+        return null;
+    }
 
-        IfExternal ifExternal = iface.getAugmentation(IfExternal.class);
-        return ifExternal != null && Boolean.TRUE.equals(ifExternal.isExternal());
+    public static String getElanMacKey(long elanTag, String macAddress) {
+        return ("MAC-" + macAddress + " ELAN_TAG-" + elanTag).intern();
     }
 }