Fix Checkstyle violations related to exception handling in elanmanager.
[netvirt.git] / vpnservice / elanmanager / elanmanager-impl / src / main / java / org / opendaylight / netvirt / elan / utils / ElanUtils.java
1 /*
2  * Copyright (c) 2016 Ericsson India Global Services Pvt Ltd. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.netvirt.elan.utils;
9
10 import com.google.common.base.Optional;
11 import com.google.common.util.concurrent.CheckedFuture;
12 import com.google.common.util.concurrent.FutureCallback;
13 import com.google.common.util.concurrent.Futures;
14 import com.google.common.util.concurrent.ListenableFuture;
15 import java.math.BigInteger;
16 import java.util.ArrayList;
17 import java.util.Collections;
18 import java.util.List;
19 import java.util.Map;
20 import java.util.concurrent.ConcurrentHashMap;
21 import java.util.concurrent.ExecutionException;
22 import java.util.concurrent.Future;
23 import org.apache.commons.lang3.StringUtils;
24 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
25 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
26 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
27 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipService;
28 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
29 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
30 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
31 import org.opendaylight.genius.interfacemanager.globals.InterfaceInfo;
32 import org.opendaylight.genius.interfacemanager.globals.InterfaceServiceUtil;
33 import org.opendaylight.genius.interfacemanager.interfaces.IInterfaceManager;
34 import org.opendaylight.genius.itm.globals.ITMConstants;
35 import org.opendaylight.genius.mdsalutil.FlowEntity;
36 import org.opendaylight.genius.mdsalutil.InstructionInfo;
37 import org.opendaylight.genius.mdsalutil.InstructionType;
38 import org.opendaylight.genius.mdsalutil.MDSALUtil;
39 import org.opendaylight.genius.mdsalutil.MDSALUtil.MdsalOp;
40 import org.opendaylight.genius.mdsalutil.MatchFieldType;
41 import org.opendaylight.genius.mdsalutil.MatchInfo;
42 import org.opendaylight.genius.mdsalutil.MetaDataUtil;
43 import org.opendaylight.genius.mdsalutil.NwConstants;
44 import org.opendaylight.genius.mdsalutil.interfaces.IMdsalApiManager;
45 import org.opendaylight.genius.utils.ServiceIndex;
46 import org.opendaylight.netvirt.elan.ElanException;
47 import org.opendaylight.netvirt.elan.internal.ElanBridgeManager;
48 import org.opendaylight.netvirt.elan.internal.ElanInstanceManager;
49 import org.opendaylight.netvirt.elan.internal.ElanInterfaceManager;
50 import org.opendaylight.netvirt.elan.l2gw.utils.ElanL2GatewayMulticastUtils;
51 import org.opendaylight.netvirt.elan.l2gw.utils.ElanL2GatewayUtils;
52 import org.opendaylight.netvirt.elan.l2gw.utils.L2GatewayConnectionUtils;
53 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.Interfaces;
54 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.InterfacesState;
55 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface;
56 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface.AdminStatus;
57 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface.OperStatus;
58 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.PhysAddress;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowBuilder;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.Instruction;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdInput;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdInputBuilder;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdOutput;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.IdManagerService;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.ReleaseIdInput;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.ReleaseIdInputBuilder;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406.IfIndexesInterfaceMap;
71 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406._if.indexes._interface.map.IfIndexInterface;
72 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406._if.indexes._interface.map.IfIndexInterfaceKey;
73 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.IfExternal;
74 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelTypeBase;
75 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelTypeVxlan;
76 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetDpidFromInterfaceInputBuilder;
77 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetDpidFromInterfaceOutput;
78 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetEgressActionsForInterfaceInput;
79 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetEgressActionsForInterfaceInputBuilder;
80 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetEgressActionsForInterfaceOutput;
81 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.OdlInterfaceRpcService;
82 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceBindings;
83 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceModeIngress;
84 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceTypeFlowBased;
85 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.StypeOpenflow;
86 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.StypeOpenflowBuilder;
87 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.ServicesInfo;
88 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.ServicesInfoKey;
89 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.services.info.BoundServices;
90 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.services.info.BoundServicesBuilder;
91 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.services.info.BoundServicesKey;
92 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.ExternalTunnelList;
93 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.TunnelList;
94 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.external.tunnel.list.ExternalTunnel;
95 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.external.tunnel.list.ExternalTunnelKey;
96 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.CreateTerminatingServiceActionsInput;
97 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.CreateTerminatingServiceActionsInputBuilder;
98 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.GetExternalTunnelInterfaceNameInput;
99 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.GetExternalTunnelInterfaceNameInputBuilder;
100 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.GetExternalTunnelInterfaceNameOutput;
101 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.GetTunnelInterfaceNameInput;
102 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.GetTunnelInterfaceNameInputBuilder;
103 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.GetTunnelInterfaceNameOutput;
104 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.ItmRpcService;
105 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.RemoveTerminatingServiceActionsInput;
106 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.RemoveTerminatingServiceActionsInputBuilder;
107 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
108 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
109 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
110 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
111 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInstance;
112 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInstanceBuilder;
113 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInterface;
114 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInterface.EtreeInterfaceType;
115 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeLeafTag;
116 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeLeafTagName;
117 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeLeafTagNameBuilder;
118 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanDpnInterfaces;
119 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanForwardingTables;
120 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInstances;
121 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInterfaceForwardingEntries;
122 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInterfaces;
123 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanState;
124 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanTagNameMap;
125 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.SegmentTypeFlat;
126 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.SegmentTypeVlan;
127 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.SegmentTypeVxlan;
128 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan._interface.forwarding.entries.ElanInterfaceMac;
129 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan._interface.forwarding.entries.ElanInterfaceMacKey;
130 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.ElanDpnInterfacesList;
131 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.ElanDpnInterfacesListKey;
132 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.elan.dpn.interfaces.list.DpnInterfaces;
133 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.elan.dpn.interfaces.list.DpnInterfacesKey;
134 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.forwarding.tables.MacTable;
135 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.forwarding.tables.MacTableBuilder;
136 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.forwarding.tables.MacTableKey;
137 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.ElanInstance;
138 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.ElanInstanceBuilder;
139 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.ElanInstanceKey;
140 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.ElanInterface;
141 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.ElanInterfaceKey;
142 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.state.Elan;
143 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.state.ElanBuilder;
144 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.state.ElanKey;
145 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.tag.name.map.ElanTagName;
146 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.tag.name.map.ElanTagNameBuilder;
147 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.tag.name.map.ElanTagNameKey;
148 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.forwarding.entries.MacEntry;
149 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.forwarding.entries.MacEntryBuilder;
150 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.forwarding.entries.MacEntryKey;
151 import org.opendaylight.yangtools.yang.binding.DataObject;
152 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
153 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.InstanceIdentifierBuilder;
154 import org.opendaylight.yangtools.yang.common.RpcResult;
155 import org.slf4j.Logger;
156 import org.slf4j.LoggerFactory;
157
158 public class ElanUtils {
159
160     private static final Logger LOG = LoggerFactory.getLogger(ElanUtils.class);
161
162     private static Map<String, ElanInstance> elanInstanceLocalCache = new ConcurrentHashMap<>();
163     private static Map<String, ElanInterface> elanInterfaceLocalCache = new ConcurrentHashMap<>();
164
165     private final DataBroker broker;
166     private final IMdsalApiManager mdsalManager;
167     private final ElanInstanceManager elanInstanceManager;
168     private final OdlInterfaceRpcService interfaceManagerRpcService;
169     private final ItmRpcService itmRpcService;
170     private ElanL2GatewayUtils elanL2GatewayUtils;
171     private ElanL2GatewayMulticastUtils elanL2GatewayMulticastUtils;
172     private L2GatewayConnectionUtils l2GatewayConnectionUtils;
173     private ElanBridgeManager bridgeManager;
174
175     public static final FutureCallback<Void> DEFAULT_CALLBACK = new FutureCallback<Void>() {
176         @Override
177         public void onSuccess(Void result) {
178             LOG.debug("Success in Datastore operation");
179         }
180
181         @Override
182         public void onFailure(Throwable error) {
183             LOG.error("Error in Datastore operation", error);
184         }
185     };
186
187     public ElanUtils(DataBroker dataBroker, IMdsalApiManager mdsalManager, ElanInstanceManager elanInstanceManager,
188                      OdlInterfaceRpcService interfaceManagerRpcService, ItmRpcService itmRpcService,
189                      ElanInterfaceManager elanInterfaceManager,
190                      EntityOwnershipService entityOwnershipService, ElanBridgeManager bridgeManager) {
191         this.broker = dataBroker;
192         this.mdsalManager = mdsalManager;
193         this.elanInstanceManager = elanInstanceManager;
194         this.interfaceManagerRpcService = interfaceManagerRpcService;
195         this.itmRpcService = itmRpcService;
196         this.bridgeManager = bridgeManager;
197
198         elanL2GatewayMulticastUtils =
199                 new ElanL2GatewayMulticastUtils(broker, elanInstanceManager, elanInterfaceManager, this);
200         elanL2GatewayUtils = new ElanL2GatewayUtils(broker, itmRpcService, this,
201                 entityOwnershipService, elanL2GatewayMulticastUtils);
202         l2GatewayConnectionUtils = new L2GatewayConnectionUtils(broker,
203                 elanInstanceManager, entityOwnershipService, this);
204     }
205
206     public ElanL2GatewayUtils getElanL2GatewayUtils() {
207         return elanL2GatewayUtils;
208     }
209
210     public ElanL2GatewayMulticastUtils getElanL2GatewayMulticastUtils() {
211         return elanL2GatewayMulticastUtils;
212     }
213
214     public L2GatewayConnectionUtils getL2GatewayConnectionUtils() {
215         return l2GatewayConnectionUtils;
216     }
217
218     public static void addElanInstanceIntoCache(String elanInstanceName, ElanInstance elanInstance) {
219         elanInstanceLocalCache.put(elanInstanceName, elanInstance);
220     }
221
222     public static void removeElanInstanceFromCache(String elanInstanceName) {
223         elanInstanceLocalCache.remove(elanInstanceName);
224     }
225
226     public static ElanInstance getElanInstanceFromCache(String elanInstanceName) {
227         return elanInstanceLocalCache.get(elanInstanceName);
228     }
229
230     public static void addElanInterfaceIntoCache(String interfaceName, ElanInterface elanInterface) {
231         elanInterfaceLocalCache.put(interfaceName, elanInterface);
232     }
233
234     public static void removeElanInterfaceFromCache(String interfaceName) {
235         elanInterfaceLocalCache.remove(interfaceName);
236     }
237
238     public static ElanInterface getElanInterfaceFromCache(String interfaceName) {
239         return elanInterfaceLocalCache.get(interfaceName);
240     }
241
242     /**
243      * Uses the IdManager to retrieve a brand new ElanTag.
244      *
245      * @param idManager
246      *            the id manager
247      * @param idKey
248      *            the id key
249      * @return the integer
250      */
251     public static Long retrieveNewElanTag(IdManagerService idManager, String idKey) {
252
253         AllocateIdInput getIdInput = new AllocateIdInputBuilder().setPoolName(ElanConstants.ELAN_ID_POOL_NAME)
254                 .setIdKey(idKey).build();
255
256         try {
257             Future<RpcResult<AllocateIdOutput>> result = idManager.allocateId(getIdInput);
258             RpcResult<AllocateIdOutput> rpcResult = result.get();
259             if (rpcResult.isSuccessful()) {
260                 return rpcResult.getResult().getIdValue().longValue();
261             } else {
262                 LOG.warn("RPC Call to Allocate Id returned with Errors {}", rpcResult.getErrors());
263             }
264         } catch (InterruptedException | ExecutionException e) {
265             LOG.warn("Exception when Allocating Id", e);
266         }
267         return 0L;
268     }
269
270     public static void releaseId(IdManagerService idManager, String poolName, String idKey) {
271         ReleaseIdInput releaseIdInput = new ReleaseIdInputBuilder().setPoolName(poolName).setIdKey(idKey).build();
272         Future<RpcResult<Void>> result = idManager.releaseId(releaseIdInput);
273     }
274
275     /**
276      * Read utility.
277      *
278      * @deprecated Consider using {@link #read2(LogicalDatastoreType, InstanceIdentifier)} with proper exception
279      *             handling instead
280      */
281     @Deprecated
282     @SuppressWarnings("checkstyle:IllegalCatch")
283     public <T extends DataObject> Optional<T> read(DataBroker broker, LogicalDatastoreType datastoreType,
284             InstanceIdentifier<T> path) {
285         ReadOnlyTransaction tx = broker != null ? broker.newReadOnlyTransaction()
286                 : this.broker.newReadOnlyTransaction();
287         Optional<T> result = Optional.absent();
288         try {
289             CheckedFuture<Optional<T>, ReadFailedException> checkedFuture = tx.read(datastoreType, path);
290             result = checkedFuture.get();
291         } catch (Exception e) {
292             throw new RuntimeException(e);
293         } finally {
294             tx.close();
295         }
296
297         return result;
298     }
299
300     public <T extends DataObject> Optional<T> read2(LogicalDatastoreType datastoreType, InstanceIdentifier<T> path)
301             throws ReadFailedException {
302         ReadOnlyTransaction tx = broker.newReadOnlyTransaction();
303         try {
304             CheckedFuture<Optional<T>, ReadFailedException> checkedFuture = tx.read(datastoreType, path);
305             return checkedFuture.checkedGet();
306         } finally {
307             tx.close();
308         }
309     }
310
311     public static <T extends DataObject> void delete(DataBroker broker, LogicalDatastoreType datastoreType,
312             InstanceIdentifier<T> path) {
313         WriteTransaction tx = broker.newWriteOnlyTransaction();
314         tx.delete(datastoreType, path);
315         Futures.addCallback(tx.submit(), DEFAULT_CALLBACK);
316     }
317
318     public static <T extends DataObject> void delete(DataBroker broker, LogicalDatastoreType datastoreType,
319             InstanceIdentifier<T> path, FutureCallback<Void> callback) {
320         WriteTransaction tx = broker.newWriteOnlyTransaction();
321         tx.delete(datastoreType, path);
322         Futures.addCallback(tx.submit(), callback);
323     }
324
325     public static InstanceIdentifier<ElanInstance> getElanInstanceIdentifier() {
326         return InstanceIdentifier.builder(ElanInstances.class).child(ElanInstance.class).build();
327     }
328
329     // elan-instances config container
330     public static ElanInstance getElanInstanceByName(DataBroker broker, String elanInstanceName) {
331         ElanInstance elanObj = getElanInstanceFromCache(elanInstanceName);
332         if (elanObj != null) {
333             return elanObj;
334         }
335         InstanceIdentifier<ElanInstance> elanIdentifierId = getElanInstanceConfigurationDataPath(elanInstanceName);
336         Optional<ElanInstance> elanInstance = MDSALUtil.read(broker, LogicalDatastoreType.CONFIGURATION,
337                 elanIdentifierId);
338         if (elanInstance.isPresent()) {
339             return elanInstance.get();
340         }
341         return null;
342     }
343
344     public static InstanceIdentifier<ElanInstance> getElanInstanceConfigurationDataPath(String elanInstanceName) {
345         return InstanceIdentifier.builder(ElanInstances.class)
346                 .child(ElanInstance.class, new ElanInstanceKey(elanInstanceName)).build();
347     }
348
349     // elan-interfaces Config Container
350     public static ElanInterface getElanInterfaceByElanInterfaceName(DataBroker broker, String elanInterfaceName) {
351         ElanInterface elanInterfaceObj = getElanInterfaceFromCache(elanInterfaceName);
352         if (elanInterfaceObj != null) {
353             return elanInterfaceObj;
354         }
355         InstanceIdentifier<ElanInterface> elanInterfaceId = getElanInterfaceConfigurationDataPathId(elanInterfaceName);
356         Optional<ElanInterface> existingElanInterface = MDSALUtil.read(broker,
357                 LogicalDatastoreType.CONFIGURATION, elanInterfaceId);
358         if (existingElanInterface.isPresent()) {
359             return existingElanInterface.get();
360         }
361         return null;
362     }
363
364     public static EtreeInterface getEtreeInterfaceByElanInterfaceName(DataBroker broker, String elanInterfaceName) {
365         ElanInterface elanInterface = getElanInterfaceByElanInterfaceName(broker, elanInterfaceName);
366         return elanInterface.getAugmentation(EtreeInterface.class);
367     }
368
369     public static InstanceIdentifier<ElanInterface> getElanInterfaceConfigurationDataPathId(String interfaceName) {
370         return InstanceIdentifier.builder(ElanInterfaces.class)
371                 .child(ElanInterface.class, new ElanInterfaceKey(interfaceName)).build();
372     }
373
374     // elan-state Operational container
375     public static Elan getElanByName(DataBroker broker, String elanInstanceName) {
376         InstanceIdentifier<Elan> elanIdentifier = getElanInstanceOperationalDataPath(elanInstanceName);
377         Optional<Elan> elanInstance = MDSALUtil.read(broker, LogicalDatastoreType.OPERATIONAL,
378                 elanIdentifier);
379         if (elanInstance.isPresent()) {
380             return elanInstance.get();
381         }
382         return null;
383     }
384
385     public static InstanceIdentifier<Elan> getElanInstanceOperationalDataPath(String elanInstanceName) {
386         return InstanceIdentifier.builder(ElanState.class).child(Elan.class, new ElanKey(elanInstanceName)).build();
387     }
388
389     // grouping of forwarding-entries
390     public MacEntry getInterfaceMacEntriesOperationalDataPath(String interfaceName, PhysAddress physAddress) {
391         InstanceIdentifier<MacEntry> existingMacEntryId = getInterfaceMacEntriesIdentifierOperationalDataPath(
392                 interfaceName, physAddress);
393         Optional<MacEntry> existingInterfaceMacEntry = read(broker,
394                 LogicalDatastoreType.OPERATIONAL, existingMacEntryId);
395         if (existingInterfaceMacEntry.isPresent()) {
396             return existingInterfaceMacEntry.get();
397         }
398         return null;
399     }
400
401     public MacEntry getInterfaceMacEntriesOperationalDataPathFromId(InstanceIdentifier identifier) {
402         Optional<MacEntry> existingInterfaceMacEntry = read(broker,
403                 LogicalDatastoreType.OPERATIONAL, identifier);
404         if (existingInterfaceMacEntry.isPresent()) {
405             return existingInterfaceMacEntry.get();
406         }
407         return null;
408     }
409
410     public static InstanceIdentifier<MacEntry> getInterfaceMacEntriesIdentifierOperationalDataPath(String interfaceName,
411             PhysAddress physAddress) {
412         return InstanceIdentifier.builder(ElanInterfaceForwardingEntries.class)
413                 .child(ElanInterfaceMac.class, new ElanInterfaceMacKey(interfaceName))
414                 .child(MacEntry.class, new MacEntryKey(physAddress)).build();
415
416     }
417
418     // elan-forwarding-tables Operational container
419     public MacEntry getMacTableByElanName(String elanName, PhysAddress physAddress) {
420         InstanceIdentifier<MacEntry> macId = getMacEntryOperationalDataPath(elanName, physAddress);
421         Optional<MacEntry> existingElanMacEntry = read(broker,
422                 LogicalDatastoreType.OPERATIONAL, macId);
423         if (existingElanMacEntry.isPresent()) {
424             return existingElanMacEntry.get();
425         }
426         return null;
427     }
428
429     public MacEntry getMacEntryFromElanMacId(InstanceIdentifier identifier) {
430         Optional<MacEntry> existingInterfaceMacEntry = read(broker,
431                 LogicalDatastoreType.OPERATIONAL, identifier);
432         if (existingInterfaceMacEntry.isPresent()) {
433             return existingInterfaceMacEntry.get();
434         }
435         return null;
436     }
437
438     public static InstanceIdentifier<MacEntry> getMacEntryOperationalDataPath(String elanName,
439             PhysAddress physAddress) {
440         return InstanceIdentifier.builder(ElanForwardingTables.class).child(MacTable.class, new MacTableKey(elanName))
441                 .child(MacEntry.class, new MacEntryKey(physAddress)).build();
442     }
443
444     public static InstanceIdentifier<MacTable> getElanMacTableOperationalDataPath(String elanName) {
445         return InstanceIdentifier.builder(ElanForwardingTables.class).child(MacTable.class, new MacTableKey(elanName))
446                 .build();
447     }
448
449     // elan-interface-forwarding-entries Operational container
450     public ElanInterfaceMac getElanInterfaceMacByInterfaceName(String interfaceName) {
451         InstanceIdentifier<ElanInterfaceMac> elanInterfaceId = getElanInterfaceMacEntriesOperationalDataPath(
452                 interfaceName);
453         Optional<ElanInterfaceMac> existingElanInterface = read(broker,
454                 LogicalDatastoreType.OPERATIONAL, elanInterfaceId);
455         if (existingElanInterface.isPresent()) {
456             return existingElanInterface.get();
457         }
458         return null;
459     }
460
461     /**
462      * Gets the elan interface mac addresses.
463      *
464      * @param interfaceName
465      *            the interface name
466      * @return the elan interface mac addresses
467      */
468     public List<PhysAddress> getElanInterfaceMacAddresses(String interfaceName) {
469         List<PhysAddress> macAddresses = new ArrayList<>();
470         ElanInterfaceMac elanInterfaceMac = getElanInterfaceMacByInterfaceName(interfaceName);
471         if (elanInterfaceMac != null && elanInterfaceMac.getMacEntry() != null) {
472             List<MacEntry> macEntries = elanInterfaceMac.getMacEntry();
473             for (MacEntry macEntry : macEntries) {
474                 macAddresses.add(macEntry.getMacAddress());
475             }
476         }
477         return macAddresses;
478     }
479
480     public static InstanceIdentifier<ElanInterfaceMac> getElanInterfaceMacEntriesOperationalDataPath(
481             String interfaceName) {
482         return InstanceIdentifier.builder(ElanInterfaceForwardingEntries.class)
483                 .child(ElanInterfaceMac.class, new ElanInterfaceMacKey(interfaceName)).build();
484     }
485
486     /**
487      * Returns the list of Interfaces that belong to an Elan on an specific DPN.
488      * Data retrieved from Elan's operational DS: elan-dpn-interfaces container
489      *
490      * @param elanInstanceName
491      *            name of the Elan to which the interfaces must belong to
492      * @param dpId
493      *            Id of the DPN where the interfaces are located
494      * @return the elan interface Info
495      */
496     public DpnInterfaces getElanInterfaceInfoByElanDpn(String elanInstanceName, BigInteger dpId) {
497         InstanceIdentifier<DpnInterfaces> elanDpnInterfacesId = getElanDpnInterfaceOperationalDataPath(elanInstanceName,
498                 dpId);
499         Optional<DpnInterfaces> elanDpnInterfaces = read(broker,
500                 LogicalDatastoreType.OPERATIONAL, elanDpnInterfacesId);
501         if (elanDpnInterfaces.isPresent()) {
502             return elanDpnInterfaces.get();
503         }
504         return null;
505     }
506
507     /**
508      * Returns the InstanceIdentifier that points to the Interfaces of an Elan
509      * in a given DPN in the Operational DS. Data retrieved from Elans's
510      * operational DS: dpn-interfaces list
511      *
512      * @param elanInstanceName
513      *            name of the Elan to which the interfaces must belong to
514      * @param dpId
515      *            Id of the DPN where the interfaces are located
516      * @return the elan dpn interface
517      */
518     public static InstanceIdentifier<DpnInterfaces> getElanDpnInterfaceOperationalDataPath(String elanInstanceName,
519             BigInteger dpId) {
520         return InstanceIdentifier.builder(ElanDpnInterfaces.class)
521                 .child(ElanDpnInterfacesList.class, new ElanDpnInterfacesListKey(elanInstanceName))
522                 .child(DpnInterfaces.class, new DpnInterfacesKey(dpId)).build();
523     }
524
525     // elan-tag-name-map Operational Container
526     public ElanTagName getElanInfoByElanTag(long elanTag) {
527         InstanceIdentifier<ElanTagName> elanId = getElanInfoEntriesOperationalDataPath(elanTag);
528         Optional<ElanTagName> existingElanInfo = read(broker,
529                 LogicalDatastoreType.OPERATIONAL, elanId);
530         if (existingElanInfo.isPresent()) {
531             return existingElanInfo.get();
532         }
533         return null;
534     }
535
536     public EtreeLeafTagName getEtreeLeafTagByElanTag(long elanTag) {
537         InstanceIdentifier<ElanTagName> elanId = getElanInfoEntriesOperationalDataPath(elanTag);
538         Optional<ElanTagName> existingElanInfo = read(broker,
539                 LogicalDatastoreType.OPERATIONAL, elanId);
540         if (existingElanInfo.isPresent()) {
541             ElanTagName elanTagName = existingElanInfo.get();
542             EtreeLeafTagName etreeAugmentation = elanTagName.getAugmentation(EtreeLeafTagName.class);
543             return etreeAugmentation;
544         }
545         return null;
546     }
547
548     public static InstanceIdentifier<ElanTagName> getElanInfoEntriesOperationalDataPath(long elanTag) {
549         return InstanceIdentifier.builder(ElanTagNameMap.class).child(ElanTagName.class, new ElanTagNameKey(elanTag))
550                 .build();
551     }
552
553     // interface-index-tag operational container
554     public Optional<IfIndexInterface> getInterfaceInfoByInterfaceTag(long interfaceTag) {
555         InstanceIdentifier<IfIndexInterface> interfaceId = getInterfaceInfoEntriesOperationalDataPath(interfaceTag);
556         return read(broker, LogicalDatastoreType.OPERATIONAL, interfaceId);
557     }
558
559     public static InstanceIdentifier<IfIndexInterface> getInterfaceInfoEntriesOperationalDataPath(long interfaceTag) {
560         return InstanceIdentifier.builder(IfIndexesInterfaceMap.class)
561                 .child(IfIndexInterface.class, new IfIndexInterfaceKey((int) interfaceTag)).build();
562     }
563
564     public static InstanceIdentifier<ElanDpnInterfacesList> getElanDpnOperationDataPath(String elanInstanceName) {
565         return InstanceIdentifier.builder(ElanDpnInterfaces.class)
566                 .child(ElanDpnInterfacesList.class, new ElanDpnInterfacesListKey(elanInstanceName)).build();
567     }
568
569     public ElanDpnInterfacesList getElanDpnInterfacesList(String elanName) {
570         InstanceIdentifier<ElanDpnInterfacesList> elanDpnInterfaceId = getElanDpnOperationDataPath(elanName);
571         Optional<ElanDpnInterfacesList> existingElanDpnInterfaces = read(broker,
572                 LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId);
573         if (existingElanDpnInterfaces.isPresent()) {
574             return existingElanDpnInterfaces.get();
575         }
576         return null;
577     }
578
579     public ElanDpnInterfaces getElanDpnInterfacesList() {
580         InstanceIdentifier<ElanDpnInterfaces> elanDpnInterfaceId = InstanceIdentifier.builder(ElanDpnInterfaces.class)
581                 .build();
582         Optional<ElanDpnInterfaces> existingElanDpnInterfaces = read(broker,
583                 LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId);
584         if (existingElanDpnInterfaces.isPresent()) {
585             return existingElanDpnInterfaces.get();
586         }
587         return null;
588     }
589
590     /**
591      * This method is useful get all ELAN participating CSS dpIds to install
592      * program remote dmac entries and updating remote bc groups for tor
593      * integration.
594      *
595      * @param elanInstanceName
596      *            the elan instance name
597      * @return list of dpIds
598      */
599     public List<BigInteger> getParticipatingDPNsInElanInstance(String elanInstanceName) {
600         List<BigInteger> dpIds = new ArrayList<>();
601         InstanceIdentifier<ElanDpnInterfacesList> elanDpnInterfaceId = getElanDpnOperationDataPath(elanInstanceName);
602         Optional<ElanDpnInterfacesList> existingElanDpnInterfaces = read(broker,
603                 LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId);
604         if (!existingElanDpnInterfaces.isPresent()) {
605             return dpIds;
606         }
607         List<DpnInterfaces> dpnInterfaces = existingElanDpnInterfaces.get().getDpnInterfaces();
608         for (DpnInterfaces dpnInterface : dpnInterfaces) {
609             dpIds.add(dpnInterface.getDpId());
610         }
611         return dpIds;
612     }
613
614     /**
615      * To check given dpId is already present in Elan instance. This can be used
616      * to program flow entry in external tunnel table when a new access port
617      * added for first time into the ELAN instance
618      *
619      * @param dpId
620      *            the dp id
621      * @param elanInstanceName
622      *            the elan instance name
623      * @return true if dpId is already present, otherwise return false
624      */
625     public boolean isDpnAlreadyPresentInElanInstance(BigInteger dpId, String elanInstanceName) {
626         boolean isDpIdPresent = false;
627         InstanceIdentifier<ElanDpnInterfacesList> elanDpnInterfaceId = getElanDpnOperationDataPath(elanInstanceName);
628         Optional<ElanDpnInterfacesList> existingElanDpnInterfaces = read(broker,
629                 LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId);
630         if (!existingElanDpnInterfaces.isPresent()) {
631             return isDpIdPresent;
632         }
633         List<DpnInterfaces> dpnInterfaces = existingElanDpnInterfaces.get().getDpnInterfaces();
634         for (DpnInterfaces dpnInterface : dpnInterfaces) {
635             if (dpnInterface.getDpId().equals(dpId)) {
636                 isDpIdPresent = true;
637                 break;
638             }
639         }
640         return isDpIdPresent;
641     }
642
643     public ElanForwardingTables getElanForwardingList() {
644         InstanceIdentifier<ElanForwardingTables> elanForwardingTableId = InstanceIdentifier
645                 .builder(ElanForwardingTables.class).build();
646         Optional<ElanForwardingTables> existingElanForwardingList = read(broker,
647                 LogicalDatastoreType.OPERATIONAL, elanForwardingTableId);
648         if (existingElanForwardingList.isPresent()) {
649             return existingElanForwardingList.get();
650         }
651         return null;
652     }
653
654     /**
655      * Gets the elan mac table.
656      *
657      * @param elanName
658      *            the elan name
659      * @return the elan mac table
660      */
661     public MacTable getElanMacTable(String elanName) {
662         InstanceIdentifier<MacTable> elanMacTableId = getElanMacTableOperationalDataPath(elanName);
663         Optional<MacTable> existingElanMacTable = read(broker,
664                 LogicalDatastoreType.OPERATIONAL, elanMacTableId);
665         if (existingElanMacTable.isPresent()) {
666             return existingElanMacTable.get();
667         }
668         return null;
669     }
670
671     public static long getElanLocalBCGId(long elanTag) {
672         return ElanConstants.ELAN_GID_MIN + (elanTag % ElanConstants.ELAN_GID_MIN * 2 - 1);
673     }
674
675     public static long getElanRemoteBCGId(long elanTag) {
676         return ElanConstants.ELAN_GID_MIN + elanTag % ElanConstants.ELAN_GID_MIN * 2;
677     }
678
679     public static long getEtreeLeafLocalBCGId(long etreeLeafTag) {
680         return ElanConstants.ELAN_GID_MIN + (etreeLeafTag % ElanConstants.ELAN_GID_MIN * 2 - 1);
681     }
682
683     public static long getEtreeLeafRemoteBCGId(long etreeLeafTag) {
684         return ElanConstants.ELAN_GID_MIN + etreeLeafTag % ElanConstants.ELAN_GID_MIN * 2;
685     }
686
687     public static BigInteger getElanMetadataLabel(long elanTag) {
688         return BigInteger.valueOf(elanTag).shiftLeft(24);
689     }
690
691     public static BigInteger getElanMetadataLabel(long elanTag, boolean isSHFlagSet) {
692         int shBit = isSHFlagSet ? 1 : 0;
693         return BigInteger.valueOf(elanTag).shiftLeft(24).or(BigInteger.valueOf(shBit));
694     }
695
696     public static BigInteger getElanMetadataLabel(long elanTag, int lportTag) {
697         return getElanMetadataLabel(elanTag).or(MetaDataUtil.getLportTagMetaData(lportTag));
698     }
699
700     public static BigInteger getElanMetadataMask() {
701         return MetaDataUtil.METADATA_MASK_SERVICE.or(MetaDataUtil.METADATA_MASK_LPORT_TAG);
702     }
703
704     /**
705      * Setting INTERNAL_TUNNEL_TABLE, SMAC, DMAC, UDMAC in this DPN and optionally in other DPNs.
706      *
707      * @param elanInfo
708      *            the elan info
709      * @param interfaceInfo
710      *            the interface info
711      * @param macTimeout
712      *            the mac timeout
713      * @param macAddress
714      *            the mac address
715      * @param configureRemoteFlows
716      *            true if remote dmac flows should be configured as well
717      * @param writeFlowGroupTx
718      *            the flow group tx
719      * @throws ElanException in case of issues creating the flow objects
720      */
721     public void setupMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, long macTimeout,
722             String macAddress, boolean configureRemoteFlows, WriteTransaction writeFlowGroupTx) throws ElanException {
723         synchronized (macAddress) {
724             LOG.debug("Acquired lock for mac : " + macAddress + ". Proceeding with install operation.");
725             setupKnownSmacFlow(elanInfo, interfaceInfo, macTimeout, macAddress, mdsalManager,
726                     writeFlowGroupTx);
727             setupOrigDmacFlows(elanInfo, interfaceInfo, macAddress, configureRemoteFlows, mdsalManager,
728                     broker, writeFlowGroupTx);
729         }
730     }
731
732     /**
733      * Setting INTERNAL_TUNNEL_TABLE, SMAC, DMAC, UDMAC in this DPN and on other DPNs.
734      *
735      * @param elanInfo
736      *            the elan info
737      * @param interfaceInfo
738      *            the interface info
739      * @param macTimeout
740      *            the mac timeout
741      * @param macAddress
742      *            the mac address
743      * @param writeFlowGroupTx
744      *            the flow group tx
745      * @throws ElanException in case of issues creating the flow objects
746      */
747     public void setupMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, long macTimeout,
748                               String macAddress, WriteTransaction writeFlowGroupTx) throws ElanException {
749         setupMacFlows(elanInfo, interfaceInfo, macTimeout, macAddress, true, writeFlowGroupTx);
750     }
751
752     public void setupDMacFlowonRemoteDpn(ElanInstance elanInfo, InterfaceInfo interfaceInfo, BigInteger dstDpId,
753             String macAddress, WriteTransaction writeFlowTx) throws ElanException {
754         synchronized (macAddress) {
755             LOG.debug("Acquired lock for mac : " + macAddress + ". Proceeding with install operation.");
756             setupOrigDmacFlowsonRemoteDpn(elanInfo, interfaceInfo, dstDpId, macAddress, writeFlowTx);
757         }
758     }
759
760     /**
761      * Inserts a Flow in SMAC table to state that the MAC has already been
762      * learnt.
763      */
764     private void setupKnownSmacFlow(ElanInstance elanInfo, InterfaceInfo interfaceInfo, long macTimeout,
765             String macAddress, IMdsalApiManager mdsalApiManager, WriteTransaction writeFlowGroupTx) {
766         FlowEntity flowEntity = buildKnownSmacFlow(elanInfo, interfaceInfo, macTimeout, macAddress);
767         mdsalApiManager.addFlowToTx(flowEntity, writeFlowGroupTx);
768         if (LOG.isDebugEnabled()) {
769             LOG.debug("Known Smac flow entry created for elan Name:{}, logical Interface port:{} and mac address:{}",
770                     elanInfo.getElanInstanceName(), elanInfo.getDescription(), macAddress);
771         }
772     }
773
774     public FlowEntity buildKnownSmacFlow(ElanInstance elanInfo, InterfaceInfo interfaceInfo, long macTimeout,
775             String macAddress) {
776         int lportTag = interfaceInfo.getInterfaceTag();
777         // Matching metadata and eth_src fields
778         List<MatchInfo> mkMatches = new ArrayList<>();
779         mkMatches.add(new MatchInfo(MatchFieldType.metadata, new BigInteger[] {
780                 getElanMetadataLabel(elanInfo.getElanTag(), lportTag), getElanMetadataMask() }));
781         mkMatches.add(new MatchInfo(MatchFieldType.eth_src, new String[] { macAddress }));
782         List<InstructionInfo> mkInstructions = new ArrayList<>();
783         mkInstructions.add(new InstructionInfo(InstructionType.goto_table, new long[] { NwConstants.ELAN_DMAC_TABLE }));
784
785         BigInteger dpId = interfaceInfo.getDpId();
786         long elanTag = getElanTag(broker, elanInfo, interfaceInfo);
787         FlowEntity flowEntity = MDSALUtil.buildFlowEntity(dpId, NwConstants.ELAN_SMAC_TABLE,
788                 getKnownDynamicmacFlowRef(NwConstants.ELAN_SMAC_TABLE, dpId, lportTag, macAddress, elanTag), 20,
789                 elanInfo.getDescription(), (int) macTimeout, 0,
790                 ElanConstants.COOKIE_ELAN_KNOWN_SMAC.add(BigInteger.valueOf(elanTag)), mkMatches, mkInstructions);
791         flowEntity.setStrictFlag(true);
792         flowEntity.setSendFlowRemFlag(macTimeout != 0); // If Mac timeout is 0,
793                                                         // the flow wont be
794                                                         // deleted
795                                                         // automatically, so no
796                                                         // need to get notified
797         return flowEntity;
798     }
799
800     private static Long getElanTag(DataBroker broker, ElanInstance elanInfo, InterfaceInfo interfaceInfo) {
801         EtreeInterface etreeInterface = getEtreeInterfaceByElanInterfaceName(broker, interfaceInfo.getInterfaceName());
802         if (etreeInterface == null || etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
803             return elanInfo.getElanTag();
804         } else { // Leaf
805             EtreeInstance etreeInstance = elanInfo.getAugmentation(EtreeInstance.class);
806             if (etreeInstance == null) {
807                 LOG.warn("EtreeInterface " + interfaceInfo.getInterfaceName() + " is connected to a non-Etree network: "
808                         + elanInfo.getElanInstanceName());
809                 return elanInfo.getElanTag();
810             } else {
811                 return etreeInstance.getEtreeLeafTagVal().getValue();
812             }
813         }
814     }
815
816     /**
817      * Installs a Flow in INTERNAL_TUNNEL_TABLE of the affected DPN that sends
818      * the packet through the specified interface if the tunnel_id matches the
819      * interface's lportTag.
820      *
821      * @param interfaceInfo
822      *            the interface info
823      * @param mdsalApiManager
824      *            the mdsal API manager
825      * @param writeFlowGroupTx
826      *            the writeFLowGroup tx
827      */
828     public void setupTermDmacFlows(InterfaceInfo interfaceInfo, IMdsalApiManager mdsalApiManager,
829             WriteTransaction writeFlowGroupTx) {
830         BigInteger dpId = interfaceInfo.getDpId();
831         int lportTag = interfaceInfo.getInterfaceTag();
832         Flow flow = MDSALUtil.buildFlowNew(NwConstants.INTERNAL_TUNNEL_TABLE,
833                 getIntTunnelTableFlowRef(NwConstants.INTERNAL_TUNNEL_TABLE, lportTag), 5,
834                 String.format("%s:%d", "ITM Flow Entry ", lportTag), 0, 0,
835                 ITMConstants.COOKIE_ITM.add(BigInteger.valueOf(lportTag)),
836                 getTunnelIdMatchForFilterEqualsLPortTag(lportTag),
837                 getInstructionsInPortForOutGroup(interfaceInfo.getInterfaceName()));
838         mdsalApiManager.addFlowToTx(dpId, flow, writeFlowGroupTx);
839         if (LOG.isDebugEnabled()) {
840             LOG.debug("Terminating service table flow entry created on dpn:{} for logical Interface port:{}", dpId,
841                     interfaceInfo.getPortName());
842         }
843     }
844
845     /**
846      * Constructs the FlowName for flows installed in the Internal Tunnel Table,
847      * consisting in tableId + elanTag.
848      *
849      * @param tableId
850      *            table Id
851      * @param elanTag
852      *            elan Tag
853      * @return the Internal tunnel
854      */
855     public static String getIntTunnelTableFlowRef(short tableId, int elanTag) {
856         return new StringBuffer().append(tableId).append(elanTag).toString();
857     }
858
859     /**
860      * Constructs the Matches that checks that the tunnel_id field contains a
861      * specific lportTag.
862      *
863      * @param lportTag
864      *            lportTag that must be checked against the tunnel_id field
865      * @return the list of match Info
866      */
867     public static List<MatchInfo> getTunnelIdMatchForFilterEqualsLPortTag(int lportTag) {
868         List<MatchInfo> mkMatches = new ArrayList<>();
869         // Matching metadata
870         mkMatches.add(new MatchInfo(MatchFieldType.tunnel_id, new BigInteger[] { BigInteger.valueOf(lportTag) }));
871         return mkMatches;
872     }
873
874     /**
875      * Constructs the Instructions that take the packet over a given interface.
876      *
877      * @param ifName
878      *            Name of the interface where the packet must be sent over. It
879      *            can be a local interface or a tunnel interface (internal or
880      *            external)
881      * @return the Instruction
882      */
883     public List<Instruction> getInstructionsInPortForOutGroup(String ifName) {
884         List<Instruction> mkInstructions = new ArrayList<>();
885         List<Action> actions = getEgressActionsForInterface(ifName, /* tunnelKey */ null);
886
887         mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
888         return mkInstructions;
889     }
890
891     /**
892      * Returns the list of Actions to be taken when sending the packet through
893      * an Elan interface. Note that this interface can refer to an ElanInterface
894      * where the Elan VM is attached to a DPN or an ITM tunnel interface where
895      * Elan traffic can be sent through. In this latter case, the tunnelKey is
896      * mandatory and it can hold serviceId for internal tunnels or the VNI for
897      * external tunnels.
898      *
899      * @param ifName
900      *            the if name
901      * @param tunnelKey
902      *            the tunnel key
903      * @return the egress actions for interface
904      */
905     public List<Action> getEgressActionsForInterface(String ifName, Long tunnelKey) {
906         List<Action> listAction = new ArrayList<>();
907         try {
908             GetEgressActionsForInterfaceInput getEgressActionInput = new GetEgressActionsForInterfaceInputBuilder()
909                     .setIntfName(ifName).setTunnelKey(tunnelKey).build();
910             Future<RpcResult<GetEgressActionsForInterfaceOutput>> result = interfaceManagerRpcService
911                     .getEgressActionsForInterface(getEgressActionInput);
912             RpcResult<GetEgressActionsForInterfaceOutput> rpcResult = result.get();
913             if (!rpcResult.isSuccessful()) {
914                 LOG.warn("RPC Call to Get egress actions for interface {} returned with Errors {}", ifName,
915                         rpcResult.getErrors());
916             } else {
917                 List<Action> actions = rpcResult.getResult().getAction();
918                 listAction = actions;
919             }
920         } catch (InterruptedException | ExecutionException e) {
921             LOG.warn("Exception when egress actions for interface {}", ifName, e);
922         }
923         return listAction;
924     }
925
926     private void setupOrigDmacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
927                                     boolean configureRemoteFlows, IMdsalApiManager mdsalApiManager,
928                                     DataBroker broker, WriteTransaction writeFlowGroupTx)
929                                     throws ElanException {
930         BigInteger dpId = interfaceInfo.getDpId();
931         String ifName = interfaceInfo.getInterfaceName();
932         long ifTag = interfaceInfo.getInterfaceTag();
933         String elanInstanceName = elanInfo.getElanInstanceName();
934
935         Long elanTag = getElanTag(broker, elanInfo, interfaceInfo);
936
937         setupLocalDmacFlow(elanTag, dpId, ifName, macAddress, elanInstanceName, mdsalApiManager, ifTag,
938                 writeFlowGroupTx);
939         LOG.debug("Dmac flow entry created for elan Name:{}, logical port Name:{} mand mac address:{} "
940                                     + "on dpn:{}", elanInstanceName, interfaceInfo.getPortName(), macAddress, dpId);
941
942         if (!configureRemoteFlows) {
943             return;
944         }
945
946         List<DpnInterfaces> elanDpns = getInvolvedDpnsInElan(elanInstanceName);
947         if (elanDpns == null) {
948             return;
949         }
950
951         for (DpnInterfaces elanDpn : elanDpns) {
952
953             if (elanDpn.getDpId().equals(dpId)) {
954                 continue;
955             }
956
957             // Check for the Remote DPN present in Inventory Manager
958             if (!isDpnPresent(elanDpn.getDpId())) {
959                 continue;
960             }
961
962             // For remote DPNs a flow is needed to indicate that
963             // packets of this ELAN going to this MAC
964             // need to be forwarded through the appropiated ITM
965             // tunnel
966             setupRemoteDmacFlow(elanDpn.getDpId(), // srcDpn (the remote DPN in this case)
967                     dpId, // dstDpn (the local DPN)
968                     interfaceInfo.getInterfaceTag(), // lportTag of the local interface
969                     elanTag, // identifier of the Elan
970                     macAddress, // MAC to be programmed in remote DPN
971                     elanInstanceName, writeFlowGroupTx, ifName, elanInfo);
972             LOG.debug("Dmac flow entry created for elan Name:{}, logical port Name:{} and mac address:{} on"
973                         + " dpn:{}", elanInstanceName, interfaceInfo.getPortName(), macAddress, elanDpn.getDpId());
974         }
975
976         // TODO: Make sure that the same is performed against the ElanDevices.
977     }
978
979     private void setupOrigDmacFlowsonRemoteDpn(ElanInstance elanInfo, InterfaceInfo interfaceInfo,
980             BigInteger dstDpId, String macAddress, WriteTransaction writeFlowTx) throws ElanException {
981         BigInteger dpId = interfaceInfo.getDpId();
982         String elanInstanceName = elanInfo.getElanInstanceName();
983         List<DpnInterfaces> remoteFEs = getInvolvedDpnsInElan(elanInstanceName);
984         for (DpnInterfaces remoteFE : remoteFEs) {
985             Long elanTag = elanInfo.getElanTag();
986             if (remoteFE.getDpId().equals(dstDpId)) {
987                 // Check for the Remote DPN present in Inventory Manager
988                 setupRemoteDmacFlow(dstDpId, dpId, interfaceInfo.getInterfaceTag(), elanTag, macAddress,
989                         elanInstanceName, writeFlowTx, interfaceInfo.getInterfaceName(), elanInfo);
990                 if (LOG.isDebugEnabled()) {
991                     LOG.debug("Dmac flow entry created for elan Name:{}, logical port Name:{} and mac address {} on"
992                             + " dpn:{}", elanInstanceName, interfaceInfo.getPortName(), macAddress, remoteFE.getDpId());
993                 }
994                 break;
995             }
996         }
997     }
998
999     @SuppressWarnings("unchecked")
1000     public List<DpnInterfaces> getInvolvedDpnsInElan(String elanName) {
1001         List<DpnInterfaces> dpns = elanInstanceManager.getElanDPNByName(elanName);
1002         if (dpns == null) {
1003             return Collections.emptyList();
1004         }
1005         return dpns;
1006     }
1007
1008     private void setupLocalDmacFlow(long elanTag, BigInteger dpId, String ifName, String macAddress,
1009             String displayName, IMdsalApiManager mdsalApiManager, long ifTag, WriteTransaction writeFlowGroupTx) {
1010         Flow flowEntity = buildLocalDmacFlowEntry(elanTag, dpId, ifName, macAddress, displayName, ifTag);
1011         mdsalApiManager.addFlowToTx(dpId, flowEntity, writeFlowGroupTx);
1012         installEtreeLocalDmacFlow(elanTag, dpId, ifName, macAddress, displayName, mdsalApiManager, ifTag,
1013                 writeFlowGroupTx);
1014     }
1015
1016     private void installEtreeLocalDmacFlow(long elanTag, BigInteger dpId, String ifName, String macAddress,
1017             String displayName, IMdsalApiManager mdsalApiManager, long ifTag, WriteTransaction writeFlowGroupTx) {
1018         EtreeInterface etreeInterface = getEtreeInterfaceByElanInterfaceName(broker, ifName);
1019         if (etreeInterface != null) {
1020             if (etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
1021                 EtreeLeafTagName etreeTagName = getEtreeLeafTagByElanTag(elanTag);
1022                 if (etreeTagName == null) {
1023                     LOG.warn("Interface " + ifName + " seems like it belongs to Etree but etreeTagName from elanTag "
1024                             + elanTag + " is null.");
1025                 } else {
1026                     Flow flowEntity = buildLocalDmacFlowEntry(etreeTagName.getEtreeLeafTag().getValue(), dpId, ifName,
1027                             macAddress, displayName, ifTag);
1028                     mdsalApiManager.addFlowToTx(dpId, flowEntity, writeFlowGroupTx);
1029                 }
1030             }
1031         }
1032     }
1033
1034     public static String getKnownDynamicmacFlowRef(short tableId, BigInteger dpId, long lporTag, String macAddress,
1035             long elanTag) {
1036         return new StringBuffer().append(tableId).append(elanTag).append(dpId).append(lporTag).append(macAddress)
1037                 .toString();
1038     }
1039
1040     public static String getKnownDynamicmacFlowRef(short tableId, BigInteger dpId, BigInteger remoteDpId,
1041             String macAddress, long elanTag) {
1042         return new StringBuffer().append(tableId).append(elanTag).append(dpId).append(remoteDpId).append(macAddress)
1043                 .toString();
1044     }
1045
1046     private static String getKnownDynamicmacFlowRef(short elanDmacTable, BigInteger dpId, String extDeviceNodeId,
1047             String dstMacAddress, long elanTag, boolean shFlag) {
1048         return new StringBuffer().append(elanDmacTable).append(elanTag).append(dpId).append(extDeviceNodeId)
1049                 .append(dstMacAddress).append(shFlag).toString();
1050     }
1051
1052     /**
1053      * Builds the flow to be programmed in the DMAC table of the local DPN (that
1054      * is, where the MAC is attached to). This flow consists in:
1055      *
1056      * <p>Match: + elanTag in metadata + packet goes to a MAC locally attached
1057      * Actions: + optionally, pop-vlan + set-vlan-id + output to ifName's
1058      * portNumber
1059      *
1060      * @param elanTag
1061      *            the elan tag
1062      * @param dpId
1063      *            the dp id
1064      * @param ifName
1065      *            the if name
1066      * @param macAddress
1067      *            the mac address
1068      * @param displayName
1069      *            the display name
1070      * @param ifTag
1071      *            the if tag
1072      * @return the flow
1073      */
1074     public Flow buildLocalDmacFlowEntry(long elanTag, BigInteger dpId, String ifName, String macAddress,
1075             String displayName, long ifTag) {
1076         List<MatchInfo> mkMatches = new ArrayList<>();
1077         mkMatches.add(new MatchInfo(MatchFieldType.metadata,
1078                 new BigInteger[] { getElanMetadataLabel(elanTag), MetaDataUtil.METADATA_MASK_SERVICE }));
1079         mkMatches.add(new MatchInfo(MatchFieldType.eth_dst, new String[] { macAddress }));
1080
1081         List<Instruction> mkInstructions = new ArrayList<>();
1082         List<Action> actions = getEgressActionsForInterface(ifName, /* tunnelKey */ null);
1083         mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
1084         Flow flow = MDSALUtil.buildFlowNew(NwConstants.ELAN_DMAC_TABLE,
1085                 getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, ifTag, macAddress, elanTag), 20,
1086                 displayName, 0, 0, ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(BigInteger.valueOf(elanTag)), mkMatches,
1087                 mkInstructions);
1088
1089         return flow;
1090     }
1091
1092     public void setupRemoteDmacFlow(BigInteger srcDpId, BigInteger destDpId, int lportTag, long elanTag,
1093             String macAddress, String displayName, WriteTransaction writeFlowGroupTx, String interfaceName,
1094             ElanInstance elanInstance) throws ElanException {
1095         Flow flowEntity = buildRemoteDmacFlowEntry(srcDpId, destDpId, lportTag, elanTag, macAddress, displayName,
1096                 elanInstance);
1097         mdsalManager.addFlowToTx(srcDpId, flowEntity, writeFlowGroupTx);
1098         setupEtreeRemoteDmacFlow(srcDpId, destDpId, lportTag, elanTag, macAddress, displayName, interfaceName,
1099                 writeFlowGroupTx, elanInstance);
1100     }
1101
1102     private void setupEtreeRemoteDmacFlow(BigInteger srcDpId, BigInteger destDpId, int lportTag, long elanTag,
1103                                 String macAddress, String displayName, String interfaceName,
1104                                 WriteTransaction writeFlowGroupTx, ElanInstance elanInstance) throws ElanException {
1105         Flow flowEntity;
1106         EtreeInterface etreeInterface = getEtreeInterfaceByElanInterfaceName(broker, interfaceName);
1107         if (etreeInterface != null) {
1108             if (etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
1109                 EtreeLeafTagName etreeTagName = getEtreeLeafTagByElanTag(elanTag);
1110                 if (etreeTagName == null) {
1111                     LOG.warn("Interface " + interfaceName
1112                             + " seems like it belongs to Etree but etreeTagName from elanTag " + elanTag + " is null.");
1113                 } else {
1114                     flowEntity = buildRemoteDmacFlowEntry(srcDpId, destDpId, lportTag,
1115                             etreeTagName.getEtreeLeafTag().getValue(), macAddress, displayName, elanInstance);
1116                     mdsalManager.addFlowToTx(srcDpId, flowEntity, writeFlowGroupTx);
1117                 }
1118             }
1119         }
1120     }
1121
1122     /**
1123      * Builds a Flow to be programmed in a remote DPN's DMAC table. This flow
1124      * consists in: Match: + elanTag in packet's metadata + packet going to a
1125      * MAC known to be located in another DPN Actions: + set_tunnel_id(lportTag)
1126      * + output ITM internal tunnel interface with the other DPN
1127      *
1128      * @param srcDpId
1129      *            the src Dpn Id
1130      * @param destDpId
1131      *            dest Dp Id
1132      * @param lportTag
1133      *            lport Tag
1134      * @param elanTag
1135      *            elan Tag
1136      * @param macAddress
1137      *            macAddress
1138      * @param displayName
1139      *            display Name
1140      * @return the flow remote Dmac
1141      * @throws ElanException in case of issues creating the flow objects
1142      */
1143     @SuppressWarnings("checkstyle:IllegalCatch")
1144     public Flow buildRemoteDmacFlowEntry(BigInteger srcDpId, BigInteger destDpId, int lportTag, long elanTag,
1145             String macAddress, String displayName, ElanInstance elanInstance) throws ElanException {
1146         List<MatchInfo> mkMatches = new ArrayList<>();
1147         mkMatches.add(new MatchInfo(MatchFieldType.metadata,
1148                 new BigInteger[] { getElanMetadataLabel(elanTag), MetaDataUtil.METADATA_MASK_SERVICE }));
1149         mkMatches.add(new MatchInfo(MatchFieldType.eth_dst, new String[] { macAddress }));
1150
1151         List<Instruction> mkInstructions = new ArrayList<>();
1152
1153         // List of Action for the provided Source and Destination DPIDs
1154         try {
1155             List<Action> actions = null;
1156             if (isVlan(elanInstance) || isFlat(elanInstance)) {
1157                 String interfaceName = getExternalElanInterface(elanInstance.getElanInstanceName(), srcDpId);
1158                 if (null == interfaceName) {
1159                     LOG.error("buildRemoteDmacFlowEntry: Could not find interfaceName for {} {}", srcDpId,
1160                             elanInstance);
1161                 }
1162                 actions = getEgressActionsForInterface(interfaceName, null);
1163             } else {
1164                 actions = getInternalTunnelItmEgressAction(srcDpId, destDpId, lportTag);
1165             }
1166             mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
1167         } catch (Exception e) {
1168             LOG.error("Could not get egress actions to add to flow for srcDpId=" + srcDpId + ", destDpId=" + destDpId
1169                     + ", lportTag=" + lportTag, e);
1170         }
1171
1172         Flow flow = MDSALUtil.buildFlowNew(NwConstants.ELAN_DMAC_TABLE,
1173                 getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, srcDpId, destDpId, macAddress, elanTag),
1174                 20, /* prio */
1175                 displayName, 0, /* idleTimeout */
1176                 0, /* hardTimeout */
1177                 ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(BigInteger.valueOf(elanTag)), mkMatches, mkInstructions);
1178
1179         return flow;
1180
1181     }
1182
1183     public void deleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, MacEntry macEntry,
1184             WriteTransaction deleteFlowGroupTx) {
1185         if (elanInfo == null || interfaceInfo == null) {
1186             return;
1187         }
1188         String macAddress = macEntry.getMacAddress().getValue();
1189         synchronized (macAddress) {
1190             LOG.debug("Acquired lock for mac : " + macAddress + ". Proceeding with remove operation.");
1191             deleteMacFlows(elanInfo, interfaceInfo, macAddress, /* alsoDeleteSMAC */ true, deleteFlowGroupTx);
1192         }
1193     }
1194
1195     public void deleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1196             boolean deleteSmac, WriteTransaction deleteFlowGroupTx) {
1197         String elanInstanceName = elanInfo.getElanInstanceName();
1198         List<DpnInterfaces> remoteFEs = getInvolvedDpnsInElan(elanInstanceName);
1199         BigInteger srcdpId = interfaceInfo.getDpId();
1200         boolean isFlowsRemovedInSrcDpn = false;
1201         for (DpnInterfaces dpnInterface : remoteFEs) {
1202             Long elanTag = elanInfo.getElanTag();
1203             BigInteger dstDpId = dpnInterface.getDpId();
1204             if (executeDeleteMacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, elanInstanceName, srcdpId,
1205                     elanTag, dstDpId, deleteFlowGroupTx)) {
1206                 isFlowsRemovedInSrcDpn = true;
1207             }
1208             executeEtreeDeleteMacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, elanInstanceName, srcdpId,
1209                     elanTag, dstDpId, deleteFlowGroupTx);
1210         }
1211         if (!isFlowsRemovedInSrcDpn) {
1212             deleteSmacAndDmacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, deleteFlowGroupTx);
1213         }
1214     }
1215
1216     private void executeEtreeDeleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1217             boolean deleteSmac, String elanInstanceName, BigInteger srcdpId, Long elanTag, BigInteger dstDpId,
1218             WriteTransaction deleteFlowGroupTx) {
1219         EtreeLeafTagName etreeLeafTag = getEtreeLeafTagByElanTag(elanTag);
1220         if (etreeLeafTag != null) {
1221             executeDeleteMacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, elanInstanceName, srcdpId,
1222                     etreeLeafTag.getEtreeLeafTag().getValue(), dstDpId, deleteFlowGroupTx);
1223         }
1224     }
1225
1226     private boolean executeDeleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1227             boolean deleteSmac, String elanInstanceName, BigInteger srcdpId, Long elanTag, BigInteger dstDpId,
1228             WriteTransaction deleteFlowGroupTx) {
1229         boolean isFlowsRemovedInSrcDpn = false;
1230         if (dstDpId.equals(srcdpId)) {
1231             isFlowsRemovedInSrcDpn = true;
1232             deleteSmacAndDmacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, deleteFlowGroupTx);
1233         } else if (isDpnPresent(dstDpId)) {
1234             mdsalManager
1235                     .removeFlowToTx(dstDpId,
1236                             MDSALUtil.buildFlow(NwConstants.ELAN_DMAC_TABLE, getKnownDynamicmacFlowRef(
1237                                     NwConstants.ELAN_DMAC_TABLE, dstDpId, srcdpId, macAddress, elanTag)),
1238                             deleteFlowGroupTx);
1239             if (LOG.isDebugEnabled()) {
1240                 LOG.debug("Dmac flow entry deleted for elan:{}, logical interface port:{} and mac address:{} on dpn:{}",
1241                         elanInstanceName, interfaceInfo.getPortName(), macAddress, dstDpId);
1242             }
1243         }
1244         return isFlowsRemovedInSrcDpn;
1245     }
1246
1247     private void deleteSmacAndDmacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1248             boolean deleteSmac, WriteTransaction deleteFlowGroupTx) {
1249         String elanInstanceName = elanInfo.getElanInstanceName();
1250         long ifTag = interfaceInfo.getInterfaceTag();
1251         BigInteger srcdpId = interfaceInfo.getDpId();
1252         Long elanTag = elanInfo.getElanTag();
1253         if (deleteSmac) {
1254             mdsalManager
1255                     .removeFlowToTx(srcdpId,
1256                             MDSALUtil.buildFlow(NwConstants.ELAN_SMAC_TABLE, getKnownDynamicmacFlowRef(
1257                                     NwConstants.ELAN_SMAC_TABLE, srcdpId, ifTag, macAddress, elanTag)),
1258                             deleteFlowGroupTx);
1259         }
1260         mdsalManager.removeFlowToTx(srcdpId,
1261                 MDSALUtil.buildFlow(NwConstants.ELAN_DMAC_TABLE,
1262                         getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, srcdpId, ifTag, macAddress, elanTag)),
1263                 deleteFlowGroupTx);
1264         if (LOG.isDebugEnabled()) {
1265             LOG.debug("All the required flows deleted for elan:{}, logical Interface port:{} and MAC address:{} "
1266                     + "on dpn:{}", elanInstanceName, interfaceInfo.getPortName(), macAddress, srcdpId);
1267         }
1268     }
1269
1270     /**
1271      * Updates the Elan information in the Operational DS. It also updates the
1272      * ElanInstance in the Config DS by setting the adquired elanTag.
1273      *
1274      * @param broker
1275      *            the broker
1276      * @param idManager
1277      *            the id manager
1278      * @param elanInstanceAdded
1279      *            the elan instance added
1280      * @param elanInterfaces
1281      *            the elan interfaces
1282      * @param tx
1283      *            transaction
1284      */
1285     public static void updateOperationalDataStore(DataBroker broker, IdManagerService idManager,
1286             ElanInstance elanInstanceAdded, List<String> elanInterfaces, WriteTransaction tx) {
1287         String elanInstanceName = elanInstanceAdded.getElanInstanceName();
1288         Long elanTag = elanInstanceAdded.getElanTag();
1289         if (elanTag == null || elanTag == 0L) {
1290             elanTag = retrieveNewElanTag(idManager, elanInstanceName);
1291         }
1292         Elan elanInfo = new ElanBuilder().setName(elanInstanceName).setElanInterfaces(elanInterfaces)
1293                 .setKey(new ElanKey(elanInstanceName)).build();
1294
1295         // Add the ElanState in the elan-state operational data-store
1296         tx.put(LogicalDatastoreType.OPERATIONAL, getElanInstanceOperationalDataPath(elanInstanceName),
1297                 elanInfo, true);
1298
1299         // Add the ElanMacTable in the elan-mac-table operational data-store
1300         MacTable elanMacTable = new MacTableBuilder().setKey(new MacTableKey(elanInstanceName)).build();
1301         tx.put(LogicalDatastoreType.OPERATIONAL, getElanMacTableOperationalDataPath(elanInstanceName),
1302                 elanMacTable, true);
1303
1304         ElanTagNameBuilder elanTagNameBuilder = new ElanTagNameBuilder().setElanTag(elanTag)
1305                 .setKey(new ElanTagNameKey(elanTag)).setName(elanInstanceName);
1306         long etreeLeafTag = -1;
1307         if (isEtreeInstance(elanInstanceAdded)) {
1308             etreeLeafTag = retrieveNewElanTag(idManager, elanInstanceName + ElanConstants.LEAVES_POSTFIX);
1309             EtreeLeafTagName etreeLeafTagName = new EtreeLeafTagNameBuilder()
1310                     .setEtreeLeafTag(new EtreeLeafTag(etreeLeafTag)).build();
1311             elanTagNameBuilder.addAugmentation(EtreeLeafTagName.class, etreeLeafTagName);
1312             addTheLeafTagAsElanTag(broker, elanInstanceName, etreeLeafTag, tx);
1313         }
1314         ElanTagName elanTagName = elanTagNameBuilder.build();
1315
1316         // Add the ElanTag to ElanName in the elan-tag-name Operational
1317         // data-store
1318         tx.put(LogicalDatastoreType.OPERATIONAL,
1319                 getElanInfoEntriesOperationalDataPath(elanTag), elanTagName);
1320
1321         // Updates the ElanInstance Config DS by setting the just acquired
1322         // elanTag
1323         ElanInstanceBuilder elanInstanceBuilder = new ElanInstanceBuilder().setElanInstanceName(elanInstanceName)
1324                 .setDescription(elanInstanceAdded.getDescription())
1325                 .setMacTimeout(elanInstanceAdded.getMacTimeout() == null ? ElanConstants.DEFAULT_MAC_TIME_OUT
1326                         : elanInstanceAdded.getMacTimeout())
1327                 .setKey(elanInstanceAdded.getKey()).setElanTag(elanTag);
1328         if (isEtreeInstance(elanInstanceAdded)) {
1329             EtreeInstance etreeInstance = new EtreeInstanceBuilder().setEtreeLeafTagVal(new EtreeLeafTag(etreeLeafTag))
1330                     .build();
1331             elanInstanceBuilder.addAugmentation(EtreeInstance.class, etreeInstance);
1332         }
1333         ElanInstance elanInstanceWithTag = elanInstanceBuilder.build();
1334         tx.merge(LogicalDatastoreType.CONFIGURATION, getElanInstanceConfigurationDataPath(elanInstanceName),
1335                 elanInstanceWithTag, true);
1336     }
1337
1338     private static void addTheLeafTagAsElanTag(DataBroker broker, String elanInstanceName, long etreeLeafTag,
1339             WriteTransaction tx) {
1340         ElanTagName etreeTagAsElanTag = new ElanTagNameBuilder().setElanTag(etreeLeafTag)
1341                 .setKey(new ElanTagNameKey(etreeLeafTag)).setName(elanInstanceName).build();
1342         tx.put(LogicalDatastoreType.OPERATIONAL,
1343                 getElanInfoEntriesOperationalDataPath(etreeLeafTag), etreeTagAsElanTag);
1344     }
1345
1346     private static boolean isEtreeInstance(ElanInstance elanInstanceAdded) {
1347         return elanInstanceAdded.getAugmentation(EtreeInstance.class) != null;
1348     }
1349
1350     public boolean isDpnPresent(BigInteger dpnId) {
1351         String dpn = String.format("%s:%s", "openflow", dpnId);
1352         NodeId nodeId = new NodeId(dpn);
1353
1354         InstanceIdentifier<Node> node = InstanceIdentifier.builder(Nodes.class).child(Node.class, new NodeKey(nodeId))
1355                 .build();
1356         Optional<Node> nodePresent = read(broker, LogicalDatastoreType.OPERATIONAL, node);
1357         return nodePresent.isPresent();
1358     }
1359
1360     public static ServicesInfo getServiceInfo(String elanInstanceName, long elanTag, String interfaceName) {
1361         int priority = ElanConstants.ELAN_SERVICE_PRIORITY;
1362         int instructionKey = 0;
1363         List<Instruction> instructions = new ArrayList<>();
1364         instructions.add(MDSALUtil.buildAndGetWriteMetadaInstruction(getElanMetadataLabel(elanTag),
1365                 MetaDataUtil.METADATA_MASK_SERVICE, ++instructionKey));
1366         instructions.add(MDSALUtil.buildAndGetGotoTableInstruction(NwConstants.ELAN_SMAC_TABLE, ++instructionKey));
1367
1368         short serviceIndex = ServiceIndex.getIndex(NwConstants.ELAN_SERVICE_NAME, NwConstants.ELAN_SERVICE_INDEX);
1369         ServicesInfo serviceInfo = InterfaceServiceUtil.buildServiceInfo(
1370                 String.format("%s.%s", elanInstanceName, interfaceName), serviceIndex, priority,
1371                 NwConstants.COOKIE_ELAN_INGRESS_TABLE, instructions);
1372         return serviceInfo;
1373     }
1374
1375     public static <T extends DataObject> void syncWrite(DataBroker broker, LogicalDatastoreType datastoreType,
1376             InstanceIdentifier<T> path, T data) {
1377         WriteTransaction tx = broker.newWriteOnlyTransaction();
1378         tx.put(datastoreType, path, data, true);
1379         CheckedFuture<Void, TransactionCommitFailedException> futures = tx.submit();
1380         try {
1381             futures.get();
1382         } catch (InterruptedException | ExecutionException e) {
1383             LOG.error("Error writing to datastore (path, data) : ({}, {})", path, data);
1384             throw new RuntimeException(e.getMessage());
1385         }
1386     }
1387
1388     public static BoundServices getBoundServices(String serviceName, short servicePriority, int flowPriority,
1389             BigInteger cookie, List<Instruction> instructions) {
1390         StypeOpenflowBuilder augBuilder = new StypeOpenflowBuilder().setFlowCookie(cookie).setFlowPriority(flowPriority)
1391                 .setInstruction(instructions);
1392         return new BoundServicesBuilder().setKey(new BoundServicesKey(servicePriority)).setServiceName(serviceName)
1393                 .setServicePriority(servicePriority).setServiceType(ServiceTypeFlowBased.class)
1394                 .addAugmentation(StypeOpenflow.class, augBuilder.build()).build();
1395     }
1396
1397     public static InstanceIdentifier<BoundServices> buildServiceId(String vpnInterfaceName, short serviceIndex) {
1398         return InstanceIdentifier.builder(ServiceBindings.class)
1399                 .child(ServicesInfo.class, new ServicesInfoKey(vpnInterfaceName, ServiceModeIngress.class))
1400                 .child(BoundServices.class, new BoundServicesKey(serviceIndex)).build();
1401     }
1402
1403     /**
1404      * Builds the list of actions to be taken when sending the packet over a
1405      * VxLan Tunnel Interface, such as setting the tunnel_id field, the vlanId
1406      * if proceeds and output the packet over the right port.
1407      *
1408      * @param tunnelIfaceName
1409      *            the tunnel iface name
1410      * @param tunnelKey
1411      *            the tunnel key
1412      * @return the list
1413      */
1414     public List<Action> buildTunnelItmEgressActions(String tunnelIfaceName, Long tunnelKey) {
1415         if (tunnelIfaceName != null && !tunnelIfaceName.isEmpty()) {
1416             return buildItmEgressActions(tunnelIfaceName, tunnelKey);
1417         }
1418
1419         return Collections.emptyList();
1420     }
1421
1422     /**
1423      * Builds the list of actions to be taken when sending the packet over
1424      * external port such as tunnel, physical port etc.
1425      *
1426      * @param interfaceName
1427      *            the interface name
1428      * @param tunnelKey
1429      *            can be VNI for VxLAN tunnel interfaces, Gre Key for GRE
1430      *            tunnels, etc.
1431      * @return the list
1432      */
1433     public List<Action> buildItmEgressActions(String interfaceName, Long tunnelKey) {
1434         List<Action> result = Collections.emptyList();
1435         GetEgressActionsForInterfaceInput getEgressActInput = new GetEgressActionsForInterfaceInputBuilder()
1436                 .setIntfName(interfaceName).setTunnelKey(tunnelKey).build();
1437
1438         Future<RpcResult<GetEgressActionsForInterfaceOutput>> egressActionsOutputFuture = interfaceManagerRpcService
1439                 .getEgressActionsForInterface(getEgressActInput);
1440         try {
1441             if (egressActionsOutputFuture.get().isSuccessful()) {
1442                 GetEgressActionsForInterfaceOutput egressActionsOutput = egressActionsOutputFuture.get().getResult();
1443                 result = egressActionsOutput.getAction();
1444             }
1445         } catch (InterruptedException | ExecutionException e) {
1446             LOG.error("Error in RPC call getEgressActionsForInterface {}", e);
1447         }
1448
1449         if (result == null || result.size() == 0) {
1450             LOG.warn("Could not build Egress actions for interface {} and tunnelId {}", interfaceName, tunnelKey);
1451         }
1452         return result;
1453     }
1454
1455     /**
1456      * Builds the list of actions to be taken when sending the packet over an
1457      * external VxLan tunnel interface, such as stamping the VNI on the VxLAN
1458      * header, setting the vlanId if it proceeds and output the packet over the
1459      * right port.
1460      *
1461      * @param srcDpnId
1462      *            Dpn where the tunnelInterface is located
1463      * @param torNode
1464      *            NodeId of the ExternalDevice where the packet must be sent to.
1465      * @param vni
1466      *            Vni to be stamped on the VxLAN Header.
1467      * @return the external itm egress action
1468      */
1469     public List<Action> getExternalTunnelItmEgressAction(BigInteger srcDpnId, NodeId torNode, long vni) {
1470         List<Action> result = Collections.emptyList();
1471
1472         GetExternalTunnelInterfaceNameInput input = new GetExternalTunnelInterfaceNameInputBuilder()
1473                 .setDestinationNode(torNode.getValue()).setSourceNode(srcDpnId.toString())
1474                 .setTunnelType(TunnelTypeVxlan.class).build();
1475         Future<RpcResult<GetExternalTunnelInterfaceNameOutput>> output = itmRpcService
1476                 .getExternalTunnelInterfaceName(input);
1477         try {
1478             if (output.get().isSuccessful()) {
1479                 GetExternalTunnelInterfaceNameOutput tunnelInterfaceNameOutput = output.get().getResult();
1480                 String tunnelIfaceName = tunnelInterfaceNameOutput.getInterfaceName();
1481                 if (LOG.isDebugEnabled()) {
1482                     LOG.debug("Received tunnelInterfaceName from getTunnelInterfaceName RPC {}", tunnelIfaceName);
1483                 }
1484
1485                 result = buildTunnelItmEgressActions(tunnelIfaceName, vni);
1486             }
1487
1488         } catch (InterruptedException | ExecutionException e) {
1489             LOG.error("Error in RPC call getTunnelInterfaceName {}", e);
1490         }
1491
1492         return result;
1493     }
1494
1495     /**
1496      * Builds the list of actions to be taken when sending the packet over an
1497      * internal VxLan tunnel interface, such as setting the serviceTag on the
1498      * VNI field of the VxLAN header, setting the vlanId if it proceeds and
1499      * output the packet over the right port.
1500      *
1501      * @param sourceDpnId
1502      *            Dpn where the tunnelInterface is located
1503      * @param destinationDpnId
1504      *            Dpn where the packet must be sent to. It is used here in order
1505      *            to select the right tunnel interface.
1506      * @param serviceTag
1507      *            serviceId to be sent on the VxLAN header.
1508      * @return the internal itm egress action
1509      */
1510     public List<Action> getInternalTunnelItmEgressAction(BigInteger sourceDpnId, BigInteger destinationDpnId,
1511             long serviceTag) {
1512         List<Action> result = Collections.emptyList();
1513
1514         LOG.debug("In getInternalItmEgressAction Action source {}, destination {}, elanTag {}", sourceDpnId,
1515                 destinationDpnId, serviceTag);
1516         Class<? extends TunnelTypeBase> tunType = TunnelTypeVxlan.class;
1517         GetTunnelInterfaceNameInput input = new GetTunnelInterfaceNameInputBuilder()
1518                 .setDestinationDpid(destinationDpnId).setSourceDpid(sourceDpnId).setTunnelType(tunType).build();
1519         Future<RpcResult<GetTunnelInterfaceNameOutput>> output = itmRpcService
1520                 .getTunnelInterfaceName(input);
1521         try {
1522             if (output.get().isSuccessful()) {
1523                 GetTunnelInterfaceNameOutput tunnelInterfaceNameOutput = output.get().getResult();
1524                 String tunnelIfaceName = tunnelInterfaceNameOutput.getInterfaceName();
1525                 LOG.debug("Received tunnelInterfaceName from getTunnelInterfaceName RPC {}", tunnelIfaceName);
1526
1527                 result = buildTunnelItmEgressActions(tunnelIfaceName, serviceTag);
1528             }
1529         } catch (InterruptedException | ExecutionException e) {
1530             LOG.error("Error in RPC call getTunnelInterfaceName {}", e);
1531         }
1532
1533         return result;
1534     }
1535
1536     /**
1537      * Build the list of actions to be taken when sending the packet to external
1538      * (physical) port.
1539      *
1540      * @param interfaceName
1541      *            Interface name
1542      * @return the external port itm egress actions
1543      */
1544     public List<Action> getExternalPortItmEgressAction(String interfaceName) {
1545         return buildItmEgressActions(interfaceName, null);
1546     }
1547
1548     public static List<MatchInfo> getTunnelMatchesForServiceId(int elanTag) {
1549         List<MatchInfo> mkMatches = new ArrayList<>();
1550         // Matching metadata
1551         mkMatches.add(new MatchInfo(MatchFieldType.tunnel_id, new BigInteger[] { BigInteger.valueOf(elanTag) }));
1552
1553         return mkMatches;
1554     }
1555
1556     public void removeTerminatingServiceAction(BigInteger destDpId, int serviceId) {
1557         RemoveTerminatingServiceActionsInput input = new RemoveTerminatingServiceActionsInputBuilder()
1558                 .setDpnId(destDpId).setServiceId(serviceId).build();
1559         Future<RpcResult<Void>> futureObject = itmRpcService
1560                 .removeTerminatingServiceActions(input);
1561         try {
1562             RpcResult<Void> result = futureObject.get();
1563             if (result.isSuccessful()) {
1564                 LOG.debug("Successfully completed removeTerminatingServiceActions");
1565             } else {
1566                 LOG.debug("Failure in removeTerminatingServiceAction RPC call");
1567             }
1568         } catch (InterruptedException | ExecutionException e) {
1569             LOG.error("Error in RPC call removeTerminatingServiceActions {}", e);
1570         }
1571     }
1572
1573     public void createTerminatingServiceActions(BigInteger destDpId, int serviceId, List<Action> actions) {
1574         List<Instruction> mkInstructions = new ArrayList<>();
1575         mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
1576         CreateTerminatingServiceActionsInput input = new CreateTerminatingServiceActionsInputBuilder()
1577                 .setDpnId(destDpId).setServiceId(serviceId).setInstruction(mkInstructions).build();
1578
1579         itmRpcService.createTerminatingServiceActions(input);
1580     }
1581
1582     public static TunnelList buildInternalTunnel(DataBroker broker) {
1583         InstanceIdentifier<TunnelList> tunnelListInstanceIdentifier = InstanceIdentifier.builder(TunnelList.class)
1584                 .build();
1585         Optional<TunnelList> tunnelList = MDSALUtil.read(broker, LogicalDatastoreType.CONFIGURATION,
1586                 tunnelListInstanceIdentifier);
1587         if (tunnelList.isPresent()) {
1588             return tunnelList.get();
1589         }
1590         return null;
1591     }
1592
1593     /**
1594      * Gets the external tunnel.
1595      *
1596      * @param sourceDevice
1597      *            the source device
1598      * @param destinationDevice
1599      *            the destination device
1600      * @param datastoreType
1601      *            the datastore type
1602      * @return the external tunnel
1603      */
1604     public ExternalTunnel getExternalTunnel(String sourceDevice, String destinationDevice,
1605             LogicalDatastoreType datastoreType) {
1606         ExternalTunnel externalTunnel = null;
1607         Class<? extends TunnelTypeBase> tunType = TunnelTypeVxlan.class;
1608         InstanceIdentifier<ExternalTunnel> iid = InstanceIdentifier.builder(ExternalTunnelList.class)
1609                 .child(ExternalTunnel.class, new ExternalTunnelKey(destinationDevice, sourceDevice, tunType)).build();
1610         Optional<ExternalTunnel> tunnelList = read(broker, datastoreType, iid);
1611         if (tunnelList.isPresent()) {
1612             externalTunnel = tunnelList.get();
1613         }
1614         return externalTunnel;
1615     }
1616
1617     /**
1618      * Gets the external tunnel.
1619      *
1620      * @param interfaceName
1621      *            the interface name
1622      * @param datastoreType
1623      *            the datastore type
1624      * @return the external tunnel
1625      */
1626     public ExternalTunnel getExternalTunnel(String interfaceName, LogicalDatastoreType datastoreType) {
1627         ExternalTunnel externalTunnel = null;
1628         List<ExternalTunnel> externalTunnels = getAllExternalTunnels(datastoreType);
1629         for (ExternalTunnel tunnel : externalTunnels) {
1630             if (StringUtils.equalsIgnoreCase(interfaceName, tunnel.getTunnelInterfaceName())) {
1631                 externalTunnel = tunnel;
1632                 break;
1633             }
1634         }
1635         return externalTunnel;
1636     }
1637
1638     /**
1639      * Gets the all external tunnels.
1640      *
1641      * @param datastoreType
1642      *            the data store type
1643      * @return the all external tunnels
1644      */
1645     public List<ExternalTunnel> getAllExternalTunnels(LogicalDatastoreType datastoreType) {
1646         List<ExternalTunnel> result = null;
1647         InstanceIdentifier<ExternalTunnelList> iid = InstanceIdentifier.builder(ExternalTunnelList.class).build();
1648         Optional<ExternalTunnelList> tunnelList = read(broker, datastoreType, iid);
1649         if (tunnelList.isPresent()) {
1650             result = tunnelList.get().getExternalTunnel();
1651         }
1652         if (result == null) {
1653             result = Collections.emptyList();
1654         }
1655         return result;
1656     }
1657
1658     /**
1659      * Installs a Flow in a DPN's DMAC table. The Flow is for a MAC that is
1660      * connected remotely in another CSS and accessible through an internal
1661      * tunnel. It also installs the flow for dropping the packet if it came over
1662      * an ITM tunnel (that is, if the Split-Horizon flag is set)
1663      *
1664      * @param localDpId
1665      *            Id of the DPN where the MAC Addr is accessible locally
1666      * @param remoteDpId
1667      *            Id of the DPN where the flow must be installed
1668      * @param lportTag
1669      *            lportTag of the interface where the mac is connected to.
1670      * @param elanTag
1671      *            Identifier of the ELAN
1672      * @param macAddress
1673      *            MAC to be installed in remoteDpId's DMAC table
1674      * @param displayName
1675      *            the display name
1676      * @throws ElanException in case of issues creating the flow objects
1677      */
1678     public void installDmacFlowsToInternalRemoteMac(BigInteger localDpId, BigInteger remoteDpId, long lportTag,
1679             long elanTag, String macAddress, String displayName) throws ElanException {
1680         Flow flow = buildDmacFlowForInternalRemoteMac(localDpId, remoteDpId, lportTag, elanTag, macAddress,
1681                 displayName);
1682         mdsalManager.installFlow(remoteDpId, flow);
1683     }
1684
1685     /**
1686      * Installs a Flow in the specified DPN's DMAC table. The flow is for a MAC
1687      * that is connected remotely in an External Device (TOR) and that is
1688      * accessible through an external tunnel. It also installs the flow for
1689      * dropping the packet if it came over an ITM tunnel (that is, if the
1690      * Split-Horizon flag is set)
1691      *
1692      * @param dpnId
1693      *            Id of the DPN where the flow must be installed
1694      * @param extDeviceNodeId
1695      *            the ext device node id
1696      * @param elanTag
1697      *            the elan tag
1698      * @param vni
1699      *            the vni
1700      * @param macAddress
1701      *            the mac address
1702      * @param displayName
1703      *            the display name
1704      * @param interfaceName
1705      *            the interface name
1706      *
1707      * @return the dmac flows
1708      * @throws ElanException in case of issues creating the flow objects
1709      */
1710     public List<ListenableFuture<Void>> installDmacFlowsToExternalRemoteMac(BigInteger dpnId,
1711             String extDeviceNodeId, Long elanTag, Long vni, String macAddress, String displayName,
1712             String interfaceName) throws ElanException {
1713         List<ListenableFuture<Void>> futures = new ArrayList<>();
1714         synchronized (macAddress) {
1715             Flow flow = buildDmacFlowForExternalRemoteMac(dpnId, extDeviceNodeId, elanTag, vni, macAddress,
1716                     displayName);
1717             futures.add(mdsalManager.installFlow(dpnId, flow));
1718
1719             Flow dropFlow = buildDmacFlowDropIfPacketComingFromTunnel(dpnId, extDeviceNodeId, elanTag, macAddress);
1720             futures.add(mdsalManager.installFlow(dpnId, dropFlow));
1721             installEtreeDmacFlowsToExternalRemoteMac(dpnId, extDeviceNodeId, elanTag, vni, macAddress, displayName,
1722                     interfaceName, futures);
1723         }
1724         return futures;
1725     }
1726
1727     private void installEtreeDmacFlowsToExternalRemoteMac(BigInteger dpnId, String extDeviceNodeId, Long elanTag,
1728             Long vni, String macAddress, String displayName, String interfaceName,
1729             List<ListenableFuture<Void>> futures) throws ElanException {
1730         EtreeLeafTagName etreeLeafTag = getEtreeLeafTagByElanTag(elanTag);
1731         if (etreeLeafTag != null) {
1732             buildEtreeDmacFlowDropIfPacketComingFromTunnel(dpnId, extDeviceNodeId, elanTag, macAddress, futures,
1733                     etreeLeafTag);
1734             buildEtreeDmacFlowForExternalRemoteMac(dpnId, extDeviceNodeId, vni, macAddress, displayName, interfaceName,
1735                     futures, etreeLeafTag);
1736         }
1737     }
1738
1739     private void buildEtreeDmacFlowForExternalRemoteMac(BigInteger dpnId, String extDeviceNodeId, Long vni,
1740             String macAddress, String displayName, String interfaceName, List<ListenableFuture<Void>> futures,
1741             EtreeLeafTagName etreeLeafTag) throws ElanException {
1742         boolean isRoot = false;
1743         if (interfaceName == null) {
1744             isRoot = true;
1745         } else {
1746             EtreeInterface etreeInterface = getEtreeInterfaceByElanInterfaceName(broker, interfaceName);
1747             if (etreeInterface != null) {
1748                 if (etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
1749                     isRoot = true;
1750                 }
1751             }
1752         }
1753         if (isRoot) {
1754             Flow flow = buildDmacFlowForExternalRemoteMac(dpnId, extDeviceNodeId,
1755                     etreeLeafTag.getEtreeLeafTag().getValue(), vni, macAddress, displayName);
1756             futures.add(mdsalManager.installFlow(dpnId, flow));
1757         }
1758     }
1759
1760     private void buildEtreeDmacFlowDropIfPacketComingFromTunnel(BigInteger dpnId, String extDeviceNodeId,
1761             Long elanTag, String macAddress, List<ListenableFuture<Void>> futures, EtreeLeafTagName etreeLeafTag) {
1762         if (etreeLeafTag != null) {
1763             Flow dropFlow = buildDmacFlowDropIfPacketComingFromTunnel(dpnId, extDeviceNodeId,
1764                     etreeLeafTag.getEtreeLeafTag().getValue(), macAddress);
1765             futures.add(mdsalManager.installFlow(dpnId, dropFlow));
1766         }
1767     }
1768
1769     public static List<MatchInfo> buildMatchesForElanTagShFlagAndDstMac(long elanTag, boolean shFlag, String macAddr) {
1770         List<MatchInfo> mkMatches = new ArrayList<>();
1771         mkMatches.add(new MatchInfo(MatchFieldType.metadata, new BigInteger[] {
1772                 getElanMetadataLabel(elanTag, shFlag), MetaDataUtil.METADATA_MASK_SERVICE_SH_FLAG }));
1773         mkMatches.add(new MatchInfo(MatchFieldType.eth_dst, new String[] { macAddr }));
1774
1775         return mkMatches;
1776     }
1777
1778     /**
1779      * Builds a Flow to be programmed in a DPN's DMAC table. This method must be
1780      * used when the MAC is located in an External Device (TOR). The flow
1781      * matches on the specified MAC and 1) sends the packet over the CSS-TOR
1782      * tunnel if SHFlag is not set, or 2) drops it if SHFlag is set (what means
1783      * the packet came from an external tunnel)
1784      *
1785      * @param dpId
1786      *            DPN whose DMAC table is going to be modified
1787      * @param extDeviceNodeId
1788      *            Hwvtep node where the mac is attached to
1789      * @param elanTag
1790      *            ElanId to which the MAC is being added to
1791      * @param vni
1792      *            the vni
1793      * @param dstMacAddress
1794      *            The mac address to be programmed
1795      * @param displayName
1796      *            the display name
1797      * @return the flow
1798      * @throws ElanException in case of issues creating the flow objects
1799      */
1800     @SuppressWarnings("checkstyle:IllegalCatch")
1801     public Flow buildDmacFlowForExternalRemoteMac(BigInteger dpId, String extDeviceNodeId, long elanTag,
1802             Long vni, String dstMacAddress, String displayName) throws ElanException {
1803         List<MatchInfo> mkMatches = buildMatchesForElanTagShFlagAndDstMac(elanTag, /* shFlag */ false, dstMacAddress);
1804         List<Instruction> mkInstructions = new ArrayList<>();
1805         try {
1806             List<Action> actions = getExternalTunnelItmEgressAction(dpId, new NodeId(extDeviceNodeId), vni);
1807             mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
1808         } catch (Exception e) {
1809             LOG.error("Could not get Egress Actions for DpId=" + dpId + ", externalNode=" + extDeviceNodeId, e);
1810         }
1811
1812         Flow flow = MDSALUtil.buildFlowNew(NwConstants.ELAN_DMAC_TABLE,
1813                 getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, extDeviceNodeId, dstMacAddress, elanTag,
1814                         false),
1815                 20, /* prio */
1816                 displayName, 0, /* idleTimeout */
1817                 0, /* hardTimeout */
1818                 ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(BigInteger.valueOf(elanTag)), mkMatches, mkInstructions);
1819
1820         return flow;
1821     }
1822
1823     /**
1824      * Builds the flow that drops the packet if it came through an external
1825      * tunnel, that is, if the Split-Horizon flag is set.
1826      *
1827      * @param dpnId
1828      *            DPN whose DMAC table is going to be modified
1829      * @param extDeviceNodeId
1830      *            Hwvtep node where the mac is attached to
1831      * @param elanTag
1832      *            ElanId to which the MAC is being added to
1833      * @param dstMacAddress
1834      *            The mac address to be programmed
1835      */
1836     private static Flow buildDmacFlowDropIfPacketComingFromTunnel(BigInteger dpnId, String extDeviceNodeId,
1837             Long elanTag, String dstMacAddress) {
1838         List<MatchInfo> mkMatches = buildMatchesForElanTagShFlagAndDstMac(elanTag, /* shFlag */ true, dstMacAddress);
1839         List<Instruction> mkInstructions = MDSALUtil.buildInstructionsDrop();
1840         String flowId = getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpnId, extDeviceNodeId, dstMacAddress,
1841                 elanTag, true);
1842         Flow flow = MDSALUtil.buildFlowNew(NwConstants.ELAN_DMAC_TABLE, flowId, 20, /* prio */
1843                 "Drop", 0, /* idleTimeout */
1844                 0, /* hardTimeout */
1845                 ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(BigInteger.valueOf(elanTag)), mkMatches, mkInstructions);
1846
1847         return flow;
1848     }
1849
1850     private static String getDmacDropFlowId(Long elanTag, String dstMacAddress) {
1851         return new StringBuilder(NwConstants.ELAN_DMAC_TABLE).append(elanTag).append(dstMacAddress).append("Drop")
1852                 .toString();
1853     }
1854
1855     /**
1856      * Builds a Flow to be programmed in a remote DPN's DMAC table. This method
1857      * must be used when the MAC is located in another CSS.
1858      *
1859      * <p>This flow consists in: Match: + elanTag in packet's metadata + packet
1860      * going to a MAC known to be located in another DPN Actions: +
1861      * set_tunnel_id(lportTag) + output on ITM internal tunnel interface with
1862      * the other DPN
1863      *
1864      * @param localDpId
1865      *            the local dp id
1866      * @param remoteDpId
1867      *            the remote dp id
1868      * @param lportTag
1869      *            the lport tag
1870      * @param elanTag
1871      *            the elan tag
1872      * @param macAddress
1873      *            the mac address
1874      * @param displayName
1875      *            the display name
1876      * @return the flow
1877      * @throws ElanException in case of issues creating the flow objects
1878      */
1879     @SuppressWarnings("checkstyle:IllegalCatch")
1880     public Flow buildDmacFlowForInternalRemoteMac(BigInteger localDpId, BigInteger remoteDpId, long lportTag,
1881             long elanTag, String macAddress, String displayName) throws ElanException {
1882         List<MatchInfo> mkMatches = buildMatchesForElanTagShFlagAndDstMac(elanTag, /* shFlag */ false, macAddress);
1883
1884         List<Instruction> mkInstructions = new ArrayList<>();
1885
1886         try {
1887             // List of Action for the provided Source and Destination DPIDs
1888             List<Action> actions = getInternalTunnelItmEgressAction(localDpId, remoteDpId, lportTag);
1889             mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
1890         } catch (Exception e) {
1891             LOG.error("Could not get Egress Actions for localDpId=" + localDpId + ", remoteDpId="
1892                     + remoteDpId + ", lportTag=" + lportTag, e);
1893         }
1894
1895         Flow flow = MDSALUtil.buildFlowNew(NwConstants.ELAN_DMAC_TABLE,
1896                 getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, localDpId, remoteDpId, macAddress, elanTag),
1897                 20, /* prio */
1898                 displayName, 0, /* idleTimeout */
1899                 0, /* hardTimeout */
1900                 ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(BigInteger.valueOf(elanTag)), mkMatches, mkInstructions);
1901
1902         return flow;
1903
1904     }
1905
1906     /**
1907      * Installs or removes flows in DMAC table for MACs that are/were located in
1908      * an external Elan Device.
1909      *
1910      * @param dpId
1911      *            Id of the DPN where the DMAC table is going to be modified
1912      * @param extNodeId
1913      *            Id of the External Device where the MAC is located
1914      * @param elanTag
1915      *            Id of the ELAN
1916      * @param vni
1917      *            VNI of the LogicalSwitch to which the MAC belongs to, and that
1918      *            is associated with the ELAN
1919      * @param macAddress
1920      *            the mac address
1921      * @param elanInstanceName
1922      *            the elan instance name
1923      * @param addOrRemove
1924      *            Indicates if flows must be installed or removed.
1925      * @param interfaceName
1926      *            the interface name
1927      * @throws ElanException in case of issues creating the flow objects
1928      * @see org.opendaylight.genius.mdsalutil.MDSALUtil.MdsalOp
1929      */
1930     public void setupDmacFlowsToExternalRemoteMac(BigInteger dpId, String extNodeId, Long elanTag, Long vni,
1931             String macAddress, String elanInstanceName, MdsalOp addOrRemove, String interfaceName)
1932             throws ElanException {
1933         if (addOrRemove == MdsalOp.CREATION_OP) {
1934             installDmacFlowsToExternalRemoteMac(dpId, extNodeId, elanTag, vni, macAddress, elanInstanceName,
1935                     interfaceName);
1936         } else if (addOrRemove == MdsalOp.REMOVAL_OP) {
1937             deleteDmacFlowsToExternalMac(elanTag, dpId, extNodeId, macAddress);
1938         }
1939     }
1940
1941     /**
1942      * Delete dmac flows to external mac.
1943      *
1944      * @param elanTag
1945      *            the elan tag
1946      * @param dpId
1947      *            the dp id
1948      * @param extDeviceNodeId
1949      *            the ext device node id
1950      * @param macToRemove
1951      *            the mac to remove
1952      * @return dmac flow
1953      */
1954     public List<ListenableFuture<Void>> deleteDmacFlowsToExternalMac(long elanTag, BigInteger dpId,
1955             String extDeviceNodeId, String macToRemove) {
1956         List<ListenableFuture<Void>> futures = new ArrayList<>();
1957         synchronized (macToRemove) {
1958             // Removing the flows that sends the packet on an external tunnel
1959             removeFlowThatSendsThePacketOnAnExternalTunnel(elanTag, dpId, extDeviceNodeId, macToRemove, futures);
1960
1961             // And now removing the drop flow
1962             removeTheDropFlow(elanTag, dpId, extDeviceNodeId, macToRemove, futures);
1963
1964             deleteEtreeDmacFlowsToExternalMac(elanTag, dpId, extDeviceNodeId, macToRemove, futures);
1965         }
1966         return futures;
1967     }
1968
1969     private void deleteEtreeDmacFlowsToExternalMac(long elanTag, BigInteger dpId, String extDeviceNodeId,
1970             String macToRemove, List<ListenableFuture<Void>> futures) {
1971         EtreeLeafTagName etreeLeafTag = getEtreeLeafTagByElanTag(elanTag);
1972         if (etreeLeafTag != null) {
1973             removeFlowThatSendsThePacketOnAnExternalTunnel(etreeLeafTag.getEtreeLeafTag().getValue(), dpId,
1974                     extDeviceNodeId, macToRemove, futures);
1975             removeTheDropFlow(etreeLeafTag.getEtreeLeafTag().getValue(), dpId, extDeviceNodeId, macToRemove, futures);
1976         }
1977     }
1978
1979     private void removeTheDropFlow(long elanTag, BigInteger dpId, String extDeviceNodeId, String macToRemove,
1980             List<ListenableFuture<Void>> futures) {
1981         String flowId = getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, extDeviceNodeId, macToRemove,
1982                 elanTag, true);
1983         Flow flowToRemove = new FlowBuilder().setId(new FlowId(flowId)).setTableId(NwConstants.ELAN_DMAC_TABLE).build();
1984         futures.add(mdsalManager.removeFlow(dpId, flowToRemove));
1985     }
1986
1987     private void removeFlowThatSendsThePacketOnAnExternalTunnel(long elanTag, BigInteger dpId,
1988             String extDeviceNodeId, String macToRemove, List<ListenableFuture<Void>> futures) {
1989         String flowId = getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, extDeviceNodeId, macToRemove,
1990                 elanTag, false);
1991         Flow flowToRemove = new FlowBuilder().setId(new FlowId(flowId)).setTableId(NwConstants.ELAN_DMAC_TABLE).build();
1992         futures.add(mdsalManager.removeFlow(dpId, flowToRemove));
1993     }
1994
1995     /**
1996      * Gets the dpid from interface.
1997      *
1998      * @param interfaceName
1999      *            the interface name
2000      * @return the dpid from interface
2001      */
2002     public BigInteger getDpidFromInterface(String interfaceName) {
2003         BigInteger dpId = null;
2004         Future<RpcResult<GetDpidFromInterfaceOutput>> output = interfaceManagerRpcService
2005                 .getDpidFromInterface(new GetDpidFromInterfaceInputBuilder().setIntfName(interfaceName).build());
2006         try {
2007             RpcResult<GetDpidFromInterfaceOutput> rpcResult = output.get();
2008             if (rpcResult.isSuccessful()) {
2009                 dpId = rpcResult.getResult().getDpid();
2010             }
2011         } catch (NullPointerException | InterruptedException | ExecutionException e) {
2012             LOG.error("Failed to get the DPN ID: {} for interface {}: {} ", dpId, interfaceName, e);
2013         }
2014         return dpId;
2015     }
2016
2017     /**
2018      * Checks if is interface operational.
2019      *
2020      * @param interfaceName
2021      *            the interface name
2022      * @param dataBroker
2023      *            the data broker
2024      * @return true, if is interface operational
2025      */
2026     public static boolean isInterfaceOperational(String interfaceName, DataBroker dataBroker) {
2027         if (StringUtils.isBlank(interfaceName)) {
2028             return false;
2029         }
2030         Interface ifState = getInterfaceStateFromOperDS(interfaceName, dataBroker);
2031         if (ifState == null) {
2032             return false;
2033         }
2034         return ifState.getOperStatus() == OperStatus.Up && ifState.getAdminStatus() == AdminStatus.Up;
2035     }
2036
2037     /**
2038      * Gets the interface state from operational ds.
2039      *
2040      * @param interfaceName
2041      *            the interface name
2042      * @param dataBroker
2043      *            the data broker
2044      * @return the interface state from oper ds
2045      */
2046     public static org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
2047         .ietf.interfaces.rev140508.interfaces.state.Interface getInterfaceStateFromOperDS(
2048             String interfaceName, DataBroker dataBroker) {
2049         InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
2050             .ietf.interfaces.rev140508.interfaces.state.Interface> ifStateId = createInterfaceStateInstanceIdentifier(
2051                 interfaceName);
2052         Optional<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
2053             .ietf.interfaces.rev140508.interfaces.state.Interface> ifStateOptional = MDSALUtil
2054                 .read(dataBroker, LogicalDatastoreType.OPERATIONAL, ifStateId);
2055         if (ifStateOptional.isPresent()) {
2056             return ifStateOptional.get();
2057         }
2058         return null;
2059     }
2060
2061     /**
2062      * Gets the interface from config ds.
2063      *
2064      * @param interfaceName
2065      *            the interface name
2066      * @param dataBroker
2067      *            the data broker
2068      * @return the interface from config ds
2069      */
2070     public static org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
2071         .ietf.interfaces.rev140508.interfaces.Interface getInterfaceFromConfigDS(
2072             String interfaceName, DataBroker dataBroker) {
2073         InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
2074             .ietf.interfaces.rev140508.interfaces.Interface> ifaceId = createInterfaceInstanceIdentifier(interfaceName);
2075         Optional<org.opendaylight.yang.gen.v1.urn
2076             .ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.Interface> iface = MDSALUtil
2077                 .read(dataBroker, LogicalDatastoreType.CONFIGURATION, ifaceId);
2078         if (iface.isPresent()) {
2079             return iface.get();
2080         }
2081         return null;
2082     }
2083
2084     /**
2085      * Creates the interface state instance identifier.
2086      *
2087      * @param interfaceName
2088      *            the interface name
2089      * @return the instance identifier
2090      */
2091     public static InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
2092         .ietf.interfaces.rev140508.interfaces.state.Interface> createInterfaceStateInstanceIdentifier(
2093             String interfaceName) {
2094         InstanceIdentifierBuilder<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
2095             .ietf.interfaces.rev140508.interfaces.state.Interface> idBuilder = InstanceIdentifier
2096                 .builder(InterfacesState.class)
2097                 .child(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
2098                         .ietf.interfaces.rev140508.interfaces.state.Interface.class,
2099                         new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
2100                             .ietf.interfaces.rev140508.interfaces.state.InterfaceKey(
2101                                 interfaceName));
2102         return idBuilder.build();
2103     }
2104
2105     /**
2106      * Creates the interface instance identifier.
2107      *
2108      * @param interfaceName
2109      *            the interface name
2110      * @return the instance identifier
2111      */
2112     public static InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
2113         .ietf.interfaces.rev140508.interfaces.Interface> createInterfaceInstanceIdentifier(
2114             String interfaceName) {
2115         InstanceIdentifierBuilder<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
2116             .ietf.interfaces.rev140508.interfaces.Interface> idBuilder = InstanceIdentifier
2117                 .builder(Interfaces.class)
2118                 .child(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
2119                         .ietf.interfaces.rev140508.interfaces.Interface.class,
2120                         new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
2121                             .ietf.interfaces.rev140508.interfaces.InterfaceKey(
2122                                 interfaceName));
2123         return idBuilder.build();
2124     }
2125
2126     public static CheckedFuture<Void, TransactionCommitFailedException> waitForTransactionToComplete(
2127             WriteTransaction tx) {
2128         CheckedFuture<Void, TransactionCommitFailedException> futures = tx.submit();
2129         try {
2130             futures.get();
2131         } catch (InterruptedException | ExecutionException e) {
2132             LOG.error("Error writing to datastore {}", e);
2133         }
2134         return futures;
2135     }
2136
2137     public static boolean isVxlan(ElanInstance elanInstance) {
2138         return elanInstance != null && elanInstance.getSegmentType() != null
2139                 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
2140                 && elanInstance.getSegmentationId() != null && elanInstance.getSegmentationId().longValue() != 0;
2141     }
2142
2143     public static boolean isVlan(ElanInstance elanInstance) {
2144         return elanInstance != null && elanInstance.getSegmentType() != null
2145                 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeVlan.class)
2146                 && elanInstance.getSegmentationId() != null && elanInstance.getSegmentationId().longValue() != 0;
2147     }
2148
2149     public static boolean isFlat(ElanInstance elanInstance) {
2150         return elanInstance != null && elanInstance.getSegmentType() != null
2151                 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeFlat.class);
2152     }
2153
2154     public boolean isExternal(String interfaceName) {
2155         return isExternal(getInterfaceFromConfigDS(interfaceName, broker));
2156     }
2157
2158     public static boolean isExternal(
2159             org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
2160             .ietf.interfaces.rev140508.interfaces.Interface iface) {
2161         if (iface == null) {
2162             return false;
2163         }
2164
2165         IfExternal ifExternal = iface.getAugmentation(IfExternal.class);
2166         return ifExternal != null && Boolean.TRUE.equals(ifExternal.isExternal());
2167     }
2168
2169     public static boolean isEtreeRootInterfaceByInterfaceName(DataBroker broker, String interfaceName) {
2170         EtreeInterface etreeInterface = getEtreeInterfaceByElanInterfaceName(broker, interfaceName);
2171         if (etreeInterface != null && etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
2172             return true;
2173         }
2174         return false;
2175     }
2176
2177     /**
2178      * Add Mac Address to ElanInterfaceForwardingEntries and ElanForwardingTables
2179      * Install SMAC and DMAC flows.
2180      */
2181     public void addMacEntryToDsAndSetupFlows(IInterfaceManager interfaceManager, String interfaceName,
2182             String macAddress, String elanName, WriteTransaction tx, WriteTransaction flowWritetx, int macTimeOut)
2183             throws ElanException {
2184         LOG.trace("Adding mac address {} and interface name {} to ElanInterfaceForwardingEntries and "
2185             + "ElanForwardingTables DS", macAddress, interfaceName);
2186         BigInteger timeStamp = new BigInteger(String.valueOf(System.currentTimeMillis()));
2187         PhysAddress physAddress = new PhysAddress(macAddress);
2188         MacEntry macEntry = new MacEntryBuilder().setInterface(interfaceName).setMacAddress(physAddress)
2189                 .setKey(new MacEntryKey(physAddress)).setControllerLearnedForwardingEntryTimestamp(timeStamp)
2190                 .setIsStaticAddress(false).build();
2191         InstanceIdentifier<MacEntry> macEntryId = ElanUtils
2192                 .getInterfaceMacEntriesIdentifierOperationalDataPath(interfaceName, physAddress);
2193         tx.put(LogicalDatastoreType.OPERATIONAL, macEntryId, macEntry);
2194         InstanceIdentifier<MacEntry> elanMacEntryId = ElanUtils.getMacEntryOperationalDataPath(elanName, physAddress);
2195         tx.put(LogicalDatastoreType.OPERATIONAL, elanMacEntryId, macEntry);
2196         ElanInstance elanInstance = ElanUtils.getElanInstanceByName(broker, elanName);
2197         setupMacFlows(elanInstance, interfaceManager.getInterfaceInfo(interfaceName), macTimeOut, macAddress,
2198                 flowWritetx);
2199     }
2200
2201     /**
2202      * Remove Mac Address from ElanInterfaceForwardingEntries and ElanForwardingTables
2203      * Remove SMAC and DMAC flows.
2204      */
2205     public void deleteMacEntryFromDsAndRemoveFlows(IInterfaceManager interfaceManager, String interfaceName,
2206             String macAddress, String elanName, WriteTransaction tx, WriteTransaction deleteFlowTx) {
2207         LOG.trace("Deleting mac address {} and interface name {} from ElanInterfaceForwardingEntries "
2208                 + "and ElanForwardingTables DS", macAddress, interfaceName);
2209         PhysAddress physAddress = new PhysAddress(macAddress);
2210         MacEntry macEntry = getInterfaceMacEntriesOperationalDataPath(interfaceName, physAddress);
2211         InterfaceInfo interfaceInfo = interfaceManager.getInterfaceInfo(interfaceName);
2212         if (macEntry != null && interfaceInfo != null) {
2213             deleteMacFlows(ElanUtils.getElanInstanceByName(broker, elanName), interfaceInfo, macEntry, deleteFlowTx);
2214         }
2215         tx.delete(LogicalDatastoreType.OPERATIONAL,
2216                 ElanUtils.getInterfaceMacEntriesIdentifierOperationalDataPath(interfaceName, physAddress));
2217         tx.delete(LogicalDatastoreType.OPERATIONAL,
2218                 ElanUtils.getMacEntryOperationalDataPath(elanName, physAddress));
2219     }
2220
2221     public String getExternalElanInterface(String elanInstanceName, BigInteger dpnId) {
2222         DpnInterfaces dpnInterfaces = getElanInterfaceInfoByElanDpn(elanInstanceName, dpnId);
2223         if (dpnInterfaces == null || dpnInterfaces.getInterfaces() == null) {
2224             LOG.trace("Elan {} does not have interfaces in DPN {}", elanInstanceName, dpnId);
2225             return null;
2226         }
2227
2228         for (String dpnInterface : dpnInterfaces.getInterfaces()) {
2229             if (isExternal(dpnInterface)) {
2230                 return dpnInterface;
2231             }
2232         }
2233
2234         LOG.trace("Elan {} does not have any external interace attached to DPN {}", elanInstanceName, dpnId);
2235         return null;
2236     }
2237 }