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