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