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