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