Remove redundant names in paths
[netvirt.git] / elanmanager / impl / src / main / java / org / opendaylight / netvirt / elan / utils / ElanUtils.java
1 /*
2  * Copyright © 2016, 2017 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.base.Preconditions;
12 import com.google.common.base.Strings;
13 import com.google.common.collect.Lists;
14 import com.google.common.primitives.Ints;
15 import com.google.common.util.concurrent.CheckedFuture;
16 import com.google.common.util.concurrent.FutureCallback;
17 import com.google.common.util.concurrent.Futures;
18 import com.google.common.util.concurrent.ListenableFuture;
19 import com.google.common.util.concurrent.MoreExecutors;
20 import java.math.BigInteger;
21 import java.util.ArrayList;
22 import java.util.Collection;
23 import java.util.Collections;
24 import java.util.HashSet;
25 import java.util.List;
26 import java.util.Map;
27 import java.util.Set;
28 import java.util.concurrent.ConcurrentHashMap;
29 import java.util.concurrent.ExecutionException;
30 import java.util.concurrent.Future;
31 import javax.annotation.Nonnull;
32 import javax.annotation.Nullable;
33 import javax.inject.Inject;
34 import javax.inject.Singleton;
35 import org.apache.commons.lang3.StringUtils;
36 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
37 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
38 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
39 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
40 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
41 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
42 import org.opendaylight.genius.interfacemanager.globals.InterfaceInfo;
43 import org.opendaylight.genius.interfacemanager.globals.InterfaceServiceUtil;
44 import org.opendaylight.genius.interfacemanager.interfaces.IInterfaceManager;
45 import org.opendaylight.genius.itm.globals.ITMConstants;
46 import org.opendaylight.genius.mdsalutil.ActionInfo;
47 import org.opendaylight.genius.mdsalutil.FlowEntity;
48 import org.opendaylight.genius.mdsalutil.FlowEntityBuilder;
49 import org.opendaylight.genius.mdsalutil.InstructionInfo;
50 import org.opendaylight.genius.mdsalutil.MDSALUtil;
51 import org.opendaylight.genius.mdsalutil.MatchInfo;
52 import org.opendaylight.genius.mdsalutil.MetaDataUtil;
53 import org.opendaylight.genius.mdsalutil.NWUtil;
54 import org.opendaylight.genius.mdsalutil.NwConstants;
55 import org.opendaylight.genius.mdsalutil.actions.ActionNxResubmit;
56 import org.opendaylight.genius.mdsalutil.instructions.InstructionApplyActions;
57 import org.opendaylight.genius.mdsalutil.instructions.InstructionGotoTable;
58 import org.opendaylight.genius.mdsalutil.interfaces.IMdsalApiManager;
59 import org.opendaylight.genius.mdsalutil.matches.MatchEthernetDestination;
60 import org.opendaylight.genius.mdsalutil.matches.MatchEthernetSource;
61 import org.opendaylight.genius.mdsalutil.matches.MatchMetadata;
62 import org.opendaylight.genius.mdsalutil.matches.MatchTunnelId;
63 import org.opendaylight.genius.mdsalutil.packet.ARP;
64 import org.opendaylight.genius.mdsalutil.packet.Ethernet;
65 import org.opendaylight.genius.mdsalutil.packet.IPv4;
66 import org.opendaylight.infrautils.utils.concurrent.JdkFutures;
67 import org.opendaylight.netvirt.elan.ElanException;
68 import org.opendaylight.netvirt.elan.arp.responder.ArpResponderUtil;
69 import org.opendaylight.netvirt.elanmanager.api.ElanHelper;
70 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
71 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddressBuilder;
72 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.InterfacesState;
73 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface;
74 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface.AdminStatus;
75 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface.OperStatus;
76 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress;
77 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.PhysAddress;
78 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action;
79 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
80 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId;
81 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
82 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableKey;
83 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
84 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowKey;
85 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.Instruction;
86 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdInput;
87 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdInputBuilder;
88 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdOutput;
89 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.IdManagerService;
90 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.ReleaseIdInput;
91 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.ReleaseIdInputBuilder;
92 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406.IfIndexesInterfaceMap;
93 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406._if.indexes._interface.map.IfIndexInterface;
94 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406._if.indexes._interface.map.IfIndexInterfaceKey;
95 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.IfTunnel;
96 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.ParentRefs;
97 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelTypeBase;
98 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelTypeVxlan;
99 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetEgressActionsForInterfaceInput;
100 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetEgressActionsForInterfaceInputBuilder;
101 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetEgressActionsForInterfaceOutput;
102 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.OdlInterfaceRpcService;
103 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceBindings;
104 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceModeIngress;
105 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceTypeFlowBased;
106 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.StypeOpenflow;
107 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.StypeOpenflowBuilder;
108 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.ServicesInfo;
109 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.ServicesInfoKey;
110 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.services.info.BoundServices;
111 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.services.info.BoundServicesBuilder;
112 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.services.info.BoundServicesKey;
113 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.ExternalTunnelList;
114 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.external.tunnel.list.ExternalTunnel;
115 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.external.tunnel.list.ExternalTunnelKey;
116 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.ItmRpcService;
117 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.RemoveTerminatingServiceActionsInput;
118 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.RemoveTerminatingServiceActionsInputBuilder;
119 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
120 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
121 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
122 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeBuilder;
123 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
124 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.config.rev150710.ElanConfig;
125 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInstance;
126 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInstanceBuilder;
127 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInterface;
128 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInterface.EtreeInterfaceType;
129 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeLeafTag;
130 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeLeafTagName;
131 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeLeafTagNameBuilder;
132 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanDpnInterfaces;
133 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanForwardingTables;
134 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInstances;
135 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInterfaceForwardingEntries;
136 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInterfaces;
137 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanState;
138 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanTagNameMap;
139 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.SegmentTypeFlat;
140 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.SegmentTypeVlan;
141 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.SegmentTypeVxlan;
142 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan._interface.forwarding.entries.ElanInterfaceMac;
143 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan._interface.forwarding.entries.ElanInterfaceMacKey;
144 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.ElanDpnInterfacesList;
145 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.ElanDpnInterfacesListKey;
146 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.elan.dpn.interfaces.list.DpnInterfaces;
147 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.elan.dpn.interfaces.list.DpnInterfacesKey;
148 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.forwarding.tables.MacTable;
149 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.forwarding.tables.MacTableBuilder;
150 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.forwarding.tables.MacTableKey;
151 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.ElanInstance;
152 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.ElanInstanceBuilder;
153 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.elan.instance.ElanSegments;
154 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.ElanInterface;
155 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.ElanInterfaceKey;
156 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.elan._interface.StaticMacEntries;
157 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.elan._interface.StaticMacEntriesBuilder;
158 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.elan._interface.StaticMacEntriesKey;
159 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.state.Elan;
160 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.state.ElanBuilder;
161 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.state.ElanKey;
162 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.tag.name.map.ElanTagName;
163 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.tag.name.map.ElanTagNameBuilder;
164 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.tag.name.map.ElanTagNameKey;
165 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.forwarding.entries.MacEntry;
166 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.forwarding.entries.MacEntryBuilder;
167 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.forwarding.entries.MacEntryKey;
168 import org.opendaylight.yangtools.yang.binding.DataObject;
169 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
170 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.InstanceIdentifierBuilder;
171 import org.opendaylight.yangtools.yang.common.RpcResult;
172 import org.slf4j.Logger;
173 import org.slf4j.LoggerFactory;
174
175 @Singleton
176 public class ElanUtils {
177
178     private static final Logger LOG = LoggerFactory.getLogger(ElanUtils.class);
179
180     private static Map<String, ElanInstance> elanInstanceLocalCache = new ConcurrentHashMap<>();
181     private static Map<String, ElanInterface> elanInterfaceLocalCache = new ConcurrentHashMap<>();
182     private static Map<String, Set<DpnInterfaces>> elanInstancToDpnsCache = new ConcurrentHashMap<>();
183     private static Map<String, Set<String>> elanInstanceToInterfacesCache = new ConcurrentHashMap<>();
184
185     private final DataBroker broker;
186     private final IMdsalApiManager mdsalManager;
187     private final OdlInterfaceRpcService interfaceManagerRpcService;
188     private final ItmRpcService itmRpcService;
189     private final IInterfaceManager interfaceManager;
190     private final ElanConfig elanConfig;
191     private final ElanItmUtils elanItmUtils;
192     private final ElanEtreeUtils elanEtreeUtils;
193
194     public static final FutureCallback<Void> DEFAULT_CALLBACK = new FutureCallback<Void>() {
195         @Override
196         public void onSuccess(Void result) {
197             LOG.debug("Success in Datastore operation");
198         }
199
200         @Override
201         public void onFailure(Throwable error) {
202             LOG.error("Error in Datastore operation", error);
203         }
204     };
205
206     @Inject
207     public ElanUtils(DataBroker dataBroker, IMdsalApiManager mdsalManager,
208             OdlInterfaceRpcService interfaceManagerRpcService, ItmRpcService itmRpcService, ElanConfig elanConfig,
209             IInterfaceManager interfaceManager, ElanEtreeUtils elanEtreeUtils, ElanItmUtils elanItmUtils) {
210         this.broker = dataBroker;
211         this.mdsalManager = mdsalManager;
212         this.interfaceManagerRpcService = interfaceManagerRpcService;
213         this.itmRpcService = itmRpcService;
214         this.interfaceManager = interfaceManager;
215         this.elanConfig = elanConfig;
216         this.elanEtreeUtils = elanEtreeUtils;
217         this.elanItmUtils = elanItmUtils;
218     }
219
220     public final Boolean isOpenstackVniSemanticsEnforced() {
221         return elanConfig.isOpenstackVniSemanticsEnforced() != null
222                 ? elanConfig.isOpenstackVniSemanticsEnforced() : false;
223     }
224
225     public static void addElanInstanceIntoCache(String elanInstanceName, ElanInstance elanInstance) {
226         elanInstanceLocalCache.put(elanInstanceName, elanInstance);
227     }
228
229     public static void removeElanInstanceFromCache(String elanInstanceName) {
230         elanInstanceLocalCache.remove(elanInstanceName);
231     }
232
233     public static ElanInstance getElanInstanceFromCache(String elanInstanceName) {
234         return elanInstanceLocalCache.get(elanInstanceName);
235     }
236
237     public static Set<String> getAllElanNames() {
238         return elanInstanceLocalCache.keySet();
239     }
240
241     public static void addElanInterfaceIntoCache(String interfaceName, ElanInterface elanInterface) {
242         elanInterfaceLocalCache.put(interfaceName, elanInterface);
243     }
244
245     public static void removeElanInterfaceFromCache(String interfaceName) {
246         elanInterfaceLocalCache.remove(interfaceName);
247     }
248
249     public static ElanInterface getElanInterfaceFromCache(String interfaceName) {
250         return elanInterfaceLocalCache.get(interfaceName);
251     }
252
253     /**
254      * Uses the IdManager to retrieve a brand new ElanTag.
255      *
256      * @param idManager
257      *            the id manager
258      * @param idKey
259      *            the id key
260      * @return the integer
261      */
262     public static Long retrieveNewElanTag(IdManagerService idManager, String idKey) {
263
264         AllocateIdInput getIdInput = new AllocateIdInputBuilder().setPoolName(ElanConstants.ELAN_ID_POOL_NAME)
265                 .setIdKey(idKey).build();
266
267         try {
268             Future<RpcResult<AllocateIdOutput>> result = idManager.allocateId(getIdInput);
269             RpcResult<AllocateIdOutput> rpcResult = result.get();
270             if (rpcResult.isSuccessful()) {
271                 return rpcResult.getResult().getIdValue();
272             } else {
273                 LOG.warn("RPC Call to Allocate Id returned with Errors {}", rpcResult.getErrors());
274             }
275         } catch (InterruptedException | ExecutionException e) {
276             LOG.warn("Exception when Allocating Id", e);
277         }
278         return 0L;
279     }
280
281     public static void releaseId(IdManagerService idManager, String poolName, String idKey) {
282         ReleaseIdInput releaseIdInput = new ReleaseIdInputBuilder().setPoolName(poolName).setIdKey(idKey).build();
283         JdkFutures.addErrorLogging(idManager.releaseId(releaseIdInput), LOG, "Release Id");
284     }
285
286     /**
287      * Read utility.
288      *
289      * @deprecated Consider using {@link #read2(LogicalDatastoreType, InstanceIdentifier)} with proper exception
290      *             handling instead
291      */
292     @Deprecated
293     @SuppressWarnings("checkstyle:IllegalCatch")
294     public static <T extends DataObject> Optional<T> read(@Nonnull DataBroker broker,
295             LogicalDatastoreType datastoreType, InstanceIdentifier<T> path) {
296         try (ReadOnlyTransaction tx = broker.newReadOnlyTransaction()) {
297             return tx.read(datastoreType, path).get();
298         } catch (Exception e) {
299             throw new RuntimeException(e);
300         }
301     }
302
303     public <T extends DataObject> Optional<T> read2(LogicalDatastoreType datastoreType, InstanceIdentifier<T> path)
304             throws ReadFailedException {
305         try (ReadOnlyTransaction tx = broker.newReadOnlyTransaction()) {
306             CheckedFuture<Optional<T>, ReadFailedException> checkedFuture = tx.read(datastoreType, path);
307             return checkedFuture.checkedGet();
308         }
309     }
310
311     public static <T extends DataObject> void delete(DataBroker broker, LogicalDatastoreType datastoreType,
312             InstanceIdentifier<T> path) {
313         WriteTransaction tx = broker.newWriteOnlyTransaction();
314         tx.delete(datastoreType, path);
315         Futures.addCallback(tx.submit(), DEFAULT_CALLBACK, MoreExecutors.directExecutor());
316     }
317
318     public static <T extends DataObject> void delete(DataBroker broker, LogicalDatastoreType datastoreType,
319             InstanceIdentifier<T> path, FutureCallback<Void> callback) {
320         WriteTransaction tx = broker.newWriteOnlyTransaction();
321         tx.delete(datastoreType, path);
322         Futures.addCallback(tx.submit(), callback, MoreExecutors.directExecutor());
323     }
324
325     public static InstanceIdentifier<ElanInstance> getElanInstanceIdentifier() {
326         return InstanceIdentifier.builder(ElanInstances.class).child(ElanInstance.class).build();
327     }
328
329     // elan-instances config container
330     @Nullable
331     public static ElanInstance getElanInstanceByName(DataBroker broker, String elanInstanceName) {
332         ElanInstance elanObj = getElanInstanceFromCache(elanInstanceName);
333         if (elanObj != null) {
334             return elanObj;
335         }
336         InstanceIdentifier<ElanInstance> elanIdentifierId =
337                 ElanHelper.getElanInstanceConfigurationDataPath(elanInstanceName);
338         return MDSALUtil.read(broker, LogicalDatastoreType.CONFIGURATION, elanIdentifierId).orNull();
339     }
340
341     // elan-interfaces Config Container
342     public static ElanInterface getElanInterfaceByElanInterfaceName(DataBroker broker, String elanInterfaceName) {
343         ElanInterface elanInterfaceObj = getElanInterfaceFromCache(elanInterfaceName);
344         if (elanInterfaceObj != null) {
345             return elanInterfaceObj;
346         }
347         InstanceIdentifier<ElanInterface> elanInterfaceId = getElanInterfaceConfigurationDataPathId(elanInterfaceName);
348         return MDSALUtil.read(broker, LogicalDatastoreType.CONFIGURATION, elanInterfaceId).orNull();
349     }
350
351     public static EtreeInterface getEtreeInterfaceByElanInterfaceName(DataBroker broker, String elanInterfaceName) {
352         ElanInterface elanInterface = getElanInterfaceByElanInterfaceName(broker, elanInterfaceName);
353         if (elanInterface == null) {
354             return null;
355         } else {
356             return elanInterface.getAugmentation(EtreeInterface.class);
357         }
358     }
359
360     public static InstanceIdentifier<ElanInterface> getElanInterfaceConfigurationDataPathId(String interfaceName) {
361         return InstanceIdentifier.builder(ElanInterfaces.class)
362                 .child(ElanInterface.class, new ElanInterfaceKey(interfaceName)).build();
363     }
364
365     // elan-state Operational container
366     public static Elan getElanByName(DataBroker broker, String elanInstanceName) {
367         InstanceIdentifier<Elan> elanIdentifier = getElanInstanceOperationalDataPath(elanInstanceName);
368         return MDSALUtil.read(broker, LogicalDatastoreType.OPERATIONAL, elanIdentifier).orNull();
369     }
370
371     public static InstanceIdentifier<Elan> getElanInstanceOperationalDataPath(String elanInstanceName) {
372         return InstanceIdentifier.builder(ElanState.class).child(Elan.class, new ElanKey(elanInstanceName)).build();
373     }
374
375     // grouping of forwarding-entries
376     public MacEntry getInterfaceMacEntriesOperationalDataPath(String interfaceName, PhysAddress physAddress) {
377         InstanceIdentifier<MacEntry> existingMacEntryId = getInterfaceMacEntriesIdentifierOperationalDataPath(
378                 interfaceName, physAddress);
379         return read(broker, LogicalDatastoreType.OPERATIONAL, existingMacEntryId).orNull();
380     }
381
382     public MacEntry getInterfaceMacEntriesOperationalDataPathFromId(InstanceIdentifier identifier) {
383         Optional<MacEntry> existingInterfaceMacEntry = read(broker,
384                 LogicalDatastoreType.OPERATIONAL, identifier);
385         return existingInterfaceMacEntry.orNull();
386     }
387
388     public static InstanceIdentifier<MacEntry> getInterfaceMacEntriesIdentifierOperationalDataPath(String interfaceName,
389             PhysAddress physAddress) {
390         return InstanceIdentifier.builder(ElanInterfaceForwardingEntries.class)
391                 .child(ElanInterfaceMac.class, new ElanInterfaceMacKey(interfaceName))
392                 .child(MacEntry.class, new MacEntryKey(physAddress)).build();
393
394     }
395
396     // elan-forwarding-tables Operational container
397     public Optional<MacEntry> getMacEntryForElanInstance(String elanName, PhysAddress physAddress) {
398         InstanceIdentifier<MacEntry> macId = getMacEntryOperationalDataPath(elanName, physAddress);
399         return read(broker, LogicalDatastoreType.OPERATIONAL, macId);
400     }
401
402     public MacEntry getMacEntryFromElanMacId(InstanceIdentifier identifier) {
403         Optional<MacEntry> existingInterfaceMacEntry = read(broker,
404                 LogicalDatastoreType.OPERATIONAL, identifier);
405         return existingInterfaceMacEntry.orNull();
406     }
407
408     public static InstanceIdentifier<MacEntry> getMacEntryOperationalDataPath(String elanName,
409             PhysAddress physAddress) {
410         return InstanceIdentifier.builder(ElanForwardingTables.class).child(MacTable.class, new MacTableKey(elanName))
411                 .child(MacEntry.class, new MacEntryKey(physAddress)).build();
412     }
413
414     public static InstanceIdentifier<MacTable> getElanMacTableOperationalDataPath(String elanName) {
415         return InstanceIdentifier.builder(ElanForwardingTables.class).child(MacTable.class, new MacTableKey(elanName))
416                 .build();
417     }
418
419     // elan-interface-forwarding-entries Operational container
420     public ElanInterfaceMac getElanInterfaceMacByInterfaceName(String interfaceName) {
421         return getElanInterfaceMacByInterfaceName(broker, interfaceName);
422     }
423
424     @Nullable
425     public static ElanInterfaceMac getElanInterfaceMacByInterfaceName(DataBroker dataBroker, String interfaceName) {
426         InstanceIdentifier<ElanInterfaceMac> elanInterfaceId = getElanInterfaceMacEntriesOperationalDataPath(
427                 interfaceName);
428         return read(dataBroker, LogicalDatastoreType.OPERATIONAL, elanInterfaceId).orNull();
429     }
430
431     /**
432      * Gets the elan interface mac addresses.
433      *
434      * @param interfaceName
435      *            the interface name
436      * @return the elan interface mac addresses
437      */
438     public List<PhysAddress> getElanInterfaceMacAddresses(String interfaceName) {
439         List<PhysAddress> macAddresses = new ArrayList<>();
440         ElanInterfaceMac elanInterfaceMac = getElanInterfaceMacByInterfaceName(interfaceName);
441         if (elanInterfaceMac != null && elanInterfaceMac.getMacEntry() != null) {
442             List<MacEntry> macEntries = elanInterfaceMac.getMacEntry();
443             for (MacEntry macEntry : macEntries) {
444                 macAddresses.add(macEntry.getMacAddress());
445             }
446         }
447         return macAddresses;
448     }
449
450     public static InstanceIdentifier<ElanInterfaceMac> getElanInterfaceMacEntriesOperationalDataPath(
451             String interfaceName) {
452         return InstanceIdentifier.builder(ElanInterfaceForwardingEntries.class)
453                 .child(ElanInterfaceMac.class, new ElanInterfaceMacKey(interfaceName)).build();
454     }
455
456     /**
457      * Returns the list of Interfaces that belong to an Elan on an specific DPN.
458      * Data retrieved from Elan's operational DS: elan-dpn-interfaces container
459      *
460      * @param elanInstanceName
461      *            name of the Elan to which the interfaces must belong to
462      * @param dpId
463      *            Id of the DPN where the interfaces are located
464      * @return the elan interface Info
465      */
466     public DpnInterfaces getElanInterfaceInfoByElanDpn(String elanInstanceName, BigInteger dpId) {
467         InstanceIdentifier<DpnInterfaces> elanDpnInterfacesId = getElanDpnInterfaceOperationalDataPath(elanInstanceName,
468                 dpId);
469         return read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfacesId).orNull();
470     }
471
472     /**
473      * Returns the InstanceIdentifier that points to the Interfaces of an Elan
474      * in a given DPN in the Operational DS. Data retrieved from Elans's
475      * operational DS: dpn-interfaces list
476      *
477      * @param elanInstanceName
478      *            name of the Elan to which the interfaces must belong to
479      * @param dpId
480      *            Id of the DPN where the interfaces are located
481      * @return the elan dpn interface
482      */
483     public static InstanceIdentifier<DpnInterfaces> getElanDpnInterfaceOperationalDataPath(String elanInstanceName,
484             BigInteger dpId) {
485         return InstanceIdentifier.builder(ElanDpnInterfaces.class)
486                 .child(ElanDpnInterfacesList.class, new ElanDpnInterfacesListKey(elanInstanceName))
487                 .child(DpnInterfaces.class, new DpnInterfacesKey(dpId)).build();
488     }
489
490     // elan-tag-name-map Operational Container
491     public ElanTagName getElanInfoByElanTag(long elanTag) {
492         InstanceIdentifier<ElanTagName> elanId = getElanInfoEntriesOperationalDataPath(elanTag);
493         Optional<ElanTagName> existingElanInfo = read(broker,
494                 LogicalDatastoreType.OPERATIONAL, elanId);
495         return existingElanInfo.orNull();
496     }
497
498     public static InstanceIdentifier<ElanTagName> getElanInfoEntriesOperationalDataPath(long elanTag) {
499         return InstanceIdentifier.builder(ElanTagNameMap.class).child(ElanTagName.class, new ElanTagNameKey(elanTag))
500                 .build();
501     }
502
503     // interface-index-tag operational container
504     public Optional<IfIndexInterface> getInterfaceInfoByInterfaceTag(long interfaceTag) {
505         InstanceIdentifier<IfIndexInterface> interfaceId = getInterfaceInfoEntriesOperationalDataPath(interfaceTag);
506         return read(broker, LogicalDatastoreType.OPERATIONAL, interfaceId);
507     }
508
509     public static InstanceIdentifier<IfIndexInterface> getInterfaceInfoEntriesOperationalDataPath(long interfaceTag) {
510         return InstanceIdentifier.builder(IfIndexesInterfaceMap.class)
511                 .child(IfIndexInterface.class, new IfIndexInterfaceKey((int) interfaceTag)).build();
512     }
513
514     public static InstanceIdentifier<ElanDpnInterfacesList> getElanDpnOperationDataPath(String elanInstanceName) {
515         return InstanceIdentifier.builder(ElanDpnInterfaces.class)
516                 .child(ElanDpnInterfacesList.class, new ElanDpnInterfacesListKey(elanInstanceName)).build();
517     }
518
519     public ElanDpnInterfacesList getElanDpnInterfacesList(String elanName) {
520         InstanceIdentifier<ElanDpnInterfacesList> elanDpnInterfaceId = getElanDpnOperationDataPath(elanName);
521         return read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId).orNull();
522     }
523
524     public ElanDpnInterfaces getElanDpnInterfacesList() {
525         InstanceIdentifier<ElanDpnInterfaces> elanDpnInterfaceId = InstanceIdentifier.builder(ElanDpnInterfaces.class)
526                 .build();
527         return read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId).orNull();
528     }
529
530     /**
531      * This method is useful get all ELAN participating CSS dpIds to install
532      * program remote dmac entries and updating remote bc groups for tor
533      * integration.
534      *
535      * @param elanInstanceName
536      *            the elan instance name
537      * @return list of dpIds
538      */
539     @Nonnull
540     public List<BigInteger> getParticipatingDpnsInElanInstance(String elanInstanceName) {
541         List<BigInteger> dpIds = new ArrayList<>();
542         InstanceIdentifier<ElanDpnInterfacesList> elanDpnInterfaceId = getElanDpnOperationDataPath(elanInstanceName);
543         Optional<ElanDpnInterfacesList> existingElanDpnInterfaces = read(broker,
544                 LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId);
545         if (!existingElanDpnInterfaces.isPresent()) {
546             return dpIds;
547         }
548         List<DpnInterfaces> dpnInterfaces = existingElanDpnInterfaces.get().getDpnInterfaces();
549         for (DpnInterfaces dpnInterface : dpnInterfaces) {
550             dpIds.add(dpnInterface.getDpId());
551         }
552         return dpIds;
553     }
554
555     /**
556      * To check given dpId is already present in Elan instance. This can be used
557      * to program flow entry in external tunnel table when a new access port
558      * added for first time into the ELAN instance
559      *
560      * @param dpId
561      *            the dp id
562      * @param elanInstanceName
563      *            the elan instance name
564      * @return true if dpId is already present, otherwise return false
565      */
566     public boolean isDpnAlreadyPresentInElanInstance(BigInteger dpId, String elanInstanceName) {
567         InstanceIdentifier<ElanDpnInterfacesList> elanDpnInterfaceId = getElanDpnOperationDataPath(elanInstanceName);
568         Optional<ElanDpnInterfacesList> existingElanDpnInterfaces = read(broker,
569                 LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId);
570         if (!existingElanDpnInterfaces.isPresent()) {
571             return false;
572         }
573         List<DpnInterfaces> dpnInterfaces = existingElanDpnInterfaces.get().getDpnInterfaces();
574         for (DpnInterfaces dpnInterface : dpnInterfaces) {
575             if (dpnInterface.getDpId().equals(dpId)) {
576                 return true;
577             }
578         }
579         return false;
580     }
581
582     public ElanForwardingTables getElanForwardingList() {
583         InstanceIdentifier<ElanForwardingTables> elanForwardingTableId = InstanceIdentifier
584                 .builder(ElanForwardingTables.class).build();
585         return read(broker, LogicalDatastoreType.OPERATIONAL, elanForwardingTableId).orNull();
586     }
587
588     public static long getElanRemoteBroadCastGroupID(long elanTag) {
589         return ElanConstants.ELAN_GID_MIN + elanTag % ElanConstants.ELAN_GID_MIN * 2;
590     }
591
592     /**
593      * Gets the elan mac table.
594      *
595      * @param elanName
596      *            the elan name
597      * @return the elan mac table
598      */
599     public MacTable getElanMacTable(String elanName) {
600         return getElanMacTable(broker, elanName);
601     }
602
603     @Nullable
604     public static MacTable getElanMacTable(DataBroker dataBroker, String elanName) {
605         InstanceIdentifier<MacTable> elanMacTableId = getElanMacTableOperationalDataPath(elanName);
606         return read(dataBroker, LogicalDatastoreType.OPERATIONAL, elanMacTableId).orNull();
607     }
608
609     public static long getElanLocalBCGId(long elanTag) {
610         return ElanConstants.ELAN_GID_MIN + (elanTag % ElanConstants.ELAN_GID_MIN * 2 - 1);
611     }
612
613     public static long getElanRemoteBCGId(long elanTag) {
614         return ElanConstants.ELAN_GID_MIN + elanTag % ElanConstants.ELAN_GID_MIN * 2;
615     }
616
617     public static long getEtreeLeafLocalBCGId(long etreeLeafTag) {
618         return ElanConstants.ELAN_GID_MIN + (etreeLeafTag % ElanConstants.ELAN_GID_MIN * 2 - 1);
619     }
620
621     public static long getEtreeLeafRemoteBCGId(long etreeLeafTag) {
622         return ElanConstants.ELAN_GID_MIN + etreeLeafTag % ElanConstants.ELAN_GID_MIN * 2;
623     }
624
625     public static BigInteger getElanMetadataLabel(long elanTag, boolean isSHFlagSet) {
626         int shBit = isSHFlagSet ? 1 : 0;
627         return BigInteger.valueOf(elanTag).shiftLeft(24).or(BigInteger.valueOf(shBit));
628     }
629
630     /**
631      * Setting SMAC, DMAC, UDMAC in this DPN and optionally in other DPNs.
632      *
633      * @param elanInfo
634      *            the elan info
635      * @param interfaceInfo
636      *            the interface info
637      * @param macTimeout
638      *            the mac timeout
639      * @param macAddress
640      *            the mac address
641      * @param configureRemoteFlows
642      *            true if remote dmac flows should be configured as well
643      * @param writeFlowGroupTx
644      *            the flow group tx
645      * @throws ElanException in case of issues creating the flow objects
646      */
647     public void setupMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo,
648                               long macTimeout, String macAddress, boolean configureRemoteFlows,
649                               WriteTransaction writeFlowGroupTx) throws ElanException {
650         synchronized (getElanMacDPNKey(elanInfo.getElanTag(), macAddress, interfaceInfo.getDpId())) {
651             setupKnownSmacFlow(elanInfo, interfaceInfo, macTimeout, macAddress, mdsalManager,
652                 writeFlowGroupTx);
653             setupOrigDmacFlows(elanInfo, interfaceInfo, macAddress, configureRemoteFlows, mdsalManager,
654                     writeFlowGroupTx);
655         }
656     }
657
658     public void setupDMacFlowOnRemoteDpn(ElanInstance elanInfo, InterfaceInfo interfaceInfo, BigInteger dstDpId,
659                                          String macAddress, WriteTransaction writeFlowTx) throws ElanException {
660         String elanInstanceName = elanInfo.getElanInstanceName();
661         setupRemoteDmacFlow(dstDpId, interfaceInfo.getDpId(), interfaceInfo.getInterfaceTag(), elanInfo.getElanTag(),
662                 macAddress, elanInstanceName, writeFlowTx, interfaceInfo.getInterfaceName(), elanInfo);
663         LOG.info("Remote Dmac flow entry created for elan Name:{}, logical port Name:{} and"
664                 + " mac address {} on dpn:{}", elanInstanceName, interfaceInfo.getPortName(),
665                 macAddress, dstDpId);
666     }
667
668     /**
669      * Inserts a Flow in SMAC table to state that the MAC has already been
670      * learnt.
671      */
672     private void setupKnownSmacFlow(ElanInstance elanInfo, InterfaceInfo interfaceInfo, long macTimeout,
673             String macAddress, IMdsalApiManager mdsalApiManager, WriteTransaction writeFlowGroupTx) {
674         FlowEntity flowEntity = buildKnownSmacFlow(elanInfo, interfaceInfo, macTimeout, macAddress);
675         mdsalApiManager.addFlowToTx(flowEntity, writeFlowGroupTx);
676         LOG.debug("Known Smac flow entry created for elan Name:{}, logical Interface port:{} and mac address:{}",
677                 elanInfo.getElanInstanceName(), elanInfo.getDescription(), macAddress);
678     }
679
680     public FlowEntity buildKnownSmacFlow(ElanInstance elanInfo, InterfaceInfo interfaceInfo, long macTimeout,
681             String macAddress) {
682         int lportTag = interfaceInfo.getInterfaceTag();
683         // Matching metadata and eth_src fields
684         List<MatchInfo> mkMatches = new ArrayList<>();
685         mkMatches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanInfo.getElanTag(), lportTag),
686                 ElanHelper.getElanMetadataMask()));
687         mkMatches.add(new MatchEthernetSource(new MacAddress(macAddress)));
688         List<InstructionInfo> mkInstructions = new ArrayList<>();
689         mkInstructions.add(new InstructionGotoTable(NwConstants.ELAN_DMAC_TABLE));
690         BigInteger dpId = interfaceInfo.getDpId();
691         long elanTag = getElanTag(broker, elanInfo, interfaceInfo);
692         return new FlowEntityBuilder()
693             .setDpnId(dpId)
694             .setTableId(NwConstants.ELAN_SMAC_TABLE)
695             .setFlowId(getKnownDynamicmacFlowRef(NwConstants.ELAN_SMAC_TABLE, dpId, lportTag, macAddress, elanTag))
696             .setPriority(20)
697             .setFlowName(elanInfo.getDescription())
698             .setIdleTimeOut((int) macTimeout)
699             .setHardTimeOut(0)
700             .setCookie(ElanConstants.COOKIE_ELAN_KNOWN_SMAC.add(BigInteger.valueOf(elanTag)))
701             .setMatchInfoList(mkMatches)
702             .setInstructionInfoList(mkInstructions)
703             .setStrictFlag(true)
704             // If Mac timeout is 0, the flow won't be deleted automatically, so no need to get notified
705             .setSendFlowRemFlag(macTimeout != 0)
706             .build();
707     }
708
709     private static Long getElanTag(DataBroker broker, ElanInstance elanInfo, InterfaceInfo interfaceInfo) {
710         EtreeInterface etreeInterface = getEtreeInterfaceByElanInterfaceName(broker, interfaceInfo.getInterfaceName());
711         if (etreeInterface == null || etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
712             return elanInfo.getElanTag();
713         } else { // Leaf
714             EtreeInstance etreeInstance = elanInfo.getAugmentation(EtreeInstance.class);
715             if (etreeInstance == null) {
716                 LOG.warn("EtreeInterface {} is connected to a non-Etree network: {}",
717                          interfaceInfo.getInterfaceName(), elanInfo.getElanInstanceName());
718                 return elanInfo.getElanTag();
719             } else {
720                 return etreeInstance.getEtreeLeafTagVal().getValue();
721             }
722         }
723     }
724
725     /**
726      * Installs a Flow in INTERNAL_TUNNEL_TABLE of the affected DPN that sends
727      * the packet through the specified interface if the tunnel_id matches the
728      * interface's lportTag.
729      *
730      * @param interfaceInfo
731      *            the interface info
732      * @param mdsalApiManager
733      *            the mdsal API manager
734      * @param writeFlowGroupTx
735      *            the writeFLowGroup tx
736      */
737     public void setupTermDmacFlows(InterfaceInfo interfaceInfo, IMdsalApiManager mdsalApiManager,
738                                    WriteTransaction writeFlowGroupTx) {
739         BigInteger dpId = interfaceInfo.getDpId();
740         int lportTag = interfaceInfo.getInterfaceTag();
741         Flow flow = MDSALUtil.buildFlowNew(NwConstants.INTERNAL_TUNNEL_TABLE,
742                 getIntTunnelTableFlowRef(NwConstants.INTERNAL_TUNNEL_TABLE, lportTag), 5,
743                 String.format("%s:%d", "ITM Flow Entry ", lportTag), 0, 0,
744                 ITMConstants.COOKIE_ITM.add(BigInteger.valueOf(lportTag)),
745                 getTunnelIdMatchForFilterEqualsLPortTag(lportTag),
746                 getInstructionsInPortForOutGroup(interfaceInfo.getInterfaceName()));
747         mdsalApiManager.addFlowToTx(dpId, flow, writeFlowGroupTx);
748         LOG.debug("Terminating service table flow entry created on dpn:{} for logical Interface port:{}", dpId,
749                 interfaceInfo.getPortName());
750     }
751
752     /**
753      * Constructs the FlowName for flows installed in the Internal Tunnel Table,
754      * consisting in tableId + elanTag.
755      *
756      * @param tableId
757      *            table Id
758      * @param elanTag
759      *            elan Tag
760      * @return the Internal tunnel
761      */
762     public static String getIntTunnelTableFlowRef(short tableId, int elanTag) {
763         return new StringBuffer().append(tableId).append(elanTag).toString();
764     }
765
766     /**
767      * Constructs the Matches that checks that the tunnel_id field contains a
768      * specific lportTag.
769      *
770      * @param lportTag
771      *            lportTag that must be checked against the tunnel_id field
772      * @return the list of match Info
773      */
774     public static List<MatchInfo> getTunnelIdMatchForFilterEqualsLPortTag(int lportTag) {
775         List<MatchInfo> mkMatches = new ArrayList<>();
776         // Matching metadata
777         mkMatches.add(new MatchTunnelId(BigInteger.valueOf(lportTag)));
778         return mkMatches;
779     }
780
781     /**
782      * Constructs the Instructions that take the packet over a given interface.
783      *
784      * @param ifName
785      *            Name of the interface where the packet must be sent over. It
786      *            can be a local interface or a tunnel interface (internal or
787      *            external)
788      * @return the Instruction
789      */
790     public List<Instruction> getInstructionsInPortForOutGroup(String ifName) {
791         List<Instruction> mkInstructions = new ArrayList<>();
792         List<Action> actions = getEgressActionsForInterface(ifName, /* tunnelKey */ null);
793
794         mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
795         return mkInstructions;
796     }
797
798     /**
799      * Returns the list of Actions to be taken when sending the packet through
800      * an Elan interface. Note that this interface can refer to an ElanInterface
801      * where the Elan VM is attached to a DPN or an ITM tunnel interface where
802      * Elan traffic can be sent through. In this latter case, the tunnelKey is
803      * mandatory and it can hold serviceId for internal tunnels or the VNI for
804      * external tunnels.
805      *
806      * @param ifName
807      *            the if name
808      * @param tunnelKey
809      *            the tunnel key
810      * @return the egress actions for interface
811      */
812     @SuppressWarnings("checkstyle:IllegalCatch")
813     public List<Action> getEgressActionsForInterface(String ifName, Long tunnelKey) {
814         List<Action> listAction = new ArrayList<>();
815         try {
816             GetEgressActionsForInterfaceInput getEgressActionInput = new GetEgressActionsForInterfaceInputBuilder()
817                     .setIntfName(ifName).setTunnelKey(tunnelKey).build();
818             Future<RpcResult<GetEgressActionsForInterfaceOutput>> result = interfaceManagerRpcService
819                     .getEgressActionsForInterface(getEgressActionInput);
820             RpcResult<GetEgressActionsForInterfaceOutput> rpcResult = result.get();
821             if (!rpcResult.isSuccessful()) {
822                 LOG.debug("RPC Call to Get egress actions for interface {} returned with Errors {}", ifName,
823                         rpcResult.getErrors());
824             } else {
825                 List<Action> actions = rpcResult.getResult().getAction();
826                 listAction = actions;
827             }
828         } catch (Exception e) {
829             LOG.warn("Exception when egress actions for interface {}", ifName, e);
830         }
831         return listAction;
832     }
833
834     private void setupOrigDmacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
835                                     boolean configureRemoteFlows, IMdsalApiManager mdsalApiManager,
836                                     WriteTransaction writeFlowGroupTx)
837                                     throws ElanException {
838         BigInteger dpId = interfaceInfo.getDpId();
839         String ifName = interfaceInfo.getInterfaceName();
840         long ifTag = interfaceInfo.getInterfaceTag();
841         String elanInstanceName = elanInfo.getElanInstanceName();
842
843         Long elanTag = elanInfo.getElanTag();
844
845         setupLocalDmacFlow(elanTag, dpId, ifName, macAddress, elanInfo, mdsalApiManager, ifTag,
846                 writeFlowGroupTx);
847         LOG.debug("Dmac flow entry created for elan Name:{}, logical port Name:{} mand mac address:{} "
848                                     + "on dpn:{}", elanInstanceName, interfaceInfo.getPortName(), macAddress, dpId);
849
850         if (!configureRemoteFlows) {
851             return;
852         }
853
854         List<DpnInterfaces> elanDpns = getInvolvedDpnsInElan(elanInstanceName);
855         for (DpnInterfaces elanDpn : elanDpns) {
856
857             if (elanDpn.getDpId().equals(dpId)) {
858                 continue;
859             }
860
861             // Check for the Remote DPN present in Inventory Manager
862             if (!isDpnPresent(elanDpn.getDpId())) {
863                 continue;
864             }
865
866             // For remote DPNs a flow is needed to indicate that packets of this ELAN going to this MAC need to be
867             // forwarded through the appropriate ITM tunnel
868             setupRemoteDmacFlow(elanDpn.getDpId(), // srcDpn (the remote DPN in this case)
869                     dpId, // dstDpn (the local DPN)
870                     interfaceInfo.getInterfaceTag(), // lportTag of the local interface
871                     elanTag,  // identifier of the Elan
872                     macAddress, // MAC to be programmed in remote DPN
873                     elanInstanceName, writeFlowGroupTx, ifName, elanInfo
874             );
875             LOG.debug("Remote Dmac flow entry created for elan Name:{}, logical port Name:{} and mac address:{} on"
876                         + " dpn:{}", elanInstanceName, interfaceInfo.getPortName(), macAddress, elanDpn.getDpId());
877         }
878
879         // TODO: Make sure that the same is performed against the ElanDevices.
880     }
881
882     @Nonnull
883     public List<DpnInterfaces> getInvolvedDpnsInElan(String elanName) {
884         return getElanDPNByName(elanName);
885     }
886
887     @Nonnull
888     public List<DpnInterfaces> getElanDPNByName(String elanInstanceName) {
889         InstanceIdentifier<ElanDpnInterfacesList> elanIdentifier = getElanDpnOperationDataPath(elanInstanceName);
890         return MDSALUtil.read(broker, LogicalDatastoreType.OPERATIONAL, elanIdentifier).toJavaUtil().map(
891                 ElanDpnInterfacesList::getDpnInterfaces).orElse(Collections.emptyList());
892     }
893
894     private void setupLocalDmacFlow(long elanTag, BigInteger dpId, String ifName, String macAddress,
895             ElanInstance elanInfo, IMdsalApiManager mdsalApiManager, long ifTag, WriteTransaction writeFlowGroupTx) {
896         Flow flowEntity = buildLocalDmacFlowEntry(elanTag, dpId, ifName, macAddress, elanInfo, ifTag);
897         mdsalApiManager.addFlowToTx(dpId, flowEntity, writeFlowGroupTx);
898         installEtreeLocalDmacFlow(elanTag, dpId, ifName, macAddress, elanInfo,
899                 mdsalApiManager, ifTag, writeFlowGroupTx);
900     }
901
902     private void installEtreeLocalDmacFlow(long elanTag, BigInteger dpId, String ifName, String macAddress,
903             ElanInstance elanInfo, IMdsalApiManager mdsalApiManager, long ifTag, WriteTransaction writeFlowGroupTx) {
904         EtreeInterface etreeInterface = getEtreeInterfaceByElanInterfaceName(broker, ifName);
905         if (etreeInterface != null) {
906             if (etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
907                 EtreeLeafTagName etreeTagName = elanEtreeUtils.getEtreeLeafTagByElanTag(elanTag);
908                 if (etreeTagName == null) {
909                     LOG.warn("Interface {} seems like it belongs to Etree but etreeTagName from elanTag {} is null",
910                              ifName, elanTag);
911                 } else {
912                     Flow flowEntity = buildLocalDmacFlowEntry(etreeTagName.getEtreeLeafTag().getValue(), dpId, ifName,
913                             macAddress, elanInfo, ifTag);
914                     mdsalApiManager.addFlowToTx(dpId, flowEntity, writeFlowGroupTx);
915                 }
916             }
917         }
918     }
919
920     public static String getKnownDynamicmacFlowRef(short tableId, BigInteger dpId, long lporTag, String macAddress,
921             long elanTag) {
922         return new StringBuffer().append(tableId).append(elanTag).append(dpId).append(lporTag).append(macAddress)
923                 .toString();
924     }
925
926     public static String getKnownDynamicmacFlowRef(short tableId, BigInteger dpId, BigInteger remoteDpId,
927             String macAddress, long elanTag) {
928         return new StringBuffer().append(tableId).append(elanTag).append(dpId).append(remoteDpId).append(macAddress)
929                 .toString();
930     }
931
932     public static String getKnownDynamicmacFlowRef(short tableId, BigInteger dpId, String macAddress, long elanTag) {
933         return new StringBuffer().append(tableId).append(elanTag).append(dpId).append(macAddress).toString();
934     }
935
936     public static String getKnownDynamicmacFlowRef(short elanDmacTable, BigInteger dpId, String extDeviceNodeId,
937             String dstMacAddress, long elanTag, boolean shFlag) {
938         return new StringBuffer().append(elanDmacTable).append(elanTag).append(dpId).append(extDeviceNodeId)
939                 .append(dstMacAddress).append(shFlag).toString();
940     }
941
942     /**
943      * Builds the flow to be programmed in the DMAC table of the local DPN (that
944      * is, where the MAC is attached to). This flow consists in:
945      *
946      * <p>Match: + elanTag in metadata + packet goes to a MAC locally attached
947      * Actions: + optionally, pop-vlan + set-vlan-id + output to ifName's
948      * portNumber
949      *
950      * @param elanTag
951      *            the elan tag
952      * @param dpId
953      *            the dp id
954      * @param ifName
955      *            the if name
956      * @param macAddress
957      *            the mac address
958      * @param elanInfo
959      *            the elan info
960      * @param ifTag
961      *            the if tag
962      * @return the flow
963      */
964     public Flow buildLocalDmacFlowEntry(long elanTag, BigInteger dpId, String ifName, String macAddress,
965             ElanInstance elanInfo, long ifTag) {
966
967         List<MatchInfo> mkMatches = new ArrayList<>();
968         mkMatches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanTag), MetaDataUtil.METADATA_MASK_SERVICE));
969         mkMatches.add(new MatchEthernetDestination(new MacAddress(macAddress)));
970
971         List<Instruction> mkInstructions = new ArrayList<>();
972         List<Action> actions = getEgressActionsForInterface(ifName, /* tunnelKey */ null);
973         mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
974         Flow flow = MDSALUtil.buildFlowNew(NwConstants.ELAN_DMAC_TABLE,
975                 getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, ifTag, macAddress, elanTag), 20,
976                 elanInfo.getElanInstanceName(), 0, 0, ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(
977                         BigInteger.valueOf(elanTag)), mkMatches, mkInstructions);
978
979         return flow;
980     }
981
982     public void setupRemoteDmacFlow(BigInteger srcDpId, BigInteger destDpId, int lportTag, long elanTag, String
983             macAddress, String displayName, WriteTransaction writeFlowGroupTx, String interfaceName, ElanInstance
984             elanInstance) throws ElanException {
985         if (interfaceManager.isExternalInterface(interfaceName)) {
986             LOG.debug("Ignoring install remote DMAC {} flow on provider interface {} elan {}",
987                     macAddress, interfaceName, elanInstance.getElanInstanceName());
988             return;
989         }
990         Flow flowEntity;
991         // if openstack-vni-semantics are enforced, segmentation ID is passed as network VNI for VxLAN based provider
992         // networks, 0 otherwise
993         long lportTagOrVni = !isOpenstackVniSemanticsEnforced() ? lportTag : isVxlan(elanInstance)
994                 ? elanInstance.getSegmentationId() : 0;
995         flowEntity = buildRemoteDmacFlowEntry(srcDpId, destDpId, lportTagOrVni, elanTag, macAddress, displayName,
996                 elanInstance);
997         mdsalManager.addFlowToTx(srcDpId, flowEntity, writeFlowGroupTx);
998         setupEtreeRemoteDmacFlow(srcDpId, destDpId, lportTagOrVni, elanTag, macAddress, displayName, interfaceName,
999                 writeFlowGroupTx, elanInstance);
1000     }
1001
1002     private void setupEtreeRemoteDmacFlow(BigInteger srcDpId, BigInteger destDpId, long lportTagOrVni, long elanTag,
1003                                           String macAddress, String displayName, String interfaceName,
1004                                           WriteTransaction writeFlowGroupTx, ElanInstance elanInstance)
1005                                           throws ElanException {
1006         Flow flowEntity;
1007         EtreeInterface etreeInterface = getEtreeInterfaceByElanInterfaceName(broker, interfaceName);
1008         if (etreeInterface != null) {
1009             if (etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
1010                 EtreeLeafTagName etreeTagName = elanEtreeUtils.getEtreeLeafTagByElanTag(elanTag);
1011                 if (etreeTagName == null) {
1012                     LOG.warn("Interface " + interfaceName
1013                             + " seems like it belongs to Etree but etreeTagName from elanTag " + elanTag + " is null.");
1014                 } else {
1015                     flowEntity = buildRemoteDmacFlowEntry(srcDpId, destDpId, lportTagOrVni,
1016                             etreeTagName.getEtreeLeafTag().getValue(), macAddress, displayName, elanInstance);
1017                     mdsalManager.addFlowToTx(srcDpId, flowEntity, writeFlowGroupTx);
1018                 }
1019             }
1020         }
1021     }
1022
1023     /**
1024      * Builds a Flow to be programmed in a remote DPN's DMAC table. This flow
1025      * consists in: Match: + elanTag in packet's metadata + packet going to a
1026      * MAC known to be located in another DPN Actions: + set_tunnel_id
1027      * + output ITM internal tunnel interface with the other DPN
1028      *
1029      * @param srcDpId
1030      *            the src Dpn Id
1031      * @param destDpId
1032      *            dest Dp Id
1033      * @param lportTagOrVni
1034      *            lportTag or network VNI
1035      * @param elanTag
1036      *            elan Tag
1037      * @param macAddress
1038      *            macAddress
1039      * @param displayName
1040      *            display Name
1041      * @return the flow remote Dmac
1042      * @throws ElanException in case of issues creating the flow objects
1043      */
1044     @SuppressWarnings("checkstyle:IllegalCatch")
1045     public Flow buildRemoteDmacFlowEntry(BigInteger srcDpId, BigInteger destDpId, long lportTagOrVni, long elanTag,
1046             String macAddress, String displayName, ElanInstance elanInstance) throws ElanException {
1047         List<MatchInfo> mkMatches = new ArrayList<>();
1048         mkMatches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanTag), MetaDataUtil.METADATA_MASK_SERVICE));
1049         mkMatches.add(new MatchEthernetDestination(new MacAddress(macAddress)));
1050
1051         List<Instruction> mkInstructions = new ArrayList<>();
1052
1053         // List of Action for the provided Source and Destination DPIDs
1054         try {
1055             List<Action> actions = null;
1056             if (isVlan(elanInstance) || isFlat(elanInstance)) {
1057                 String interfaceName = getExternalElanInterface(elanInstance.getElanInstanceName(), srcDpId);
1058                 if (null == interfaceName) {
1059                     LOG.info("buildRemoteDmacFlowEntry: Could not find interfaceName for {} {}", srcDpId,
1060                         elanInstance);
1061                 }
1062                 actions = getEgressActionsForInterface(interfaceName, null);
1063             } else if (isVxlan(elanInstance)) {
1064                 actions = elanItmUtils.getInternalTunnelItmEgressAction(srcDpId, destDpId, lportTagOrVni);
1065             }
1066             mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
1067         } catch (Exception e) {
1068             LOG.error("Could not get egress actions to add to flow for srcDpId=" + srcDpId + ", destDpId=" + destDpId
1069                     + ", lportTag/VNI=" + lportTagOrVni, e);
1070         }
1071
1072         Flow flow = MDSALUtil.buildFlowNew(NwConstants.ELAN_DMAC_TABLE,
1073                 getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, srcDpId, destDpId, macAddress, elanTag),
1074                 20, /* prio */
1075                 displayName, 0, /* idleTimeout */
1076                 0, /* hardTimeout */
1077                 ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(BigInteger.valueOf(elanTag)), mkMatches, mkInstructions);
1078
1079         return flow;
1080
1081     }
1082
1083     public void deleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, MacEntry macEntry,
1084             WriteTransaction deleteFlowGroupTx) {
1085         if (elanInfo == null || interfaceInfo == null) {
1086             return;
1087         }
1088         String macAddress = macEntry.getMacAddress().getValue();
1089         synchronized (getElanMacDPNKey(elanInfo.getElanTag(), macAddress, interfaceInfo.getDpId())) {
1090             deleteMacFlows(elanInfo, interfaceInfo, macAddress, /* alsoDeleteSMAC */ true, deleteFlowGroupTx);
1091         }
1092     }
1093
1094     public void deleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1095             boolean deleteSmac, WriteTransaction deleteFlowGroupTx) {
1096         String elanInstanceName = elanInfo.getElanInstanceName();
1097         List<DpnInterfaces> remoteFEs = getInvolvedDpnsInElan(elanInstanceName);
1098         BigInteger srcdpId = interfaceInfo.getDpId();
1099         boolean isFlowsRemovedInSrcDpn = false;
1100         for (DpnInterfaces dpnInterface : remoteFEs) {
1101             Long elanTag = elanInfo.getElanTag();
1102             BigInteger dstDpId = dpnInterface.getDpId();
1103             if (executeDeleteMacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, elanInstanceName, srcdpId,
1104                     elanTag, dstDpId, deleteFlowGroupTx)) {
1105                 isFlowsRemovedInSrcDpn = true;
1106             }
1107             executeEtreeDeleteMacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, elanInstanceName, srcdpId,
1108                     elanTag, dstDpId, deleteFlowGroupTx);
1109         }
1110         if (!isFlowsRemovedInSrcDpn) {
1111             deleteSmacAndDmacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, deleteFlowGroupTx);
1112         }
1113     }
1114
1115     private void executeEtreeDeleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1116             boolean deleteSmac, String elanInstanceName, BigInteger srcdpId, Long elanTag, BigInteger dstDpId,
1117             WriteTransaction deleteFlowGroupTx) {
1118         EtreeLeafTagName etreeLeafTag = elanEtreeUtils.getEtreeLeafTagByElanTag(elanTag);
1119         if (etreeLeafTag != null) {
1120             executeDeleteMacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, elanInstanceName, srcdpId,
1121                     etreeLeafTag.getEtreeLeafTag().getValue(), dstDpId, deleteFlowGroupTx);
1122         }
1123     }
1124
1125     private boolean executeDeleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1126             boolean deleteSmac, String elanInstanceName, BigInteger srcdpId, Long elanTag, BigInteger dstDpId,
1127             WriteTransaction deleteFlowGroupTx) {
1128         boolean isFlowsRemovedInSrcDpn = false;
1129         if (dstDpId.equals(srcdpId)) {
1130             isFlowsRemovedInSrcDpn = true;
1131             deleteSmacAndDmacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, deleteFlowGroupTx);
1132         } else if (isDpnPresent(dstDpId)) {
1133             mdsalManager
1134                     .removeFlowToTx(dstDpId,
1135                             MDSALUtil.buildFlow(NwConstants.ELAN_DMAC_TABLE, getKnownDynamicmacFlowRef(
1136                                     NwConstants.ELAN_DMAC_TABLE, dstDpId, srcdpId, macAddress, elanTag)),
1137                             deleteFlowGroupTx);
1138             LOG.debug("Dmac flow entry deleted for elan:{}, logical interface port:{} and mac address:{} on dpn:{}",
1139                     elanInstanceName, interfaceInfo.getPortName(), macAddress, dstDpId);
1140         }
1141         return isFlowsRemovedInSrcDpn;
1142     }
1143
1144     private void deleteSmacAndDmacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1145             boolean deleteSmac, WriteTransaction deleteFlowGroupTx) {
1146         String elanInstanceName = elanInfo.getElanInstanceName();
1147         long ifTag = interfaceInfo.getInterfaceTag();
1148         BigInteger srcdpId = interfaceInfo.getDpId();
1149         Long elanTag = elanInfo.getElanTag();
1150         if (deleteSmac) {
1151             mdsalManager
1152                     .removeFlowToTx(srcdpId,
1153                             MDSALUtil.buildFlow(NwConstants.ELAN_SMAC_TABLE, getKnownDynamicmacFlowRef(
1154                                     NwConstants.ELAN_SMAC_TABLE, srcdpId, ifTag, macAddress, elanTag)),
1155                             deleteFlowGroupTx);
1156         }
1157         mdsalManager.removeFlowToTx(srcdpId,
1158                 MDSALUtil.buildFlow(NwConstants.ELAN_DMAC_TABLE,
1159                         getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, srcdpId, ifTag, macAddress, elanTag)),
1160                 deleteFlowGroupTx);
1161         LOG.debug("All the required flows deleted for elan:{}, logical Interface port:{} and MAC address:{} on dpn:{}",
1162                 elanInstanceName, interfaceInfo.getPortName(), macAddress, srcdpId);
1163     }
1164
1165     /**
1166      * Updates the Elan information in the Operational DS. It also updates the
1167      * ElanInstance in the Config DS by setting the adquired elanTag.
1168      *
1169      * @param broker
1170      *            the broker
1171      * @param idManager
1172      *            the id manager
1173      * @param elanInstanceAdded
1174      *            the elan instance added
1175      * @param elanInterfaces
1176      *            the elan interfaces
1177      * @param tx
1178      *            transaction
1179      *
1180      * @return the updated ELAN instance.
1181      */
1182     public static ElanInstance updateOperationalDataStore(DataBroker broker, IdManagerService idManager,
1183             ElanInstance elanInstanceAdded, List<String> elanInterfaces, WriteTransaction tx) {
1184         String elanInstanceName = elanInstanceAdded.getElanInstanceName();
1185         Long elanTag = elanInstanceAdded.getElanTag();
1186         if (elanTag == null || elanTag == 0L) {
1187             elanTag = retrieveNewElanTag(idManager, elanInstanceName);
1188         }
1189         Elan elanInfo = new ElanBuilder().setName(elanInstanceName).setElanInterfaces(elanInterfaces)
1190                 .setKey(new ElanKey(elanInstanceName)).build();
1191
1192         // Add the ElanState in the elan-state operational data-store
1193         tx.put(LogicalDatastoreType.OPERATIONAL, getElanInstanceOperationalDataPath(elanInstanceName),
1194                 elanInfo, WriteTransaction.CREATE_MISSING_PARENTS);
1195
1196         // Add the ElanMacTable in the elan-mac-table operational data-store
1197         MacTable elanMacTable = new MacTableBuilder().setKey(new MacTableKey(elanInstanceName)).build();
1198         tx.put(LogicalDatastoreType.OPERATIONAL, getElanMacTableOperationalDataPath(elanInstanceName),
1199                 elanMacTable, WriteTransaction.CREATE_MISSING_PARENTS);
1200
1201         ElanTagNameBuilder elanTagNameBuilder = new ElanTagNameBuilder().setElanTag(elanTag)
1202                 .setKey(new ElanTagNameKey(elanTag)).setName(elanInstanceName);
1203         long etreeLeafTag = -1;
1204         if (isEtreeInstance(elanInstanceAdded)) {
1205             etreeLeafTag = retrieveNewElanTag(idManager,elanInstanceName + ElanConstants
1206                     .LEAVES_POSTFIX);
1207             EtreeLeafTagName etreeLeafTagName = new EtreeLeafTagNameBuilder()
1208                     .setEtreeLeafTag(new EtreeLeafTag(etreeLeafTag)).build();
1209             elanTagNameBuilder.addAugmentation(EtreeLeafTagName.class, etreeLeafTagName);
1210             addTheLeafTagAsElanTag(broker, elanInstanceName, etreeLeafTag, tx);
1211         }
1212         ElanTagName elanTagName = elanTagNameBuilder.build();
1213
1214         // Add the ElanTag to ElanName in the elan-tag-name Operational
1215         // data-store
1216         tx.put(LogicalDatastoreType.OPERATIONAL,
1217                 getElanInfoEntriesOperationalDataPath(elanTag), elanTagName);
1218
1219         // Updates the ElanInstance Config DS by setting the just acquired
1220         // elanTag
1221         ElanInstanceBuilder elanInstanceBuilder = new ElanInstanceBuilder().setElanInstanceName(elanInstanceName)
1222                 .setDescription(elanInstanceAdded.getDescription())
1223                 .setMacTimeout(elanInstanceAdded.getMacTimeout() == null
1224                         ? Long.valueOf(ElanConstants.DEFAULT_MAC_TIME_OUT) : elanInstanceAdded.getMacTimeout())
1225                 .setKey(elanInstanceAdded.getKey()).setElanTag(elanTag);
1226         if (isEtreeInstance(elanInstanceAdded)) {
1227             EtreeInstance etreeInstance = new EtreeInstanceBuilder().setEtreeLeafTagVal(new EtreeLeafTag(etreeLeafTag))
1228                     .build();
1229             elanInstanceBuilder.addAugmentation(EtreeInstance.class, etreeInstance);
1230         }
1231         ElanInstance elanInstanceWithTag = elanInstanceBuilder.build();
1232         tx.merge(LogicalDatastoreType.CONFIGURATION, ElanHelper.getElanInstanceConfigurationDataPath(elanInstanceName),
1233                 elanInstanceWithTag, WriteTransaction.CREATE_MISSING_PARENTS);
1234         return elanInstanceWithTag;
1235     }
1236
1237     private static void addTheLeafTagAsElanTag(DataBroker broker, String elanInstanceName, long etreeLeafTag,
1238             WriteTransaction tx) {
1239         ElanTagName etreeTagAsElanTag = new ElanTagNameBuilder().setElanTag(etreeLeafTag)
1240                 .setKey(new ElanTagNameKey(etreeLeafTag)).setName(elanInstanceName).build();
1241         tx.put(LogicalDatastoreType.OPERATIONAL,
1242                 getElanInfoEntriesOperationalDataPath(etreeLeafTag), etreeTagAsElanTag);
1243     }
1244
1245     private static boolean isEtreeInstance(ElanInstance elanInstanceAdded) {
1246         return elanInstanceAdded.getAugmentation(EtreeInstance.class) != null;
1247     }
1248
1249     public boolean isDpnPresent(BigInteger dpnId) {
1250         String dpn = String.format("%s:%s", "openflow", dpnId);
1251         NodeId nodeId = new NodeId(dpn);
1252
1253         InstanceIdentifier<Node> node = InstanceIdentifier.builder(Nodes.class).child(Node.class, new NodeKey(nodeId))
1254                 .build();
1255         return read(broker, LogicalDatastoreType.CONFIGURATION, node).isPresent();
1256     }
1257
1258     public static ServicesInfo getServiceInfo(String elanInstanceName, String interfaceName) {
1259         return InterfaceServiceUtil.buildServiceInfo(elanInstanceName + "." + interfaceName,
1260                 ElanConstants.ELAN_SERVICE_PRIORITY);
1261     }
1262
1263     public static String getElanServiceName(String elanName, String interfaceName) {
1264         return "elan." + elanName + interfaceName;
1265     }
1266
1267     public static BoundServices getBoundServices(String serviceName, short servicePriority, int flowPriority,
1268             BigInteger cookie, List<Instruction> instructions) {
1269         StypeOpenflowBuilder augBuilder = new StypeOpenflowBuilder().setFlowCookie(cookie).setFlowPriority(flowPriority)
1270                 .setInstruction(instructions);
1271         return new BoundServicesBuilder().setKey(new BoundServicesKey(servicePriority)).setServiceName(serviceName)
1272                 .setServicePriority(servicePriority).setServiceType(ServiceTypeFlowBased.class)
1273                 .addAugmentation(StypeOpenflow.class, augBuilder.build()).build();
1274     }
1275
1276     public static InstanceIdentifier<BoundServices> buildServiceId(String interfaceName, short serviceIndex) {
1277         return InstanceIdentifier.builder(ServiceBindings.class)
1278                 .child(ServicesInfo.class, new ServicesInfoKey(interfaceName, ServiceModeIngress.class))
1279                 .child(BoundServices.class, new BoundServicesKey(serviceIndex)).build();
1280     }
1281
1282     public static List<MatchInfo> getTunnelMatchesForServiceId(int elanTag) {
1283         List<MatchInfo> mkMatches = new ArrayList<>();
1284         // Matching metadata
1285         mkMatches.add(new MatchTunnelId(BigInteger.valueOf(elanTag)));
1286
1287         return mkMatches;
1288     }
1289
1290     public void removeTerminatingServiceAction(BigInteger destDpId, int serviceId) {
1291         RemoveTerminatingServiceActionsInput input = new RemoveTerminatingServiceActionsInputBuilder()
1292                 .setDpnId(destDpId).setServiceId(serviceId).build();
1293         Future<RpcResult<Void>> futureObject = itmRpcService.removeTerminatingServiceActions(input);
1294         try {
1295             RpcResult<Void> result = futureObject.get();
1296             if (result.isSuccessful()) {
1297                 LOG.debug("Successfully completed removeTerminatingServiceActions for ELAN with serviceId {} on "
1298                                 + "dpn {}", serviceId, destDpId);
1299             } else {
1300                 LOG.debug("Failure in removeTerminatingServiceAction RPC call for ELAN with serviceId {} on "
1301                         + "dpn {}", serviceId, destDpId);
1302             }
1303         } catch (InterruptedException | ExecutionException e) {
1304             LOG.error("Error in RPC call removeTerminatingServiceActions for ELAN with serviceId {} on "
1305                     + "dpn {}: {}", serviceId, destDpId, e);
1306         }
1307     }
1308
1309     /**
1310      * Gets the external tunnel.
1311      *
1312      * @param sourceDevice
1313      *            the source device
1314      * @param destinationDevice
1315      *            the destination device
1316      * @param datastoreType
1317      *            the datastore type
1318      * @return the external tunnel
1319      */
1320     public ExternalTunnel getExternalTunnel(String sourceDevice, String destinationDevice,
1321             LogicalDatastoreType datastoreType) {
1322         Class<? extends TunnelTypeBase> tunType = TunnelTypeVxlan.class;
1323         InstanceIdentifier<ExternalTunnel> iid = InstanceIdentifier.builder(ExternalTunnelList.class)
1324                 .child(ExternalTunnel.class, new ExternalTunnelKey(destinationDevice, sourceDevice, tunType)).build();
1325         return read(broker, datastoreType, iid).orNull();
1326     }
1327
1328     /**
1329      * Gets the external tunnel.
1330      *
1331      * @param interfaceName
1332      *            the interface name
1333      * @param datastoreType
1334      *            the datastore type
1335      * @return the external tunnel
1336      */
1337     public ExternalTunnel getExternalTunnel(String interfaceName, LogicalDatastoreType datastoreType) {
1338         ExternalTunnel externalTunnel = null;
1339         List<ExternalTunnel> externalTunnels = getAllExternalTunnels(datastoreType);
1340         for (ExternalTunnel tunnel : externalTunnels) {
1341             if (StringUtils.equalsIgnoreCase(interfaceName, tunnel.getTunnelInterfaceName())) {
1342                 externalTunnel = tunnel;
1343                 break;
1344             }
1345         }
1346         return externalTunnel;
1347     }
1348
1349     /**
1350      * Gets the all external tunnels.
1351      *
1352      * @param datastoreType
1353      *            the data store type
1354      * @return the all external tunnels
1355      */
1356     public List<ExternalTunnel> getAllExternalTunnels(LogicalDatastoreType datastoreType) {
1357         InstanceIdentifier<ExternalTunnelList> iid = InstanceIdentifier.builder(ExternalTunnelList.class).build();
1358         return read(broker, datastoreType, iid).toJavaUtil().map(ExternalTunnelList::getExternalTunnel).orElse(
1359                 Collections.emptyList());
1360     }
1361
1362     public static List<MatchInfo> buildMatchesForElanTagShFlagAndDstMac(long elanTag, boolean shFlag, String macAddr) {
1363         List<MatchInfo> mkMatches = new ArrayList<>();
1364         mkMatches.add(
1365                 new MatchMetadata(getElanMetadataLabel(elanTag, shFlag), MetaDataUtil.METADATA_MASK_SERVICE_SH_FLAG));
1366         mkMatches.add(new MatchEthernetDestination(new MacAddress(macAddr)));
1367         return mkMatches;
1368     }
1369
1370     /**
1371      * Checks if is interface operational.
1372      *
1373      * @param interfaceName
1374      *            the interface name
1375      * @param dataBroker
1376      *            the data broker
1377      * @return true, if is interface operational
1378      */
1379     public static boolean isInterfaceOperational(String interfaceName, DataBroker dataBroker) {
1380         if (StringUtils.isBlank(interfaceName)) {
1381             return false;
1382         }
1383         Interface ifState = getInterfaceStateFromOperDS(interfaceName, dataBroker);
1384         if (ifState == null) {
1385             return false;
1386         }
1387         return ifState.getOperStatus() == OperStatus.Up && ifState.getAdminStatus() == AdminStatus.Up;
1388     }
1389
1390     /**
1391      * Gets the interface state from operational ds.
1392      *
1393      * @param interfaceName
1394      *            the interface name
1395      * @param dataBroker
1396      *            the data broker
1397      * @return the interface state from oper ds
1398      */
1399     public static org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1400         .ietf.interfaces.rev140508.interfaces.state.Interface getInterfaceStateFromOperDS(
1401             String interfaceName, DataBroker dataBroker) {
1402         InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1403             .ietf.interfaces.rev140508.interfaces.state.Interface> ifStateId = createInterfaceStateInstanceIdentifier(
1404                 interfaceName);
1405         return MDSALUtil.read(dataBroker, LogicalDatastoreType.OPERATIONAL, ifStateId).orNull();
1406     }
1407
1408     /**
1409      * Creates the interface state instance identifier.
1410      *
1411      * @param interfaceName
1412      *            the interface name
1413      * @return the instance identifier
1414      */
1415     public static InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1416         .ietf.interfaces.rev140508.interfaces.state.Interface> createInterfaceStateInstanceIdentifier(
1417             String interfaceName) {
1418         InstanceIdentifierBuilder<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1419             .ietf.interfaces.rev140508.interfaces.state.Interface> idBuilder = InstanceIdentifier
1420                 .builder(InterfacesState.class)
1421                 .child(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1422                         .ietf.interfaces.rev140508.interfaces.state.Interface.class,
1423                         new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1424                             .ietf.interfaces.rev140508.interfaces.state.InterfaceKey(
1425                                 interfaceName));
1426         return idBuilder.build();
1427     }
1428
1429     public static CheckedFuture<Void, TransactionCommitFailedException> waitForTransactionToComplete(
1430             WriteTransaction tx) {
1431         CheckedFuture<Void, TransactionCommitFailedException> futures = tx.submit();
1432         try {
1433             futures.get();
1434         } catch (InterruptedException | ExecutionException e) {
1435             LOG.error("Error writing to datastore {}", e);
1436         }
1437         return futures;
1438     }
1439
1440     public static boolean isVxlanNetwork(DataBroker broker, String elanInstanceName) {
1441         ElanInstance elanInstance = getElanInstanceByName(broker, elanInstanceName);
1442         return elanInstance != null && isVxlan(elanInstance);
1443     }
1444
1445     public static boolean isVxlan(ElanInstance elanInstance) {
1446         return elanInstance != null && elanInstance.getSegmentType() != null
1447                 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
1448                 && elanInstance.getSegmentationId() != null && elanInstance.getSegmentationId() != 0;
1449     }
1450
1451     private static boolean isVxlanSegment(ElanInstance elanInstance) {
1452         if (elanInstance != null) {
1453             List<ElanSegments> elanSegments = elanInstance.getElanSegments();
1454             if (elanSegments != null) {
1455                 for (ElanSegments segment : elanSegments) {
1456                     if (segment != null && segment.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
1457                             && segment.getSegmentationId() != null
1458                             && segment.getSegmentationId().longValue() != 0) {
1459                         return true;
1460                     }
1461                 }
1462             }
1463         }
1464         return false;
1465     }
1466
1467     public static boolean isVxlanNetworkOrVxlanSegment(ElanInstance elanInstance) {
1468         return isVxlan(elanInstance) || isVxlanSegment(elanInstance);
1469     }
1470
1471     public static Long getVxlanSegmentationId(ElanInstance elanInstance) {
1472         Long segmentationId = 0L;
1473         if (elanInstance == null) {
1474             return segmentationId;
1475         }
1476
1477         if (elanInstance.getSegmentType() != null
1478                 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
1479                 && elanInstance.getSegmentationId() != null && elanInstance.getSegmentationId().longValue() != 0) {
1480             segmentationId = elanInstance.getSegmentationId();
1481         } else {
1482             for (ElanSegments segment: elanInstance.getElanSegments()) {
1483                 if (segment != null && segment.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
1484                     && segment.getSegmentationId() != null
1485                     && segment.getSegmentationId().longValue() != 0) {
1486                     segmentationId = segment.getSegmentationId();
1487                 }
1488             }
1489         }
1490         return segmentationId;
1491     }
1492
1493     public static boolean isVlan(ElanInstance elanInstance) {
1494         return elanInstance != null && elanInstance.getSegmentType() != null
1495                 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeVlan.class)
1496                 && elanInstance.getSegmentationId() != null && elanInstance.getSegmentationId() != 0;
1497     }
1498
1499     public static boolean isFlat(ElanInstance elanInstance) {
1500         return elanInstance != null && elanInstance.getSegmentType() != null
1501                 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeFlat.class);
1502     }
1503
1504     public void addDmacRedirectToDispatcherFlows(Long elanTag, String displayName,
1505             String macAddress, List<BigInteger> dpnIds) {
1506         for (BigInteger dpId : dpnIds) {
1507             WriteTransaction writeTx = broker.newWriteOnlyTransaction();
1508             mdsalManager.addFlowToTx(buildDmacRedirectToDispatcherFlow(dpId, macAddress, displayName, elanTag),
1509                     writeTx);
1510             writeTx.submit();
1511         }
1512     }
1513
1514     public void removeDmacRedirectToDispatcherFlows(Long elanTag, String macAddress, List<BigInteger> dpnIds) {
1515         for (BigInteger dpId : dpnIds) {
1516             String flowId = getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, macAddress, elanTag);
1517             mdsalManager.removeFlow(dpId, MDSALUtil.buildFlow(NwConstants.ELAN_DMAC_TABLE, flowId));
1518         }
1519     }
1520
1521     public static FlowEntity buildDmacRedirectToDispatcherFlow(BigInteger dpId, String dstMacAddress,
1522             String displayName, long elanTag) {
1523         List<MatchInfo> matches = new ArrayList<>();
1524         matches.add(new MatchMetadata(ElanHelper.getElanMetadataLabel(elanTag), MetaDataUtil.METADATA_MASK_SERVICE));
1525         matches.add(new MatchEthernetDestination(new MacAddress(dstMacAddress)));
1526         List<InstructionInfo> instructions = new ArrayList<>();
1527         List<ActionInfo> actions = new ArrayList<>();
1528         actions.add(new ActionNxResubmit(NwConstants.LPORT_DISPATCHER_TABLE));
1529
1530         instructions.add(new InstructionApplyActions(actions));
1531         String flowId = getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, dstMacAddress, elanTag);
1532         FlowEntity flow  = MDSALUtil.buildFlowEntity(dpId, NwConstants.ELAN_DMAC_TABLE, flowId, 20, displayName, 0, 0,
1533                 ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(BigInteger.valueOf(elanTag)),
1534                 matches, instructions);
1535         return flow;
1536     }
1537
1538     /**
1539      * Add Mac Address to ElanInterfaceForwardingEntries and ElanForwardingTables
1540      * Install SMAC and DMAC flows.
1541      */
1542     public void addMacEntryToDsAndSetupFlows(String interfaceName,
1543             String macAddress, String elanName, WriteTransaction interfaceTx, WriteTransaction flowTx, int macTimeOut)
1544             throws ElanException {
1545         LOG.trace("Adding mac address {} and interface name {} to ElanInterfaceForwardingEntries and "
1546             + "ElanForwardingTables DS", macAddress, interfaceName);
1547         BigInteger timeStamp = new BigInteger(String.valueOf(System.currentTimeMillis()));
1548         PhysAddress physAddress = new PhysAddress(macAddress);
1549         MacEntry macEntry = new MacEntryBuilder().setInterface(interfaceName).setMacAddress(physAddress)
1550                 .setKey(new MacEntryKey(physAddress)).setControllerLearnedForwardingEntryTimestamp(timeStamp)
1551                 .setIsStaticAddress(false).build();
1552         InstanceIdentifier<MacEntry> macEntryId = ElanUtils
1553                 .getInterfaceMacEntriesIdentifierOperationalDataPath(interfaceName, physAddress);
1554         interfaceTx.put(LogicalDatastoreType.OPERATIONAL, macEntryId, macEntry);
1555         InstanceIdentifier<MacEntry> elanMacEntryId = ElanUtils.getMacEntryOperationalDataPath(elanName, physAddress);
1556         interfaceTx.put(LogicalDatastoreType.OPERATIONAL, elanMacEntryId, macEntry);
1557         ElanInstance elanInstance = ElanUtils.getElanInstanceByName(broker, elanName);
1558         setupMacFlows(elanInstance, interfaceManager.getInterfaceInfo(interfaceName), macTimeOut, macAddress, true,
1559                 flowTx);
1560     }
1561
1562     /**
1563      * Remove Mac Address from ElanInterfaceForwardingEntries and ElanForwardingTables
1564      * Remove SMAC and DMAC flows.
1565      */
1566     public void deleteMacEntryFromDsAndRemoveFlows(String interfaceName,
1567             String macAddress, String elanName, WriteTransaction interfaceTx, WriteTransaction flowTx) {
1568         LOG.trace("Deleting mac address {} and interface name {} from ElanInterfaceForwardingEntries "
1569                 + "and ElanForwardingTables DS", macAddress, interfaceName);
1570         PhysAddress physAddress = new PhysAddress(macAddress);
1571         MacEntry macEntry = getInterfaceMacEntriesOperationalDataPath(interfaceName, physAddress);
1572         InterfaceInfo interfaceInfo = interfaceManager.getInterfaceInfo(interfaceName);
1573         if (macEntry != null && interfaceInfo != null) {
1574             deleteMacFlows(ElanUtils.getElanInstanceByName(broker, elanName), interfaceInfo, macEntry, flowTx);
1575         }
1576         interfaceTx.delete(LogicalDatastoreType.OPERATIONAL,
1577                 ElanUtils.getInterfaceMacEntriesIdentifierOperationalDataPath(interfaceName, physAddress));
1578         interfaceTx.delete(LogicalDatastoreType.OPERATIONAL,
1579                 ElanUtils.getMacEntryOperationalDataPath(elanName, physAddress));
1580     }
1581
1582     public String getExternalElanInterface(String elanInstanceName, BigInteger dpnId) {
1583         DpnInterfaces dpnInterfaces = getElanInterfaceInfoByElanDpn(elanInstanceName, dpnId);
1584         if (dpnInterfaces == null || dpnInterfaces.getInterfaces() == null) {
1585             LOG.trace("Elan {} does not have interfaces in DPN {}", elanInstanceName, dpnId);
1586             return null;
1587         }
1588
1589         for (String dpnInterface : dpnInterfaces.getInterfaces()) {
1590             if (interfaceManager.isExternalInterface(dpnInterface)) {
1591                 return dpnInterface;
1592             }
1593         }
1594
1595         LOG.trace("Elan {} does not have any external interace attached to DPN {}", elanInstanceName, dpnId);
1596         return null;
1597     }
1598
1599     public static String getElanMacDPNKey(long elanTag, String macAddress, BigInteger dpnId) {
1600         String elanMacDmacDpnKey = "MAC-" + macAddress + " ELAN_TAG-" + elanTag + "DPN_ID-" + dpnId;
1601         return elanMacDmacDpnKey.intern();
1602     }
1603
1604     public static String getElanMacKey(long elanTag, String macAddress) {
1605         String elanMacKey = "MAC-" + macAddress + " ELAN_TAG-" + elanTag;
1606         return elanMacKey.intern();
1607     }
1608
1609     // TODO This should return a collection of futures
1610     public static void addToListenableFutureIfTxException(RuntimeException exception,
1611             List<ListenableFuture<Void>> futures) {
1612         Throwable cause = exception.getCause();
1613         if (cause != null && cause instanceof TransactionCommitFailedException) {
1614             futures.add(Futures.immediateFailedCheckedFuture((TransactionCommitFailedException) cause));
1615         }
1616     }
1617
1618     public static List<PhysAddress> getPhysAddress(List<String> macAddress) {
1619         Preconditions.checkNotNull(macAddress, "macAddress cannot be null");
1620         List<PhysAddress> physAddresses = new ArrayList<>();
1621         for (String mac : macAddress) {
1622             physAddresses.add(new PhysAddress(mac));
1623         }
1624         return physAddresses;
1625     }
1626
1627     public static List<StaticMacEntries> getStaticMacEntries(List<String> staticMacAddresses) {
1628         if (isEmpty(staticMacAddresses)) {
1629             return Collections.EMPTY_LIST;
1630         }
1631         StaticMacEntriesBuilder staticMacEntriesBuilder = new StaticMacEntriesBuilder();
1632         List<StaticMacEntries> staticMacEntries = new ArrayList<>();
1633         List<PhysAddress> physAddressList = getPhysAddress(staticMacAddresses);
1634         for (PhysAddress physAddress : physAddressList) {
1635             staticMacEntries.add(staticMacEntriesBuilder.setMacAddress(physAddress).build());
1636         }
1637         return staticMacEntries;
1638     }
1639
1640     public static InstanceIdentifier<StaticMacEntries> getStaticMacEntriesCfgDataPathIdentifier(String interfaceName,
1641                                                                                                 String macAddress) {
1642         return InstanceIdentifier.builder(ElanInterfaces.class)
1643                 .child(ElanInterface.class, new ElanInterfaceKey(interfaceName)).child(StaticMacEntries.class,
1644                         new StaticMacEntriesKey(new PhysAddress(macAddress))).build();
1645     }
1646
1647     public static List<StaticMacEntries> getDeletedEntries(List<StaticMacEntries> originalStaticMacEntries,
1648                                                            List<StaticMacEntries> updatedStaticMacEntries) {
1649         if (isEmpty(originalStaticMacEntries)) {
1650             return Collections.EMPTY_LIST;
1651         }
1652         List<StaticMacEntries> deleted = Lists.newArrayList(originalStaticMacEntries);
1653         if (isNotEmpty(updatedStaticMacEntries)) {
1654             deleted.removeAll(updatedStaticMacEntries);
1655         }
1656         return deleted;
1657     }
1658
1659     public static <T> List<T> diffOf(List<T> orig, List<T> updated) {
1660         if (isEmpty(orig)) {
1661             return Collections.EMPTY_LIST;
1662         }
1663         List<T> diff = Lists.newArrayList(orig);
1664         if (isNotEmpty(updated)) {
1665             diff.removeAll(updated);
1666         }
1667         return diff;
1668     }
1669
1670     public static void segregateToBeDeletedAndAddEntries(List<StaticMacEntries> originalStaticMacEntries,
1671                                                              List<StaticMacEntries> updatedStaticMacEntries) {
1672         if (isNotEmpty(updatedStaticMacEntries)) {
1673             List<StaticMacEntries> existingClonedStaticMacEntries = new ArrayList<>();
1674             if (isNotEmpty(originalStaticMacEntries)) {
1675                 existingClonedStaticMacEntries.addAll(0, originalStaticMacEntries);
1676                 originalStaticMacEntries.removeAll(updatedStaticMacEntries);
1677                 updatedStaticMacEntries.removeAll(existingClonedStaticMacEntries);
1678             }
1679         }
1680     }
1681
1682     public static boolean isEmpty(Collection collection) {
1683         return collection == null || collection.isEmpty();
1684     }
1685
1686     public static boolean isNotEmpty(Collection collection) {
1687         return !isEmpty(collection);
1688     }
1689
1690     public static void setElanInstancToDpnsCache(Map<String, Set<DpnInterfaces>> elanInstancToDpnsCache) {
1691         ElanUtils.elanInstancToDpnsCache = elanInstancToDpnsCache;
1692     }
1693
1694     public static Set<DpnInterfaces> getElanInvolvedDPNsFromCache(String elanName) {
1695         return elanInstancToDpnsCache.get(elanName);
1696     }
1697
1698     public static void addDPNInterfaceToElanInCache(String elanName, DpnInterfaces dpnInterfaces) {
1699         elanInstancToDpnsCache.computeIfAbsent(elanName, key -> new HashSet<>()).add(dpnInterfaces);
1700     }
1701
1702     public static void removeDPNInterfaceFromElanInCache(String elanName, DpnInterfaces dpnInterfaces) {
1703         elanInstancToDpnsCache.computeIfAbsent(elanName, key -> new HashSet<>()).remove(dpnInterfaces);
1704     }
1705
1706     public Optional<IpAddress> getSourceIpAddress(Ethernet ethernet) {
1707         Optional<IpAddress> srcIpAddress = Optional.absent();
1708         if (ethernet.getPayload() == null) {
1709             return srcIpAddress;
1710         }
1711         byte[] ipAddrBytes = null;
1712         if (ethernet.getPayload() instanceof IPv4) {
1713             IPv4 ipv4 = (IPv4) ethernet.getPayload();
1714             ipAddrBytes = Ints.toByteArray(ipv4.getSourceAddress());
1715         } else if (ethernet.getPayload() instanceof ARP) {
1716             ipAddrBytes = ((ARP) ethernet.getPayload()).getSenderProtocolAddress();
1717         }
1718         if (ipAddrBytes != null) {
1719             String ipAddr = NWUtil.toStringIpAddress(ipAddrBytes);
1720             return Optional.of(IpAddressBuilder.getDefaultInstance(ipAddr));
1721         }
1722         return srcIpAddress;
1723     }
1724
1725     public List<MacEntry> getElanMacEntries(String elanName) {
1726         MacTable macTable = getElanMacTable(elanName);
1727         if (macTable == null) {
1728             return Collections.emptyList();
1729         }
1730         return macTable.getMacEntry();
1731     }
1732
1733     public boolean isTunnelInLogicalGroup(String interfaceName) {
1734         org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1735             .ietf.interfaces.rev140508.interfaces.Interface configIface =
1736             interfaceManager.getInterfaceInfoFromConfigDataStore(interfaceName);
1737         IfTunnel ifTunnel = configIface.getAugmentation(IfTunnel.class);
1738         if (ifTunnel != null && ifTunnel.getTunnelInterfaceType().isAssignableFrom(TunnelTypeVxlan.class)) {
1739             ParentRefs refs = configIface.getAugmentation(ParentRefs.class);
1740             if (refs != null && !Strings.isNullOrEmpty(refs.getParentInterface())) {
1741                 return true; //multiple VxLAN tunnels enabled, i.e. only logical tunnel should be treated
1742             }
1743         }
1744         return false;
1745     }
1746
1747     public static void addElanInterfaceToElanInstanceCache(String elanInstanceName, String elanInterfaceName) {
1748         elanInstanceToInterfacesCache.computeIfAbsent(elanInstanceName, key -> new HashSet<>()).add(elanInterfaceName);
1749     }
1750
1751     public static void removeElanInterfaceToElanInstanceCache(String elanInstanceName, String interfaceName) {
1752         Set<String> elanInterfaces = elanInstanceToInterfacesCache.get(elanInstanceName);
1753         if (elanInterfaces == null || elanInterfaces.isEmpty()) {
1754             return;
1755         }
1756         elanInterfaces.remove(interfaceName);
1757     }
1758
1759     @Nonnull public static Set<String> removeAndGetElanInterfaces(String elanInstanceName) {
1760         Set<String> removed = elanInstanceToInterfacesCache.remove(elanInstanceName);
1761         return removed != null ? removed : Collections.emptySet();
1762     }
1763
1764     public static InstanceIdentifier<Flow> getFlowIid(Flow flow, BigInteger dpnId) {
1765         FlowKey flowKey = new FlowKey(new FlowId(flow.getId()));
1766         org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId nodeId =
1767                 new org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId("openflow:" + dpnId);
1768         org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node nodeDpn =
1769                 new NodeBuilder().setId(nodeId).setKey(new NodeKey(nodeId)).build();
1770         return InstanceIdentifier.builder(Nodes.class)
1771                 .child(org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node.class,
1772                         nodeDpn.getKey()).augmentation(FlowCapableNode.class)
1773                 .child(Table.class, new TableKey(flow.getTableId())).child(Flow.class, flowKey).build();
1774     }
1775
1776     public static String getElanInterfaceJobKey(String interfaceName) {
1777         return "elaninterface-" + interfaceName;
1778     }
1779
1780     public void addArpResponderFlow(BigInteger dpnId, String ingressInterfaceName, String ipAddress, String macAddress,
1781             int lportTag, List<Instruction> instructions) {
1782         LOG.info("Installing the ARP responder flow on DPN {} for Interface {} with MAC {} & IP {}", dpnId,
1783                 ingressInterfaceName, macAddress, ipAddress);
1784         ElanInterface elanIface = getElanInterfaceByElanInterfaceName(broker, ingressInterfaceName);
1785         ElanInstance elanInstance = getElanInstanceByName(broker, elanIface.getElanInstanceName());
1786         if (elanInstance == null) {
1787             LOG.debug("addArpResponderFlow: elanInstance is null, Failed to install arp responder flow for Interface {}"
1788                       + " with MAC {} & IP {}", dpnId,
1789                 ingressInterfaceName, macAddress, ipAddress);
1790             return;
1791         }
1792         String flowId = ArpResponderUtil.getFlowId(lportTag, ipAddress);
1793         ArpResponderUtil.installFlow(mdsalManager, dpnId, flowId, flowId, NwConstants.DEFAULT_ARP_FLOW_PRIORITY,
1794                 ArpResponderUtil.generateCookie(lportTag, ipAddress),
1795                 ArpResponderUtil.getMatchCriteria(lportTag, elanInstance, ipAddress), instructions);
1796         LOG.info("Installed the ARP Responder flow for Interface {}", ingressInterfaceName);
1797     }
1798
1799     public void addExternalTunnelArpResponderFlow(BigInteger dpnId, String ipAddress, String macAddress,
1800                         int lportTag, List<Instruction> instructions, String elanInstanceName) {
1801         LOG.trace("Installing the ExternalTunnel ARP responder flow on DPN {} for ElanInstance {} with MAC {} & IP {}",
1802                 dpnId, elanInstanceName, macAddress, ipAddress);
1803         ElanInstance elanInstance = getElanInstanceByName(broker, elanInstanceName);
1804         String flowId = ArpResponderUtil.getFlowId(lportTag, ipAddress);
1805         ArpResponderUtil.installFlow(mdsalManager, dpnId, flowId, flowId, NwConstants.DEFAULT_ARP_FLOW_PRIORITY,
1806                 ArpResponderUtil.generateCookie(lportTag, ipAddress),
1807                 ArpResponderUtil.getMatchCriteria(lportTag, elanInstance, ipAddress), instructions);
1808         LOG.trace("Installed the ExternalTunnel ARP Responder flow for ElanInstance {}", elanInstanceName);
1809     }
1810
1811     public void removeArpResponderFlow(BigInteger dpnId, String ingressInterfaceName, String ipAddress,
1812             int lportTag) {
1813         LOG.info("Removing the ARP responder flow on DPN {} of Interface {} with IP {}", dpnId, ingressInterfaceName,
1814                 ipAddress);
1815         ArpResponderUtil.removeFlow(mdsalManager, dpnId, ArpResponderUtil.getFlowId(lportTag, ipAddress));
1816     }
1817 }
1818
1819