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