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