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