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