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