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