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