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