Use named constants in ElanUtils
[netvirt.git] / vpnservice / elanmanager / 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
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.inject.Inject;
32 import javax.inject.Singleton;
33 import org.apache.commons.lang3.StringUtils;
34 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
35 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
36 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
37 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipService;
38 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
39 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
40 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
41 import org.opendaylight.genius.interfacemanager.globals.InterfaceInfo;
42 import org.opendaylight.genius.interfacemanager.globals.InterfaceServiceUtil;
43 import org.opendaylight.genius.interfacemanager.interfaces.IInterfaceManager;
44 import org.opendaylight.genius.itm.globals.ITMConstants;
45 import org.opendaylight.genius.mdsalutil.ActionInfo;
46 import org.opendaylight.genius.mdsalutil.FlowEntity;
47 import org.opendaylight.genius.mdsalutil.FlowEntityBuilder;
48 import org.opendaylight.genius.mdsalutil.InstructionInfo;
49 import org.opendaylight.genius.mdsalutil.MDSALUtil;
50 import org.opendaylight.genius.mdsalutil.MDSALUtil.MdsalOp;
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.genius.utils.ServiceIndex;
67 import org.opendaylight.netvirt.elan.ElanException;
68 import org.opendaylight.netvirt.elan.internal.ElanInstanceManager;
69 import org.opendaylight.netvirt.elan.internal.ElanInterfaceManager;
70 import org.opendaylight.netvirt.elan.l2gw.utils.ElanL2GatewayMulticastUtils;
71 import org.opendaylight.netvirt.elan.l2gw.utils.ElanL2GatewayUtils;
72 import org.opendaylight.netvirt.elan.l2gw.utils.L2GatewayConnectionUtils;
73 import org.opendaylight.netvirt.elanmanager.api.ElanHelper;
74 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
75 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddressBuilder;
76 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.InterfacesState;
77 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface;
78 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface.AdminStatus;
79 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface.OperStatus;
80 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress;
81 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.PhysAddress;
82 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action;
83 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId;
84 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
85 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowBuilder;
86 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.Instruction;
87 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdInput;
88 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdInputBuilder;
89 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdOutput;
90 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.IdManagerService;
91 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.ReleaseIdInput;
92 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.ReleaseIdInputBuilder;
93 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406.IfIndexesInterfaceMap;
94 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406._if.indexes._interface.map.IfIndexInterface;
95 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406._if.indexes._interface.map.IfIndexInterfaceKey;
96 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.IfTunnel;
97 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.ParentRefs;
98 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelTypeBase;
99 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelTypeVxlan;
100 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetDpidFromInterfaceInputBuilder;
101 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetDpidFromInterfaceOutput;
102 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetEgressActionsForInterfaceInput;
103 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetEgressActionsForInterfaceInputBuilder;
104 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetEgressActionsForInterfaceOutput;
105 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.OdlInterfaceRpcService;
106 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceBindings;
107 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceModeIngress;
108 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceTypeFlowBased;
109 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.StypeOpenflow;
110 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.StypeOpenflowBuilder;
111 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.ServicesInfo;
112 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.ServicesInfoKey;
113 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.services.info.BoundServices;
114 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.services.info.BoundServicesBuilder;
115 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.services.info.BoundServicesKey;
116 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.ExternalTunnelList;
117 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.external.tunnel.list.ExternalTunnel;
118 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.external.tunnel.list.ExternalTunnelKey;
119 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.GetExternalTunnelInterfaceNameInput;
120 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.GetExternalTunnelInterfaceNameInputBuilder;
121 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.GetExternalTunnelInterfaceNameOutput;
122 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.GetTunnelInterfaceNameInput;
123 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.GetTunnelInterfaceNameInputBuilder;
124 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.GetTunnelInterfaceNameOutput;
125 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.ItmRpcService;
126 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.RemoveTerminatingServiceActionsInput;
127 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.RemoveTerminatingServiceActionsInputBuilder;
128 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
129 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
130 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
131 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
132 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.config.rev150710.ElanConfig;
133 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInstance;
134 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInstanceBuilder;
135 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInterface;
136 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInterface.EtreeInterfaceType;
137 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeLeafTag;
138 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeLeafTagName;
139 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeLeafTagNameBuilder;
140 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanDpnInterfaces;
141 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanForwardingTables;
142 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInstances;
143 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInterfaceForwardingEntries;
144 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInterfaces;
145 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanState;
146 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanTagNameMap;
147 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.SegmentTypeFlat;
148 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.SegmentTypeVlan;
149 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.SegmentTypeVxlan;
150 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan._interface.forwarding.entries.ElanInterfaceMac;
151 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan._interface.forwarding.entries.ElanInterfaceMacKey;
152 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.ElanDpnInterfacesList;
153 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.ElanDpnInterfacesListKey;
154 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.elan.dpn.interfaces.list.DpnInterfaces;
155 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.elan.dpn.interfaces.list.DpnInterfacesKey;
156 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.forwarding.tables.MacTable;
157 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.forwarding.tables.MacTableBuilder;
158 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.forwarding.tables.MacTableKey;
159 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.ElanInstance;
160 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.ElanInstanceBuilder;
161 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.elan.instance.ElanSegments;
162 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.ElanInterface;
163 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.ElanInterfaceKey;
164 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.elan._interface.StaticMacEntries;
165 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.elan._interface.StaticMacEntriesBuilder;
166 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.elan._interface.StaticMacEntriesKey;
167 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.state.Elan;
168 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.state.ElanBuilder;
169 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.state.ElanKey;
170 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.tag.name.map.ElanTagName;
171 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.tag.name.map.ElanTagNameBuilder;
172 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.tag.name.map.ElanTagNameKey;
173 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.forwarding.entries.MacEntry;
174 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.forwarding.entries.MacEntryBuilder;
175 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.forwarding.entries.MacEntryKey;
176 import org.opendaylight.yangtools.yang.binding.DataObject;
177 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
178 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.InstanceIdentifierBuilder;
179 import org.opendaylight.yangtools.yang.common.RpcResult;
180 import org.slf4j.Logger;
181 import org.slf4j.LoggerFactory;
182
183 @Singleton
184 public class ElanUtils {
185
186     private static final Logger LOG = LoggerFactory.getLogger(ElanUtils.class);
187
188     private static final boolean SH_FLAG_SET = true;
189     private static final boolean SH_FLAG_UNSET = false;
190
191     private static Map<String, ElanInstance> elanInstanceLocalCache = new ConcurrentHashMap<>();
192     private static Map<String, ElanInterface> elanInterfaceLocalCache = new ConcurrentHashMap<>();
193     private static Map<String, Set<DpnInterfaces>> elanInstancToDpnsCache = new ConcurrentHashMap<>();
194     private static Map<String, Set<String>> elanInstanceToInterfacesCache = new ConcurrentHashMap<>();
195
196     private final DataBroker broker;
197     private final IMdsalApiManager mdsalManager;
198     private final ElanInstanceManager elanInstanceManager;
199     private final OdlInterfaceRpcService interfaceManagerRpcService;
200     private final ItmRpcService itmRpcService;
201     private final ElanL2GatewayUtils elanL2GatewayUtils;
202     private final ElanL2GatewayMulticastUtils elanL2GatewayMulticastUtils;
203     private final L2GatewayConnectionUtils l2GatewayConnectionUtils;
204     private final IInterfaceManager interfaceManager;
205     private final ElanConfig elanConfig;
206
207     public static final FutureCallback<Void> DEFAULT_CALLBACK = new FutureCallback<Void>() {
208         @Override
209         public void onSuccess(Void result) {
210             LOG.debug("Success in Datastore operation");
211         }
212
213         @Override
214         public void onFailure(Throwable error) {
215             LOG.error("Error in Datastore operation", error);
216         }
217     };
218
219     @Inject
220     public ElanUtils(DataBroker dataBroker, IMdsalApiManager mdsalManager, ElanInstanceManager elanInstanceManager,
221                      OdlInterfaceRpcService interfaceManagerRpcService, ItmRpcService itmRpcService,
222                      ElanInterfaceManager elanInterfaceManager, ElanConfig elanConfig,
223                      EntityOwnershipService entityOwnershipService, IInterfaceManager interfaceManager) {
224         this.broker = dataBroker;
225         this.mdsalManager = mdsalManager;
226         this.elanInstanceManager = elanInstanceManager;
227         this.interfaceManagerRpcService = interfaceManagerRpcService;
228         this.itmRpcService = itmRpcService;
229         this.interfaceManager = interfaceManager;
230         this.elanConfig = elanConfig;
231
232         elanL2GatewayMulticastUtils =
233                 new ElanL2GatewayMulticastUtils(broker, elanInstanceManager, elanInterfaceManager, this);
234         elanL2GatewayUtils = new ElanL2GatewayUtils(broker, itmRpcService, this,
235                 entityOwnershipService, elanL2GatewayMulticastUtils);
236         elanL2GatewayMulticastUtils.setEElanL2GatewayUtils(elanL2GatewayUtils);
237         l2GatewayConnectionUtils = new L2GatewayConnectionUtils(broker,
238                 elanInstanceManager, entityOwnershipService, this);
239     }
240
241     public void close() {
242         elanL2GatewayUtils.close();
243     }
244
245     public ElanL2GatewayUtils getElanL2GatewayUtils() {
246         return elanL2GatewayUtils;
247     }
248
249     public ElanL2GatewayMulticastUtils getElanL2GatewayMulticastUtils() {
250         return elanL2GatewayMulticastUtils;
251     }
252
253     public L2GatewayConnectionUtils getL2GatewayConnectionUtils() {
254         return l2GatewayConnectionUtils;
255     }
256
257     public final Boolean isOpenStackVniSemanticsEnforced() {
258         return elanConfig.isOpenstackVniSemanticsEnforced();
259     }
260
261     public static void addElanInstanceIntoCache(String elanInstanceName, ElanInstance elanInstance) {
262         elanInstanceLocalCache.put(elanInstanceName, elanInstance);
263     }
264
265     public static void removeElanInstanceFromCache(String elanInstanceName) {
266         elanInstanceLocalCache.remove(elanInstanceName);
267     }
268
269     public static ElanInstance getElanInstanceFromCache(String elanInstanceName) {
270         return elanInstanceLocalCache.get(elanInstanceName);
271     }
272
273     public static Set<String> getAllElanNames() {
274         return elanInstanceLocalCache.keySet();
275     }
276
277     public static void addElanInterfaceIntoCache(String interfaceName, ElanInterface elanInterface) {
278         elanInterfaceLocalCache.put(interfaceName, elanInterface);
279     }
280
281     public static void removeElanInterfaceFromCache(String interfaceName) {
282         elanInterfaceLocalCache.remove(interfaceName);
283     }
284
285     public static ElanInterface getElanInterfaceFromCache(String interfaceName) {
286         return elanInterfaceLocalCache.get(interfaceName);
287     }
288
289     /**
290      * Uses the IdManager to retrieve a brand new ElanTag.
291      *
292      * @param idManager
293      *            the id manager
294      * @param idKey
295      *            the id key
296      * @return the integer
297      */
298     public static Long retrieveNewElanTag(IdManagerService idManager, String idKey) {
299
300         AllocateIdInput getIdInput = new AllocateIdInputBuilder().setPoolName(ElanConstants.ELAN_ID_POOL_NAME)
301                 .setIdKey(idKey).build();
302
303         try {
304             Future<RpcResult<AllocateIdOutput>> result = idManager.allocateId(getIdInput);
305             RpcResult<AllocateIdOutput> rpcResult = result.get();
306             if (rpcResult.isSuccessful()) {
307                 return rpcResult.getResult().getIdValue();
308             } else {
309                 LOG.warn("RPC Call to Allocate Id returned with Errors {}", rpcResult.getErrors());
310             }
311         } catch (InterruptedException | ExecutionException e) {
312             LOG.warn("Exception when Allocating Id", e);
313         }
314         return 0L;
315     }
316
317     public static void releaseId(IdManagerService idManager, String poolName, String idKey) {
318         ReleaseIdInput releaseIdInput = new ReleaseIdInputBuilder().setPoolName(poolName).setIdKey(idKey).build();
319         idManager.releaseId(releaseIdInput);
320     }
321
322     /**
323      * Read utility.
324      *
325      * @deprecated Consider using {@link #read2(LogicalDatastoreType, InstanceIdentifier)} with proper exception
326      *             handling instead
327      */
328     @Deprecated
329     @SuppressWarnings("checkstyle:IllegalCatch")
330     public <T extends DataObject> Optional<T> read(DataBroker broker, LogicalDatastoreType datastoreType,
331             InstanceIdentifier<T> path) {
332         try (ReadOnlyTransaction tx = broker != null ? broker.newReadOnlyTransaction()
333                 : this.broker.newReadOnlyTransaction()) {
334             return tx.read(datastoreType, path).get();
335         } catch (Exception e) {
336             throw new RuntimeException(e);
337         }
338     }
339
340     public <T extends DataObject> Optional<T> read2(LogicalDatastoreType datastoreType, InstanceIdentifier<T> path)
341             throws ReadFailedException {
342         try (ReadOnlyTransaction tx = broker.newReadOnlyTransaction()) {
343             CheckedFuture<Optional<T>, ReadFailedException> checkedFuture = tx.read(datastoreType, path);
344             return checkedFuture.checkedGet();
345         }
346     }
347
348     public static <T extends DataObject> void delete(DataBroker broker, LogicalDatastoreType datastoreType,
349             InstanceIdentifier<T> path) {
350         WriteTransaction tx = broker.newWriteOnlyTransaction();
351         tx.delete(datastoreType, path);
352         Futures.addCallback(tx.submit(), DEFAULT_CALLBACK);
353     }
354
355     public static <T extends DataObject> void delete(DataBroker broker, LogicalDatastoreType datastoreType,
356             InstanceIdentifier<T> path, FutureCallback<Void> callback) {
357         WriteTransaction tx = broker.newWriteOnlyTransaction();
358         tx.delete(datastoreType, path);
359         Futures.addCallback(tx.submit(), callback);
360     }
361
362     public static InstanceIdentifier<ElanInstance> getElanInstanceIdentifier() {
363         return InstanceIdentifier.builder(ElanInstances.class).child(ElanInstance.class).build();
364     }
365
366     // elan-instances config container
367     public static ElanInstance getElanInstanceByName(DataBroker broker, String elanInstanceName) {
368         ElanInstance elanObj = getElanInstanceFromCache(elanInstanceName);
369         if (elanObj != null) {
370             return elanObj;
371         }
372         InstanceIdentifier<ElanInstance> elanIdentifierId =
373                 ElanHelper.getElanInstanceConfigurationDataPath(elanInstanceName);
374         return MDSALUtil.read(broker, LogicalDatastoreType.CONFIGURATION, elanIdentifierId).orNull();
375     }
376
377     // elan-interfaces Config Container
378     public static ElanInterface getElanInterfaceByElanInterfaceName(DataBroker broker, String elanInterfaceName) {
379         ElanInterface elanInterfaceObj = getElanInterfaceFromCache(elanInterfaceName);
380         if (elanInterfaceObj != null) {
381             return elanInterfaceObj;
382         }
383         InstanceIdentifier<ElanInterface> elanInterfaceId = getElanInterfaceConfigurationDataPathId(elanInterfaceName);
384         return MDSALUtil.read(broker, LogicalDatastoreType.CONFIGURATION, elanInterfaceId).orNull();
385     }
386
387     public static EtreeInterface getEtreeInterfaceByElanInterfaceName(DataBroker broker, String elanInterfaceName) {
388         ElanInterface elanInterface = getElanInterfaceByElanInterfaceName(broker, elanInterfaceName);
389         if (elanInterface == null) {
390             return null;
391         } else {
392             return elanInterface.getAugmentation(EtreeInterface.class);
393         }
394     }
395
396     public static InstanceIdentifier<ElanInterface> getElanInterfaceConfigurationDataPathId(String interfaceName) {
397         return InstanceIdentifier.builder(ElanInterfaces.class)
398                 .child(ElanInterface.class, new ElanInterfaceKey(interfaceName)).build();
399     }
400
401     // elan-state Operational container
402     public static Elan getElanByName(DataBroker broker, String elanInstanceName) {
403         InstanceIdentifier<Elan> elanIdentifier = getElanInstanceOperationalDataPath(elanInstanceName);
404         return MDSALUtil.read(broker, LogicalDatastoreType.OPERATIONAL, elanIdentifier).orNull();
405     }
406
407     public static InstanceIdentifier<Elan> getElanInstanceOperationalDataPath(String elanInstanceName) {
408         return InstanceIdentifier.builder(ElanState.class).child(Elan.class, new ElanKey(elanInstanceName)).build();
409     }
410
411     // grouping of forwarding-entries
412     public MacEntry getInterfaceMacEntriesOperationalDataPath(String interfaceName, PhysAddress physAddress) {
413         InstanceIdentifier<MacEntry> existingMacEntryId = getInterfaceMacEntriesIdentifierOperationalDataPath(
414                 interfaceName, physAddress);
415         return read(broker, LogicalDatastoreType.OPERATIONAL, existingMacEntryId).orNull();
416     }
417
418     public MacEntry getInterfaceMacEntriesOperationalDataPathFromId(InstanceIdentifier identifier) {
419         Optional<MacEntry> existingInterfaceMacEntry = read(broker,
420                 LogicalDatastoreType.OPERATIONAL, identifier);
421         return existingInterfaceMacEntry.orNull();
422     }
423
424     public static InstanceIdentifier<MacEntry> getInterfaceMacEntriesIdentifierOperationalDataPath(String interfaceName,
425             PhysAddress physAddress) {
426         return InstanceIdentifier.builder(ElanInterfaceForwardingEntries.class)
427                 .child(ElanInterfaceMac.class, new ElanInterfaceMacKey(interfaceName))
428                 .child(MacEntry.class, new MacEntryKey(physAddress)).build();
429
430     }
431
432     // elan-forwarding-tables Operational container
433     public Optional<MacEntry> getMacEntryForElanInstance(String elanName, PhysAddress physAddress) {
434         InstanceIdentifier<MacEntry> macId = getMacEntryOperationalDataPath(elanName, physAddress);
435         return read(broker, LogicalDatastoreType.OPERATIONAL, macId);
436     }
437
438     public MacEntry getMacEntryFromElanMacId(InstanceIdentifier identifier) {
439         Optional<MacEntry> existingInterfaceMacEntry = read(broker,
440                 LogicalDatastoreType.OPERATIONAL, identifier);
441         return existingInterfaceMacEntry.orNull();
442     }
443
444     public static InstanceIdentifier<MacEntry> getMacEntryOperationalDataPath(String elanName,
445             PhysAddress physAddress) {
446         return InstanceIdentifier.builder(ElanForwardingTables.class).child(MacTable.class, new MacTableKey(elanName))
447                 .child(MacEntry.class, new MacEntryKey(physAddress)).build();
448     }
449
450     public static InstanceIdentifier<MacTable> getElanMacTableOperationalDataPath(String elanName) {
451         return InstanceIdentifier.builder(ElanForwardingTables.class).child(MacTable.class, new MacTableKey(elanName))
452                 .build();
453     }
454
455     // elan-interface-forwarding-entries Operational container
456     public ElanInterfaceMac getElanInterfaceMacByInterfaceName(String interfaceName) {
457         InstanceIdentifier<ElanInterfaceMac> elanInterfaceId = getElanInterfaceMacEntriesOperationalDataPath(
458                 interfaceName);
459         return read(broker, LogicalDatastoreType.OPERATIONAL, elanInterfaceId).orNull();
460     }
461
462     /**
463      * Gets the elan interface mac addresses.
464      *
465      * @param interfaceName
466      *            the interface name
467      * @return the elan interface mac addresses
468      */
469     public List<PhysAddress> getElanInterfaceMacAddresses(String interfaceName) {
470         List<PhysAddress> macAddresses = new ArrayList<>();
471         ElanInterfaceMac elanInterfaceMac = getElanInterfaceMacByInterfaceName(interfaceName);
472         if (elanInterfaceMac != null && elanInterfaceMac.getMacEntry() != null) {
473             List<MacEntry> macEntries = elanInterfaceMac.getMacEntry();
474             for (MacEntry macEntry : macEntries) {
475                 macAddresses.add(macEntry.getMacAddress());
476             }
477         }
478         return macAddresses;
479     }
480
481     public static InstanceIdentifier<ElanInterfaceMac> getElanInterfaceMacEntriesOperationalDataPath(
482             String interfaceName) {
483         return InstanceIdentifier.builder(ElanInterfaceForwardingEntries.class)
484                 .child(ElanInterfaceMac.class, new ElanInterfaceMacKey(interfaceName)).build();
485     }
486
487     /**
488      * Returns the list of Interfaces that belong to an Elan on an specific DPN.
489      * Data retrieved from Elan's operational DS: elan-dpn-interfaces container
490      *
491      * @param elanInstanceName
492      *            name of the Elan to which the interfaces must belong to
493      * @param dpId
494      *            Id of the DPN where the interfaces are located
495      * @return the elan interface Info
496      */
497     public DpnInterfaces getElanInterfaceInfoByElanDpn(String elanInstanceName, BigInteger dpId) {
498         InstanceIdentifier<DpnInterfaces> elanDpnInterfacesId = getElanDpnInterfaceOperationalDataPath(elanInstanceName,
499                 dpId);
500         return read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfacesId).orNull();
501     }
502
503     /**
504      * Returns the InstanceIdentifier that points to the Interfaces of an Elan
505      * in a given DPN in the Operational DS. Data retrieved from Elans's
506      * operational DS: dpn-interfaces list
507      *
508      * @param elanInstanceName
509      *            name of the Elan to which the interfaces must belong to
510      * @param dpId
511      *            Id of the DPN where the interfaces are located
512      * @return the elan dpn interface
513      */
514     public static InstanceIdentifier<DpnInterfaces> getElanDpnInterfaceOperationalDataPath(String elanInstanceName,
515             BigInteger dpId) {
516         return InstanceIdentifier.builder(ElanDpnInterfaces.class)
517                 .child(ElanDpnInterfacesList.class, new ElanDpnInterfacesListKey(elanInstanceName))
518                 .child(DpnInterfaces.class, new DpnInterfacesKey(dpId)).build();
519     }
520
521     // elan-tag-name-map Operational Container
522     public ElanTagName getElanInfoByElanTag(long elanTag) {
523         InstanceIdentifier<ElanTagName> elanId = getElanInfoEntriesOperationalDataPath(elanTag);
524         Optional<ElanTagName> existingElanInfo = read(broker,
525                 LogicalDatastoreType.OPERATIONAL, elanId);
526         return existingElanInfo.orNull();
527     }
528
529     public EtreeLeafTagName getEtreeLeafTagByElanTag(long elanTag) {
530         InstanceIdentifier<ElanTagName> elanId = getElanInfoEntriesOperationalDataPath(elanTag);
531         Optional<ElanTagName> existingElanInfo = read(broker,
532                 LogicalDatastoreType.OPERATIONAL, elanId);
533         if (existingElanInfo.isPresent()) {
534             ElanTagName elanTagName = existingElanInfo.get();
535             return elanTagName.getAugmentation(EtreeLeafTagName.class);
536         }
537         return null;
538     }
539
540     public static InstanceIdentifier<ElanTagName> getElanInfoEntriesOperationalDataPath(long elanTag) {
541         return InstanceIdentifier.builder(ElanTagNameMap.class).child(ElanTagName.class, new ElanTagNameKey(elanTag))
542                 .build();
543     }
544
545     // interface-index-tag operational container
546     public Optional<IfIndexInterface> getInterfaceInfoByInterfaceTag(long interfaceTag) {
547         InstanceIdentifier<IfIndexInterface> interfaceId = getInterfaceInfoEntriesOperationalDataPath(interfaceTag);
548         return read(broker, LogicalDatastoreType.OPERATIONAL, interfaceId);
549     }
550
551     public static InstanceIdentifier<IfIndexInterface> getInterfaceInfoEntriesOperationalDataPath(long interfaceTag) {
552         return InstanceIdentifier.builder(IfIndexesInterfaceMap.class)
553                 .child(IfIndexInterface.class, new IfIndexInterfaceKey((int) interfaceTag)).build();
554     }
555
556     public static InstanceIdentifier<ElanDpnInterfacesList> getElanDpnOperationDataPath(String elanInstanceName) {
557         return InstanceIdentifier.builder(ElanDpnInterfaces.class)
558                 .child(ElanDpnInterfacesList.class, new ElanDpnInterfacesListKey(elanInstanceName)).build();
559     }
560
561     public ElanDpnInterfacesList getElanDpnInterfacesList(String elanName) {
562         InstanceIdentifier<ElanDpnInterfacesList> elanDpnInterfaceId = getElanDpnOperationDataPath(elanName);
563         return read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId).orNull();
564     }
565
566     public ElanDpnInterfaces getElanDpnInterfacesList() {
567         InstanceIdentifier<ElanDpnInterfaces> elanDpnInterfaceId = InstanceIdentifier.builder(ElanDpnInterfaces.class)
568                 .build();
569         return read(broker, LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId).orNull();
570     }
571
572     /**
573      * This method is useful get all ELAN participating CSS dpIds to install
574      * program remote dmac entries and updating remote bc groups for tor
575      * integration.
576      *
577      * @param elanInstanceName
578      *            the elan instance name
579      * @return list of dpIds
580      */
581     public List<BigInteger> getParticipatingDpnsInElanInstance(String elanInstanceName) {
582         List<BigInteger> dpIds = new ArrayList<>();
583         InstanceIdentifier<ElanDpnInterfacesList> elanDpnInterfaceId = getElanDpnOperationDataPath(elanInstanceName);
584         Optional<ElanDpnInterfacesList> existingElanDpnInterfaces = read(broker,
585                 LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId);
586         if (!existingElanDpnInterfaces.isPresent()) {
587             return dpIds;
588         }
589         List<DpnInterfaces> dpnInterfaces = existingElanDpnInterfaces.get().getDpnInterfaces();
590         for (DpnInterfaces dpnInterface : dpnInterfaces) {
591             dpIds.add(dpnInterface.getDpId());
592         }
593         return dpIds;
594     }
595
596     /**
597      * To check given dpId is already present in Elan instance. This can be used
598      * to program flow entry in external tunnel table when a new access port
599      * added for first time into the ELAN instance
600      *
601      * @param dpId
602      *            the dp id
603      * @param elanInstanceName
604      *            the elan instance name
605      * @return true if dpId is already present, otherwise return false
606      */
607     public boolean isDpnAlreadyPresentInElanInstance(BigInteger dpId, String elanInstanceName) {
608         InstanceIdentifier<ElanDpnInterfacesList> elanDpnInterfaceId = getElanDpnOperationDataPath(elanInstanceName);
609         Optional<ElanDpnInterfacesList> existingElanDpnInterfaces = read(broker,
610                 LogicalDatastoreType.OPERATIONAL, elanDpnInterfaceId);
611         if (!existingElanDpnInterfaces.isPresent()) {
612             return false;
613         }
614         List<DpnInterfaces> dpnInterfaces = existingElanDpnInterfaces.get().getDpnInterfaces();
615         for (DpnInterfaces dpnInterface : dpnInterfaces) {
616             if (dpnInterface.getDpId().equals(dpId)) {
617                 return true;
618             }
619         }
620         return false;
621     }
622
623     public ElanForwardingTables getElanForwardingList() {
624         InstanceIdentifier<ElanForwardingTables> elanForwardingTableId = InstanceIdentifier
625                 .builder(ElanForwardingTables.class).build();
626         return read(broker, LogicalDatastoreType.OPERATIONAL, elanForwardingTableId).orNull();
627     }
628
629     public static long getElanRemoteBroadCastGroupID(long elanTag) {
630         return ElanConstants.ELAN_GID_MIN + elanTag % ElanConstants.ELAN_GID_MIN * 2;
631     }
632
633     /**
634      * Gets the elan mac table.
635      *
636      * @param elanName
637      *            the elan name
638      * @return the elan mac table
639      */
640     public MacTable getElanMacTable(String elanName) {
641         InstanceIdentifier<MacTable> elanMacTableId = getElanMacTableOperationalDataPath(elanName);
642         return read(broker, LogicalDatastoreType.OPERATIONAL, elanMacTableId).orNull();
643     }
644
645     public static long getElanLocalBCGId(long elanTag) {
646         return ElanConstants.ELAN_GID_MIN + (elanTag % ElanConstants.ELAN_GID_MIN * 2 - 1);
647     }
648
649     public static long getElanRemoteBCGId(long elanTag) {
650         return ElanConstants.ELAN_GID_MIN + elanTag % ElanConstants.ELAN_GID_MIN * 2;
651     }
652
653     public static long getEtreeLeafLocalBCGId(long etreeLeafTag) {
654         return ElanConstants.ELAN_GID_MIN + (etreeLeafTag % ElanConstants.ELAN_GID_MIN * 2 - 1);
655     }
656
657     public static long getEtreeLeafRemoteBCGId(long etreeLeafTag) {
658         return ElanConstants.ELAN_GID_MIN + etreeLeafTag % ElanConstants.ELAN_GID_MIN * 2;
659     }
660
661     public static BigInteger getElanMetadataLabel(long elanTag) {
662         return MetaDataUtil.getElanTagMetadata(elanTag);
663     }
664
665     public static BigInteger getElanMetadataLabel(long elanTag, boolean isSHFlagSet) {
666         int shBit = isSHFlagSet ? 1 : 0;
667         return BigInteger.valueOf(elanTag).shiftLeft(24).or(BigInteger.valueOf(shBit));
668     }
669
670     public static BigInteger getElanMetadataLabel(long elanTag, int lportTag) {
671         return getElanMetadataLabel(elanTag).or(MetaDataUtil.getLportTagMetaData(lportTag));
672     }
673
674     public static BigInteger getElanMetadataMask() {
675         return MetaDataUtil.METADATA_MASK_SERVICE.or(MetaDataUtil.METADATA_MASK_LPORT_TAG);
676     }
677
678     /**
679      * Setting SMAC, DMAC, UDMAC in this DPN and optionally in other DPNs.
680      *
681      * @param elanInfo
682      *            the elan info
683      * @param interfaceInfo
684      *            the interface info
685      * @param macTimeout
686      *            the mac timeout
687      * @param macAddress
688      *            the mac address
689      * @param configureRemoteFlows
690      *            true if remote dmac flows should be configured as well
691      * @param writeFlowGroupTx
692      *            the flow group tx
693      * @throws ElanException in case of issues creating the flow objects
694      */
695     public void setupMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo,
696                               long macTimeout, String macAddress, boolean configureRemoteFlows,
697                               WriteTransaction writeFlowGroupTx) throws ElanException {
698         synchronized (getElanMacDPNKey(elanInfo.getElanTag(), macAddress, interfaceInfo.getDpId())) {
699             setupKnownSmacFlow(elanInfo, interfaceInfo, macTimeout, macAddress, mdsalManager,
700                 writeFlowGroupTx);
701             setupOrigDmacFlows(elanInfo, interfaceInfo, macAddress, configureRemoteFlows, mdsalManager,
702                 broker, writeFlowGroupTx);
703         }
704     }
705
706     public void setupDMacFlowOnRemoteDpn(ElanInstance elanInfo, InterfaceInfo interfaceInfo, BigInteger dstDpId,
707                                          String macAddress, WriteTransaction writeFlowTx) throws ElanException {
708         String elanInstanceName = elanInfo.getElanInstanceName();
709         setupRemoteDmacFlow(dstDpId, interfaceInfo.getDpId(), interfaceInfo.getInterfaceTag(), elanInfo.getElanTag(),
710                 macAddress, elanInstanceName, writeFlowTx, interfaceInfo.getInterfaceName(), elanInfo);
711         LOG.info("Remote Dmac flow entry created for elan Name:{}, logical port Name:{} and"
712                 + " mac address {} on dpn:{}", elanInstanceName, interfaceInfo.getPortName(),
713                 macAddress, dstDpId);
714     }
715
716     /**
717      * Inserts a Flow in SMAC table to state that the MAC has already been
718      * learnt.
719      */
720     private void setupKnownSmacFlow(ElanInstance elanInfo, InterfaceInfo interfaceInfo, long macTimeout,
721             String macAddress, IMdsalApiManager mdsalApiManager, WriteTransaction writeFlowGroupTx) {
722         FlowEntity flowEntity = buildKnownSmacFlow(elanInfo, interfaceInfo, macTimeout, macAddress);
723         mdsalApiManager.addFlowToTx(flowEntity, writeFlowGroupTx);
724         LOG.debug("Known Smac flow entry created for elan Name:{}, logical Interface port:{} and mac address:{}",
725                 elanInfo.getElanInstanceName(), elanInfo.getDescription(), macAddress);
726     }
727
728     public FlowEntity buildKnownSmacFlow(ElanInstance elanInfo, InterfaceInfo interfaceInfo, long macTimeout,
729             String macAddress) {
730         int lportTag = interfaceInfo.getInterfaceTag();
731         // Matching metadata and eth_src fields
732         List<MatchInfo> mkMatches = new ArrayList<>();
733         mkMatches.add(new MatchMetadata(getElanMetadataLabel(elanInfo.getElanTag(), lportTag), getElanMetadataMask()));
734         mkMatches.add(new MatchEthernetSource(new MacAddress(macAddress)));
735         List<InstructionInfo> mkInstructions = new ArrayList<>();
736         mkInstructions.add(new InstructionGotoTable(NwConstants.ELAN_DMAC_TABLE));
737         BigInteger dpId = interfaceInfo.getDpId();
738         long elanTag = getElanTag(broker, elanInfo, interfaceInfo);
739         return new FlowEntityBuilder()
740             .setDpnId(dpId)
741             .setTableId(NwConstants.ELAN_SMAC_TABLE)
742             .setFlowId(getKnownDynamicmacFlowRef(NwConstants.ELAN_SMAC_TABLE, dpId, lportTag, macAddress, elanTag))
743             .setPriority(20)
744             .setFlowName(elanInfo.getDescription())
745             .setIdleTimeOut((int) macTimeout)
746             .setHardTimeOut(0)
747             .setCookie(ElanConstants.COOKIE_ELAN_KNOWN_SMAC.add(BigInteger.valueOf(elanTag)))
748             .setMatchInfoList(mkMatches)
749             .setInstructionInfoList(mkInstructions)
750             .setStrictFlag(true)
751             // If Mac timeout is 0, the flow won't be deleted automatically, so no need to get notified
752             .setSendFlowRemFlag(macTimeout != 0)
753             .build();
754     }
755
756     private static Long getElanTag(DataBroker broker, ElanInstance elanInfo, InterfaceInfo interfaceInfo) {
757         EtreeInterface etreeInterface = getEtreeInterfaceByElanInterfaceName(broker, interfaceInfo.getInterfaceName());
758         if (etreeInterface == null || etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
759             return elanInfo.getElanTag();
760         } else { // Leaf
761             EtreeInstance etreeInstance = elanInfo.getAugmentation(EtreeInstance.class);
762             if (etreeInstance == null) {
763                 LOG.warn("EtreeInterface {} is connected to a non-Etree network: {}",
764                          interfaceInfo.getInterfaceName(), elanInfo.getElanInstanceName());
765                 return elanInfo.getElanTag();
766             } else {
767                 return etreeInstance.getEtreeLeafTagVal().getValue();
768             }
769         }
770     }
771
772     /**
773      * Installs a Flow in INTERNAL_TUNNEL_TABLE of the affected DPN that sends
774      * the packet through the specified interface if the tunnel_id matches the
775      * interface's lportTag.
776      *
777      * @param interfaceInfo
778      *            the interface info
779      * @param mdsalApiManager
780      *            the mdsal API manager
781      * @param writeFlowGroupTx
782      *            the writeFLowGroup tx
783      */
784     public void setupTermDmacFlows(InterfaceInfo interfaceInfo, IMdsalApiManager mdsalApiManager,
785                                    WriteTransaction writeFlowGroupTx) {
786         BigInteger dpId = interfaceInfo.getDpId();
787         int lportTag = interfaceInfo.getInterfaceTag();
788         Flow flow = MDSALUtil.buildFlowNew(NwConstants.INTERNAL_TUNNEL_TABLE,
789                 getIntTunnelTableFlowRef(NwConstants.INTERNAL_TUNNEL_TABLE, lportTag), 5,
790                 String.format("%s:%d", "ITM Flow Entry ", lportTag), 0, 0,
791                 ITMConstants.COOKIE_ITM.add(BigInteger.valueOf(lportTag)),
792                 getTunnelIdMatchForFilterEqualsLPortTag(lportTag),
793                 getInstructionsInPortForOutGroup(interfaceInfo.getInterfaceName()));
794         mdsalApiManager.addFlowToTx(dpId, flow, writeFlowGroupTx);
795         LOG.debug("Terminating service table flow entry created on dpn:{} for logical Interface port:{}", dpId,
796                 interfaceInfo.getPortName());
797     }
798
799     /**
800      * Constructs the FlowName for flows installed in the Internal Tunnel Table,
801      * consisting in tableId + elanTag.
802      *
803      * @param tableId
804      *            table Id
805      * @param elanTag
806      *            elan Tag
807      * @return the Internal tunnel
808      */
809     public static String getIntTunnelTableFlowRef(short tableId, int elanTag) {
810         return new StringBuffer().append(tableId).append(elanTag).toString();
811     }
812
813     /**
814      * Constructs the Matches that checks that the tunnel_id field contains a
815      * specific lportTag.
816      *
817      * @param lportTag
818      *            lportTag that must be checked against the tunnel_id field
819      * @return the list of match Info
820      */
821     public static List<MatchInfo> getTunnelIdMatchForFilterEqualsLPortTag(int lportTag) {
822         List<MatchInfo> mkMatches = new ArrayList<>();
823         // Matching metadata
824         mkMatches.add(new MatchTunnelId(BigInteger.valueOf(lportTag)));
825         return mkMatches;
826     }
827
828     /**
829      * Constructs the Instructions that take the packet over a given interface.
830      *
831      * @param ifName
832      *            Name of the interface where the packet must be sent over. It
833      *            can be a local interface or a tunnel interface (internal or
834      *            external)
835      * @return the Instruction
836      */
837     public List<Instruction> getInstructionsInPortForOutGroup(String ifName) {
838         List<Instruction> mkInstructions = new ArrayList<>();
839         List<Action> actions = getEgressActionsForInterface(ifName, /* tunnelKey */ null);
840
841         mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
842         return mkInstructions;
843     }
844
845     /**
846      * Returns the list of Actions to be taken when sending the packet through
847      * an Elan interface. Note that this interface can refer to an ElanInterface
848      * where the Elan VM is attached to a DPN or an ITM tunnel interface where
849      * Elan traffic can be sent through. In this latter case, the tunnelKey is
850      * mandatory and it can hold serviceId for internal tunnels or the VNI for
851      * external tunnels.
852      *
853      * @param ifName
854      *            the if name
855      * @param tunnelKey
856      *            the tunnel key
857      * @return the egress actions for interface
858      */
859     @SuppressWarnings("checkstyle:IllegalCatch")
860     public List<Action> getEgressActionsForInterface(String ifName, Long tunnelKey) {
861         List<Action> listAction = new ArrayList<>();
862         try {
863             GetEgressActionsForInterfaceInput getEgressActionInput = new GetEgressActionsForInterfaceInputBuilder()
864                     .setIntfName(ifName).setTunnelKey(tunnelKey).build();
865             Future<RpcResult<GetEgressActionsForInterfaceOutput>> result = interfaceManagerRpcService
866                     .getEgressActionsForInterface(getEgressActionInput);
867             RpcResult<GetEgressActionsForInterfaceOutput> rpcResult = result.get();
868             if (!rpcResult.isSuccessful()) {
869                 LOG.warn("RPC Call to Get egress actions for interface {} returned with Errors {}", ifName,
870                         rpcResult.getErrors());
871             } else {
872                 List<Action> actions = rpcResult.getResult().getAction();
873                 listAction = actions;
874             }
875         } catch (Exception e) {
876             LOG.warn("Exception when egress actions for interface {}", ifName, e);
877         }
878         return listAction;
879     }
880
881     private void setupOrigDmacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
882                                     boolean configureRemoteFlows, IMdsalApiManager mdsalApiManager,
883                                     DataBroker broker, WriteTransaction writeFlowGroupTx)
884                                     throws ElanException {
885         BigInteger dpId = interfaceInfo.getDpId();
886         String ifName = interfaceInfo.getInterfaceName();
887         long ifTag = interfaceInfo.getInterfaceTag();
888         String elanInstanceName = elanInfo.getElanInstanceName();
889
890         Long elanTag = elanInfo.getElanTag();
891
892         setupLocalDmacFlow(elanTag, dpId, ifName, macAddress, elanInfo, mdsalApiManager, ifTag,
893                 writeFlowGroupTx);
894         LOG.debug("Dmac flow entry created for elan Name:{}, logical port Name:{} mand mac address:{} "
895                                     + "on dpn:{}", elanInstanceName, interfaceInfo.getPortName(), macAddress, dpId);
896
897         if (!configureRemoteFlows) {
898             return;
899         }
900
901         List<DpnInterfaces> elanDpns = getInvolvedDpnsInElan(elanInstanceName);
902         if (elanDpns == null) {
903             return;
904         }
905
906         for (DpnInterfaces elanDpn : elanDpns) {
907
908             if (elanDpn.getDpId().equals(dpId)) {
909                 continue;
910             }
911
912             // Check for the Remote DPN present in Inventory Manager
913             if (!isDpnPresent(elanDpn.getDpId())) {
914                 continue;
915             }
916
917             // For remote DPNs a flow is needed to indicate that packets of this ELAN going to this MAC need to be
918             // forwarded through the appropriate ITM tunnel
919             setupRemoteDmacFlow(elanDpn.getDpId(), // srcDpn (the remote DPN in this case)
920                     dpId, // dstDpn (the local DPN)
921                     interfaceInfo.getInterfaceTag(), // lportTag of the local interface
922                     elanTag,  // identifier of the Elan
923                     macAddress, // MAC to be programmed in remote DPN
924                     elanInstanceName, writeFlowGroupTx, ifName, elanInfo
925             );
926             LOG.debug("Remote Dmac flow entry created for elan Name:{}, logical port Name:{} and mac address:{} on"
927                         + " dpn:{}", elanInstanceName, interfaceInfo.getPortName(), macAddress, elanDpn.getDpId());
928         }
929
930         // TODO: Make sure that the same is performed against the ElanDevices.
931     }
932
933     @SuppressWarnings("unchecked")
934     public List<DpnInterfaces> getInvolvedDpnsInElan(String elanName) {
935         List<DpnInterfaces> dpns = elanInstanceManager.getElanDPNByName(elanName);
936         if (dpns == null) {
937             return Collections.emptyList();
938         }
939         return dpns;
940     }
941
942     private void setupLocalDmacFlow(long elanTag, BigInteger dpId, String ifName, String macAddress,
943             ElanInstance elanInfo, IMdsalApiManager mdsalApiManager, long ifTag, WriteTransaction writeFlowGroupTx) {
944         Flow flowEntity = buildLocalDmacFlowEntry(elanTag, dpId, ifName, macAddress, elanInfo, ifTag);
945         mdsalApiManager.addFlowToTx(dpId, flowEntity, writeFlowGroupTx);
946         installEtreeLocalDmacFlow(elanTag, dpId, ifName, macAddress, elanInfo,
947                 mdsalApiManager, ifTag, writeFlowGroupTx);
948     }
949
950     private void installEtreeLocalDmacFlow(long elanTag, BigInteger dpId, String ifName, String macAddress,
951             ElanInstance elanInfo, IMdsalApiManager mdsalApiManager, long ifTag, WriteTransaction writeFlowGroupTx) {
952         EtreeInterface etreeInterface = getEtreeInterfaceByElanInterfaceName(broker, ifName);
953         if (etreeInterface != null) {
954             if (etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
955                 EtreeLeafTagName etreeTagName = getEtreeLeafTagByElanTag(elanTag);
956                 if (etreeTagName == null) {
957                     LOG.warn("Interface {} seems like it belongs to Etree but etreeTagName from elanTag {} is null",
958                              ifName, elanTag);
959                 } else {
960                     Flow flowEntity = buildLocalDmacFlowEntry(etreeTagName.getEtreeLeafTag().getValue(), dpId, ifName,
961                             macAddress, elanInfo, ifTag);
962                     mdsalApiManager.addFlowToTx(dpId, flowEntity, writeFlowGroupTx);
963                 }
964             }
965         }
966     }
967
968     public static String getKnownDynamicmacFlowRef(short tableId, BigInteger dpId, long lporTag, String macAddress,
969             long elanTag) {
970         return new StringBuffer().append(tableId).append(elanTag).append(dpId).append(lporTag).append(macAddress)
971                 .toString();
972     }
973
974     public static String getKnownDynamicmacFlowRef(short tableId, BigInteger dpId, BigInteger remoteDpId,
975             String macAddress, long elanTag) {
976         return new StringBuffer().append(tableId).append(elanTag).append(dpId).append(remoteDpId).append(macAddress)
977                 .toString();
978     }
979
980     public static String getKnownDynamicmacFlowRef(short tableId, BigInteger dpId, String macAddress, long elanTag) {
981         return new StringBuffer().append(tableId).append(elanTag).append(dpId).append(macAddress).toString();
982     }
983
984     public static String getKnownDynamicmacFlowRef(short elanDmacTable, BigInteger dpId, String extDeviceNodeId,
985             String dstMacAddress, long elanTag, boolean shFlag) {
986         return new StringBuffer().append(elanDmacTable).append(elanTag).append(dpId).append(extDeviceNodeId)
987                 .append(dstMacAddress).append(shFlag).toString();
988     }
989
990     /**
991      * Builds the flow to be programmed in the DMAC table of the local DPN (that
992      * is, where the MAC is attached to). This flow consists in:
993      *
994      * <p>Match: + elanTag in metadata + packet goes to a MAC locally attached
995      * Actions: + optionally, pop-vlan + set-vlan-id + output to ifName's
996      * portNumber
997      *
998      * @param elanTag
999      *            the elan tag
1000      * @param dpId
1001      *            the dp id
1002      * @param ifName
1003      *            the if name
1004      * @param macAddress
1005      *            the mac address
1006      * @param elanInfo
1007      *            the elan info
1008      * @param ifTag
1009      *            the if tag
1010      * @return the flow
1011      */
1012     public Flow buildLocalDmacFlowEntry(long elanTag, BigInteger dpId, String ifName, String macAddress,
1013             ElanInstance elanInfo, long ifTag) {
1014
1015         List<MatchInfo> mkMatches = new ArrayList<>();
1016         mkMatches.add(new MatchMetadata(getElanMetadataLabel(elanTag), MetaDataUtil.METADATA_MASK_SERVICE));
1017         mkMatches.add(new MatchEthernetDestination(new MacAddress(macAddress)));
1018
1019         List<Instruction> mkInstructions = new ArrayList<>();
1020         List<Action> actions = getEgressActionsForInterface(ifName, /* tunnelKey */ null);
1021         mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
1022         Flow flow = MDSALUtil.buildFlowNew(NwConstants.ELAN_DMAC_TABLE,
1023                 getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, ifTag, macAddress, elanTag), 20,
1024                 elanInfo.getElanInstanceName(), 0, 0, ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(
1025                         BigInteger.valueOf(elanTag)), mkMatches, mkInstructions);
1026
1027         return flow;
1028     }
1029
1030     public void setupRemoteDmacFlow(BigInteger srcDpId, BigInteger destDpId, int lportTag, long elanTag, String
1031             macAddress, String displayName, WriteTransaction writeFlowGroupTx, String interfaceName, ElanInstance
1032             elanInstance) throws ElanException {
1033         if (interfaceManager.isExternalInterface(interfaceName)) {
1034             LOG.debug("Ignoring install remote DMAC {} flow on provider interface {} elan {}",
1035                     macAddress, interfaceName, elanInstance.getElanInstanceName());
1036             return;
1037         }
1038         Flow flowEntity;
1039         // if openstack-vni-semantics are enforced, segmentation ID is passed as network VNI for VxLAN based provider
1040         // networks, 0 otherwise
1041         long lportTagOrVni = !isOpenStackVniSemanticsEnforced() ? lportTag : ((isVxlan(elanInstance))
1042                 ? elanInstance.getSegmentationId() : 0);
1043         flowEntity = buildRemoteDmacFlowEntry(srcDpId, destDpId, lportTagOrVni, elanTag, macAddress, displayName,
1044                 elanInstance);
1045         mdsalManager.addFlowToTx(srcDpId, flowEntity, writeFlowGroupTx);
1046         setupEtreeRemoteDmacFlow(srcDpId, destDpId, lportTagOrVni, elanTag, macAddress, displayName, interfaceName,
1047                 writeFlowGroupTx, elanInstance);
1048     }
1049
1050     private void setupEtreeRemoteDmacFlow(BigInteger srcDpId, BigInteger destDpId, long lportTagOrVni, long elanTag,
1051                                           String macAddress, String displayName, String interfaceName,
1052                                           WriteTransaction writeFlowGroupTx, ElanInstance elanInstance)
1053                                           throws ElanException {
1054         Flow flowEntity;
1055         EtreeInterface etreeInterface = getEtreeInterfaceByElanInterfaceName(broker, interfaceName);
1056         if (etreeInterface != null) {
1057             if (etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
1058                 EtreeLeafTagName etreeTagName = getEtreeLeafTagByElanTag(elanTag);
1059                 if (etreeTagName == null) {
1060                     LOG.warn("Interface " + interfaceName
1061                             + " seems like it belongs to Etree but etreeTagName from elanTag " + elanTag + " is null.");
1062                 } else {
1063                     flowEntity = buildRemoteDmacFlowEntry(srcDpId, destDpId, lportTagOrVni,
1064                             etreeTagName.getEtreeLeafTag().getValue(), macAddress, displayName, elanInstance);
1065                     mdsalManager.addFlowToTx(srcDpId, flowEntity, writeFlowGroupTx);
1066                 }
1067             }
1068         }
1069     }
1070
1071     /**
1072      * Builds a Flow to be programmed in a remote DPN's DMAC table. This flow
1073      * consists in: Match: + elanTag in packet's metadata + packet going to a
1074      * MAC known to be located in another DPN Actions: + set_tunnel_id
1075      * + output ITM internal tunnel interface with the other DPN
1076      *
1077      * @param srcDpId
1078      *            the src Dpn Id
1079      * @param destDpId
1080      *            dest Dp Id
1081      * @param lportTagOrVni
1082      *            lportTag or network VNI
1083      * @param elanTag
1084      *            elan Tag
1085      * @param macAddress
1086      *            macAddress
1087      * @param displayName
1088      *            display Name
1089      * @return the flow remote Dmac
1090      * @throws ElanException in case of issues creating the flow objects
1091      */
1092     @SuppressWarnings("checkstyle:IllegalCatch")
1093     public Flow buildRemoteDmacFlowEntry(BigInteger srcDpId, BigInteger destDpId, long lportTagOrVni, long elanTag,
1094             String macAddress, String displayName, ElanInstance elanInstance) throws ElanException {
1095         List<MatchInfo> mkMatches = new ArrayList<>();
1096         mkMatches.add(new MatchMetadata(getElanMetadataLabel(elanTag), MetaDataUtil.METADATA_MASK_SERVICE));
1097         mkMatches.add(new MatchEthernetDestination(new MacAddress(macAddress)));
1098
1099         List<Instruction> mkInstructions = new ArrayList<>();
1100
1101         // List of Action for the provided Source and Destination DPIDs
1102         try {
1103             List<Action> actions = null;
1104             if (isVlan(elanInstance) || isFlat(elanInstance)) {
1105                 String interfaceName = getExternalElanInterface(elanInstance.getElanInstanceName(), srcDpId);
1106                 if (null == interfaceName) {
1107                     LOG.error("buildRemoteDmacFlowEntry: Could not find interfaceName for {} {}", srcDpId,
1108                             elanInstance);
1109                 }
1110                 actions = getEgressActionsForInterface(interfaceName, null);
1111             } else if (isVxlan(elanInstance)) {
1112                 actions = getInternalTunnelItmEgressAction(srcDpId, destDpId, lportTagOrVni);
1113             }
1114             mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
1115         } catch (Exception e) {
1116             LOG.error("Could not get egress actions to add to flow for srcDpId=" + srcDpId + ", destDpId=" + destDpId
1117                     + ", lportTag/VNI=" + lportTagOrVni, e);
1118         }
1119
1120         Flow flow = MDSALUtil.buildFlowNew(NwConstants.ELAN_DMAC_TABLE,
1121                 getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, srcDpId, destDpId, macAddress, elanTag),
1122                 20, /* prio */
1123                 displayName, 0, /* idleTimeout */
1124                 0, /* hardTimeout */
1125                 ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(BigInteger.valueOf(elanTag)), mkMatches, mkInstructions);
1126
1127         return flow;
1128
1129     }
1130
1131     public void deleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, MacEntry macEntry,
1132             WriteTransaction deleteFlowGroupTx) {
1133         if (elanInfo == null || interfaceInfo == null) {
1134             return;
1135         }
1136         String macAddress = macEntry.getMacAddress().getValue();
1137         synchronized (getElanMacDPNKey(elanInfo.getElanTag(), macAddress, interfaceInfo.getDpId())) {
1138             deleteMacFlows(elanInfo, interfaceInfo, macAddress, /* alsoDeleteSMAC */ true, deleteFlowGroupTx);
1139         }
1140     }
1141
1142     public void deleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1143             boolean deleteSmac, WriteTransaction deleteFlowGroupTx) {
1144         String elanInstanceName = elanInfo.getElanInstanceName();
1145         List<DpnInterfaces> remoteFEs = getInvolvedDpnsInElan(elanInstanceName);
1146         BigInteger srcdpId = interfaceInfo.getDpId();
1147         boolean isFlowsRemovedInSrcDpn = false;
1148         for (DpnInterfaces dpnInterface : remoteFEs) {
1149             Long elanTag = elanInfo.getElanTag();
1150             BigInteger dstDpId = dpnInterface.getDpId();
1151             if (executeDeleteMacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, elanInstanceName, srcdpId,
1152                     elanTag, dstDpId, deleteFlowGroupTx)) {
1153                 isFlowsRemovedInSrcDpn = true;
1154             }
1155             executeEtreeDeleteMacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, elanInstanceName, srcdpId,
1156                     elanTag, dstDpId, deleteFlowGroupTx);
1157         }
1158         if (!isFlowsRemovedInSrcDpn) {
1159             deleteSmacAndDmacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, deleteFlowGroupTx);
1160         }
1161     }
1162
1163     private void executeEtreeDeleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1164             boolean deleteSmac, String elanInstanceName, BigInteger srcdpId, Long elanTag, BigInteger dstDpId,
1165             WriteTransaction deleteFlowGroupTx) {
1166         EtreeLeafTagName etreeLeafTag = getEtreeLeafTagByElanTag(elanTag);
1167         if (etreeLeafTag != null) {
1168             executeDeleteMacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, elanInstanceName, srcdpId,
1169                     etreeLeafTag.getEtreeLeafTag().getValue(), dstDpId, deleteFlowGroupTx);
1170         }
1171     }
1172
1173     private boolean executeDeleteMacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1174             boolean deleteSmac, String elanInstanceName, BigInteger srcdpId, Long elanTag, BigInteger dstDpId,
1175             WriteTransaction deleteFlowGroupTx) {
1176         boolean isFlowsRemovedInSrcDpn = false;
1177         if (dstDpId.equals(srcdpId)) {
1178             isFlowsRemovedInSrcDpn = true;
1179             deleteSmacAndDmacFlows(elanInfo, interfaceInfo, macAddress, deleteSmac, deleteFlowGroupTx);
1180         } else if (isDpnPresent(dstDpId)) {
1181             mdsalManager
1182                     .removeFlowToTx(dstDpId,
1183                             MDSALUtil.buildFlow(NwConstants.ELAN_DMAC_TABLE, getKnownDynamicmacFlowRef(
1184                                     NwConstants.ELAN_DMAC_TABLE, dstDpId, srcdpId, macAddress, elanTag)),
1185                             deleteFlowGroupTx);
1186             LOG.debug("Dmac flow entry deleted for elan:{}, logical interface port:{} and mac address:{} on dpn:{}",
1187                     elanInstanceName, interfaceInfo.getPortName(), macAddress, dstDpId);
1188         }
1189         return isFlowsRemovedInSrcDpn;
1190     }
1191
1192     private void deleteSmacAndDmacFlows(ElanInstance elanInfo, InterfaceInfo interfaceInfo, String macAddress,
1193             boolean deleteSmac, WriteTransaction deleteFlowGroupTx) {
1194         String elanInstanceName = elanInfo.getElanInstanceName();
1195         long ifTag = interfaceInfo.getInterfaceTag();
1196         BigInteger srcdpId = interfaceInfo.getDpId();
1197         Long elanTag = elanInfo.getElanTag();
1198         if (deleteSmac) {
1199             mdsalManager
1200                     .removeFlowToTx(srcdpId,
1201                             MDSALUtil.buildFlow(NwConstants.ELAN_SMAC_TABLE, getKnownDynamicmacFlowRef(
1202                                     NwConstants.ELAN_SMAC_TABLE, srcdpId, ifTag, macAddress, elanTag)),
1203                             deleteFlowGroupTx);
1204         }
1205         mdsalManager.removeFlowToTx(srcdpId,
1206                 MDSALUtil.buildFlow(NwConstants.ELAN_DMAC_TABLE,
1207                         getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, srcdpId, ifTag, macAddress, elanTag)),
1208                 deleteFlowGroupTx);
1209         LOG.debug("All the required flows deleted for elan:{}, logical Interface port:{} and MAC address:{} on dpn:{}",
1210                 elanInstanceName, interfaceInfo.getPortName(), macAddress, srcdpId);
1211     }
1212
1213     /**
1214      * Updates the Elan information in the Operational DS. It also updates the
1215      * ElanInstance in the Config DS by setting the adquired elanTag.
1216      *
1217      * @param broker
1218      *            the broker
1219      * @param idManager
1220      *            the id manager
1221      * @param elanInstanceAdded
1222      *            the elan instance added
1223      * @param elanInterfaces
1224      *            the elan interfaces
1225      * @param tx
1226      *            transaction
1227      */
1228     public static void updateOperationalDataStore(DataBroker broker, IdManagerService idManager,
1229             ElanInstance elanInstanceAdded, List<String> elanInterfaces, WriteTransaction tx) {
1230         String elanInstanceName = elanInstanceAdded.getElanInstanceName();
1231         Long elanTag = elanInstanceAdded.getElanTag();
1232         if (elanTag == null || elanTag == 0L) {
1233             elanTag = retrieveNewElanTag(idManager, elanInstanceName);
1234         }
1235         Elan elanInfo = new ElanBuilder().setName(elanInstanceName).setElanInterfaces(elanInterfaces)
1236                 .setKey(new ElanKey(elanInstanceName)).build();
1237
1238         // Add the ElanState in the elan-state operational data-store
1239         tx.put(LogicalDatastoreType.OPERATIONAL, getElanInstanceOperationalDataPath(elanInstanceName),
1240                 elanInfo, true);
1241
1242         // Add the ElanMacTable in the elan-mac-table operational data-store
1243         MacTable elanMacTable = new MacTableBuilder().setKey(new MacTableKey(elanInstanceName)).build();
1244         tx.put(LogicalDatastoreType.OPERATIONAL, getElanMacTableOperationalDataPath(elanInstanceName),
1245                 elanMacTable, true);
1246
1247         ElanTagNameBuilder elanTagNameBuilder = new ElanTagNameBuilder().setElanTag(elanTag)
1248                 .setKey(new ElanTagNameKey(elanTag)).setName(elanInstanceName);
1249         long etreeLeafTag = -1;
1250         if (isEtreeInstance(elanInstanceAdded)) {
1251             etreeLeafTag = retrieveNewElanTag(idManager, elanInstanceName + ElanConstants.LEAVES_POSTFIX);
1252             EtreeLeafTagName etreeLeafTagName = new EtreeLeafTagNameBuilder()
1253                     .setEtreeLeafTag(new EtreeLeafTag(etreeLeafTag)).build();
1254             elanTagNameBuilder.addAugmentation(EtreeLeafTagName.class, etreeLeafTagName);
1255             addTheLeafTagAsElanTag(broker, elanInstanceName, etreeLeafTag, tx);
1256         }
1257         ElanTagName elanTagName = elanTagNameBuilder.build();
1258
1259         // Add the ElanTag to ElanName in the elan-tag-name Operational
1260         // data-store
1261         tx.put(LogicalDatastoreType.OPERATIONAL,
1262                 getElanInfoEntriesOperationalDataPath(elanTag), elanTagName);
1263
1264         // Updates the ElanInstance Config DS by setting the just acquired
1265         // elanTag
1266         ElanInstanceBuilder elanInstanceBuilder = new ElanInstanceBuilder().setElanInstanceName(elanInstanceName)
1267                 .setDescription(elanInstanceAdded.getDescription())
1268                 .setMacTimeout(elanInstanceAdded.getMacTimeout() == null ? ElanConstants.DEFAULT_MAC_TIME_OUT
1269                         : elanInstanceAdded.getMacTimeout())
1270                 .setKey(elanInstanceAdded.getKey()).setElanTag(elanTag);
1271         if (isEtreeInstance(elanInstanceAdded)) {
1272             EtreeInstance etreeInstance = new EtreeInstanceBuilder().setEtreeLeafTagVal(new EtreeLeafTag(etreeLeafTag))
1273                     .build();
1274             elanInstanceBuilder.addAugmentation(EtreeInstance.class, etreeInstance);
1275         }
1276         ElanInstance elanInstanceWithTag = elanInstanceBuilder.build();
1277         tx.merge(LogicalDatastoreType.CONFIGURATION, ElanHelper.getElanInstanceConfigurationDataPath(elanInstanceName),
1278                 elanInstanceWithTag, true);
1279     }
1280
1281     private static void addTheLeafTagAsElanTag(DataBroker broker, String elanInstanceName, long etreeLeafTag,
1282             WriteTransaction tx) {
1283         ElanTagName etreeTagAsElanTag = new ElanTagNameBuilder().setElanTag(etreeLeafTag)
1284                 .setKey(new ElanTagNameKey(etreeLeafTag)).setName(elanInstanceName).build();
1285         tx.put(LogicalDatastoreType.OPERATIONAL,
1286                 getElanInfoEntriesOperationalDataPath(etreeLeafTag), etreeTagAsElanTag);
1287     }
1288
1289     private static boolean isEtreeInstance(ElanInstance elanInstanceAdded) {
1290         return elanInstanceAdded.getAugmentation(EtreeInstance.class) != null;
1291     }
1292
1293     public boolean isDpnPresent(BigInteger dpnId) {
1294         String dpn = String.format("%s:%s", "openflow", dpnId);
1295         NodeId nodeId = new NodeId(dpn);
1296
1297         InstanceIdentifier<Node> node = InstanceIdentifier.builder(Nodes.class).child(Node.class, new NodeKey(nodeId))
1298                 .build();
1299         return read(broker, LogicalDatastoreType.CONFIGURATION, node).isPresent();
1300     }
1301
1302     public static ServicesInfo getServiceInfo(String elanInstanceName, long elanTag, String interfaceName) {
1303         int priority = ElanConstants.ELAN_SERVICE_PRIORITY;
1304         int instructionKey = 0;
1305         List<Instruction> instructions = new ArrayList<>();
1306         instructions.add(MDSALUtil.buildAndGetWriteMetadaInstruction(getElanMetadataLabel(elanTag),
1307                 MetaDataUtil.METADATA_MASK_SERVICE, ++instructionKey));
1308         instructions.add(MDSALUtil.buildAndGetGotoTableInstruction(NwConstants.ELAN_SMAC_TABLE, ++instructionKey));
1309
1310         short serviceIndex = ServiceIndex.getIndex(NwConstants.ELAN_SERVICE_NAME, NwConstants.ELAN_SERVICE_INDEX);
1311         ServicesInfo serviceInfo = InterfaceServiceUtil.buildServiceInfo(
1312                 String.format("%s.%s", elanInstanceName, interfaceName), serviceIndex, priority,
1313                 NwConstants.COOKIE_ELAN_INGRESS_TABLE, instructions);
1314         return serviceInfo;
1315     }
1316
1317     public static <T extends DataObject> void syncWrite(DataBroker broker, LogicalDatastoreType datastoreType,
1318             InstanceIdentifier<T> path, T data) {
1319         WriteTransaction tx = broker.newWriteOnlyTransaction();
1320         tx.put(datastoreType, path, data, true);
1321         CheckedFuture<Void, TransactionCommitFailedException> futures = tx.submit();
1322         try {
1323             futures.get();
1324         } catch (InterruptedException | ExecutionException e) {
1325             LOG.error("Error writing to datastore (path, data) : ({}, {})", path, data);
1326             throw new RuntimeException(e.getMessage());
1327         }
1328     }
1329
1330     public static BoundServices getBoundServices(String serviceName, short servicePriority, int flowPriority,
1331             BigInteger cookie, List<Instruction> instructions) {
1332         StypeOpenflowBuilder augBuilder = new StypeOpenflowBuilder().setFlowCookie(cookie).setFlowPriority(flowPriority)
1333                 .setInstruction(instructions);
1334         return new BoundServicesBuilder().setKey(new BoundServicesKey(servicePriority)).setServiceName(serviceName)
1335                 .setServicePriority(servicePriority).setServiceType(ServiceTypeFlowBased.class)
1336                 .addAugmentation(StypeOpenflow.class, augBuilder.build()).build();
1337     }
1338
1339     public static InstanceIdentifier<BoundServices> buildServiceId(String interfaceName, short serviceIndex) {
1340         return InstanceIdentifier.builder(ServiceBindings.class)
1341                 .child(ServicesInfo.class, new ServicesInfoKey(interfaceName, ServiceModeIngress.class))
1342                 .child(BoundServices.class, new BoundServicesKey(serviceIndex)).build();
1343     }
1344
1345     /**
1346      * Builds the list of actions to be taken when sending the packet over a VxLan Tunnel Interface, such as setting
1347      * the network VNI in the tunnel_id field.
1348      *
1349      * @param tunnelIfaceName
1350      *            the tunnel iface name
1351      * @param tunnelKey
1352      *            the tunnel key
1353      * @return the list
1354      */
1355     public List<Action> buildTunnelItmEgressActions(String tunnelIfaceName, Long tunnelKey) {
1356         if (tunnelIfaceName != null && !tunnelIfaceName.isEmpty()) {
1357             return buildItmEgressActions(tunnelIfaceName, tunnelKey);
1358         }
1359
1360         return Collections.emptyList();
1361     }
1362
1363     /**
1364      * Builds the list of actions to be taken when sending the packet over external port such as tunnel, physical
1365      * port etc.
1366      *
1367      * @param interfaceName
1368      *            the interface name
1369      * @param tunnelKey
1370      *            can be VNI for VxLAN tunnel interfaces, Gre Key for GRE
1371      *            tunnels, etc.
1372      * @return the list
1373      */
1374     @SuppressWarnings("checkstyle:IllegalCatch")
1375     public List<Action> buildItmEgressActions(String interfaceName, Long tunnelKey) {
1376         List<Action> result = Collections.emptyList();
1377         try {
1378             GetEgressActionsForInterfaceInput getEgressActInput = new GetEgressActionsForInterfaceInputBuilder()
1379                     .setIntfName(interfaceName).setTunnelKey(tunnelKey).build();
1380
1381             Future<RpcResult<GetEgressActionsForInterfaceOutput>> egressActionsOutputFuture = interfaceManagerRpcService
1382                     .getEgressActionsForInterface(getEgressActInput);
1383             if (egressActionsOutputFuture.get().isSuccessful()) {
1384                 GetEgressActionsForInterfaceOutput egressActionsOutput = egressActionsOutputFuture.get().getResult();
1385                 result = egressActionsOutput.getAction();
1386             }
1387         } catch (Exception e) {
1388             LOG.error("Error in RPC call getEgressActionsForInterface {}", e);
1389         }
1390
1391         if (result == null || result.size() == 0) {
1392             LOG.warn("Could not build Egress actions for interface {} and tunnelId {}", interfaceName, tunnelKey);
1393         }
1394         return result;
1395     }
1396
1397     /**
1398      * Builds the list of actions to be taken when sending the packet over an
1399      * external VxLan tunnel interface, such as stamping the VNI on the VxLAN
1400      * header, setting the vlanId if it proceeds and output the packet over the
1401      * right port.
1402      *
1403      * @param srcDpnId
1404      *            Dpn where the tunnelInterface is located
1405      * @param torNode
1406      *            NodeId of the ExternalDevice where the packet must be sent to.
1407      * @param vni
1408      *            Vni to be stamped on the VxLAN Header.
1409      * @return the external itm egress action
1410      */
1411     public List<Action> getExternalTunnelItmEgressAction(BigInteger srcDpnId, NodeId torNode, long vni) {
1412         List<Action> result = Collections.emptyList();
1413
1414         GetExternalTunnelInterfaceNameInput input = new GetExternalTunnelInterfaceNameInputBuilder()
1415                 .setDestinationNode(torNode.getValue()).setSourceNode(srcDpnId.toString())
1416                 .setTunnelType(TunnelTypeVxlan.class).build();
1417         Future<RpcResult<GetExternalTunnelInterfaceNameOutput>> output = itmRpcService
1418                 .getExternalTunnelInterfaceName(input);
1419         try {
1420             if (output.get().isSuccessful()) {
1421                 GetExternalTunnelInterfaceNameOutput tunnelInterfaceNameOutput = output.get().getResult();
1422                 String tunnelIfaceName = tunnelInterfaceNameOutput.getInterfaceName();
1423                 LOG.debug("Received tunnelInterfaceName from getTunnelInterfaceName RPC {}", tunnelIfaceName);
1424
1425                 result = buildTunnelItmEgressActions(tunnelIfaceName, vni);
1426             }
1427
1428         } catch (InterruptedException | ExecutionException e) {
1429             LOG.error("Error in RPC call getTunnelInterfaceName {}", e);
1430         }
1431
1432         return result;
1433     }
1434
1435     public List<Action> getExternalTunnelItmEgressAction(BigInteger srcDpnId, String nexthopIP, long vni) {
1436         List<Action> result = Collections.emptyList();
1437
1438         GetExternalTunnelInterfaceNameInput input = new GetExternalTunnelInterfaceNameInputBuilder()
1439                 .setDestinationNode(nexthopIP).setSourceNode(srcDpnId.toString())
1440                 .setTunnelType(TunnelTypeVxlan.class).build();
1441         Future<RpcResult<GetExternalTunnelInterfaceNameOutput>> output = itmRpcService
1442                 .getExternalTunnelInterfaceName(input);
1443         try {
1444             if (output.get().isSuccessful()) {
1445                 GetExternalTunnelInterfaceNameOutput tunnelInterfaceNameOutput = output.get().getResult();
1446                 String tunnelIfaceName = tunnelInterfaceNameOutput.getInterfaceName();
1447                 LOG.debug("Received tunnelInterfaceName from getTunnelInterfaceName RPC {}", tunnelIfaceName);
1448
1449                 result = buildTunnelItmEgressActions(tunnelIfaceName, vni);
1450             }
1451
1452         } catch (InterruptedException | ExecutionException e) {
1453             LOG.error("Error in RPC call getTunnelInterfaceName {}", e);
1454         }
1455
1456         return result;
1457     }
1458
1459     /**
1460      * Builds the list of actions to be taken when sending the packet over an internal VxLAN tunnel interface, such
1461      * as setting the serviceTag/segmentationID on the VNI field of the VxLAN header, setting the vlanId if it proceeds
1462      * and output the packet over the right port.
1463      *
1464      * @param sourceDpnId
1465      *            Dpn where the tunnelInterface is located
1466      * @param destinationDpnId
1467      *            Dpn where the packet must be sent to. It is used here in order
1468      *            to select the right tunnel interface.
1469      * @param tunnelKey
1470      *            Tunnel key to be sent on the VxLAN header.
1471      * @return the internal itm egress action
1472      */
1473     public List<Action> getInternalTunnelItmEgressAction(BigInteger sourceDpnId, BigInteger destinationDpnId, long
1474             tunnelKey) {
1475         List<Action> result = Collections.emptyList();
1476         LOG.trace("In getInternalItmEgressAction Action source {}, destination {}, serviceTag/Vni {}", sourceDpnId,
1477                 destinationDpnId, tunnelKey);
1478         Class<? extends TunnelTypeBase> tunType = TunnelTypeVxlan.class;
1479         GetTunnelInterfaceNameInput input = new GetTunnelInterfaceNameInputBuilder()
1480                 .setDestinationDpid(destinationDpnId).setSourceDpid(sourceDpnId).setTunnelType(tunType).build();
1481         Future<RpcResult<GetTunnelInterfaceNameOutput>> output = itmRpcService.getTunnelInterfaceName(input);
1482         try {
1483             if (output.get().isSuccessful()) {
1484                 GetTunnelInterfaceNameOutput tunnelInterfaceNameOutput = output.get().getResult();
1485                 String tunnelIfaceName = tunnelInterfaceNameOutput.getInterfaceName();
1486                 LOG.info("Received tunnelInterfaceName from getTunnelInterfaceName RPC {}", tunnelIfaceName);
1487                 result = buildTunnelItmEgressActions(tunnelIfaceName, tunnelKey);
1488             } else {
1489                 LOG.trace("Tunnel interface doesn't exist between srcDpId {} dstDpId {}", sourceDpnId,
1490                         destinationDpnId);
1491             }
1492         } catch (InterruptedException | ExecutionException e) {
1493             LOG.error("Error in RPC call getTunnelInterfaceName {}", e);
1494         }
1495         return result;
1496     }
1497
1498     /**
1499      * Build the list of actions to be taken when sending the packet to external
1500      * (physical) port.
1501      *
1502      * @param interfaceName
1503      *            Interface name
1504      * @return the external port itm egress actions
1505      */
1506     public List<Action> getExternalPortItmEgressAction(String interfaceName) {
1507         return buildItmEgressActions(interfaceName, null);
1508     }
1509
1510     public static List<MatchInfo> getTunnelMatchesForServiceId(int elanTag) {
1511         List<MatchInfo> mkMatches = new ArrayList<>();
1512         // Matching metadata
1513         mkMatches.add(new MatchTunnelId(BigInteger.valueOf(elanTag)));
1514
1515         return mkMatches;
1516     }
1517
1518     public void removeTerminatingServiceAction(BigInteger destDpId, int serviceId) {
1519         RemoveTerminatingServiceActionsInput input = new RemoveTerminatingServiceActionsInputBuilder()
1520                 .setDpnId(destDpId).setServiceId(serviceId).build();
1521         Future<RpcResult<Void>> futureObject = itmRpcService.removeTerminatingServiceActions(input);
1522         try {
1523             RpcResult<Void> result = futureObject.get();
1524             if (result.isSuccessful()) {
1525                 LOG.debug("Successfully completed removeTerminatingServiceActions for ELAN with serviceId {} on "
1526                                 + "dpn {}", serviceId, destDpId);
1527             } else {
1528                 LOG.debug("Failure in removeTerminatingServiceAction RPC call for ELAN with serviceId {} on "
1529                         + "dpn {}", serviceId, destDpId);
1530             }
1531         } catch (InterruptedException | ExecutionException e) {
1532             LOG.error("Error in RPC call removeTerminatingServiceActions for ELAN with serviceId {} on "
1533                     + "dpn {}: {}", serviceId, destDpId, e);
1534         }
1535     }
1536
1537     /**
1538      * Gets the external tunnel.
1539      *
1540      * @param sourceDevice
1541      *            the source device
1542      * @param destinationDevice
1543      *            the destination device
1544      * @param datastoreType
1545      *            the datastore type
1546      * @return the external tunnel
1547      */
1548     public ExternalTunnel getExternalTunnel(String sourceDevice, String destinationDevice,
1549             LogicalDatastoreType datastoreType) {
1550         Class<? extends TunnelTypeBase> tunType = TunnelTypeVxlan.class;
1551         InstanceIdentifier<ExternalTunnel> iid = InstanceIdentifier.builder(ExternalTunnelList.class)
1552                 .child(ExternalTunnel.class, new ExternalTunnelKey(destinationDevice, sourceDevice, tunType)).build();
1553         return read(broker, datastoreType, iid).orNull();
1554     }
1555
1556     /**
1557      * Gets the external tunnel.
1558      *
1559      * @param interfaceName
1560      *            the interface name
1561      * @param datastoreType
1562      *            the datastore type
1563      * @return the external tunnel
1564      */
1565     public ExternalTunnel getExternalTunnel(String interfaceName, LogicalDatastoreType datastoreType) {
1566         ExternalTunnel externalTunnel = null;
1567         List<ExternalTunnel> externalTunnels = getAllExternalTunnels(datastoreType);
1568         for (ExternalTunnel tunnel : externalTunnels) {
1569             if (StringUtils.equalsIgnoreCase(interfaceName, tunnel.getTunnelInterfaceName())) {
1570                 externalTunnel = tunnel;
1571                 break;
1572             }
1573         }
1574         return externalTunnel;
1575     }
1576
1577     /**
1578      * Gets the all external tunnels.
1579      *
1580      * @param datastoreType
1581      *            the data store type
1582      * @return the all external tunnels
1583      */
1584     public List<ExternalTunnel> getAllExternalTunnels(LogicalDatastoreType datastoreType) {
1585         InstanceIdentifier<ExternalTunnelList> iid = InstanceIdentifier.builder(ExternalTunnelList.class).build();
1586         return read(broker, datastoreType, iid).transform(ExternalTunnelList::getExternalTunnel).or(
1587                 Collections.emptyList());
1588     }
1589
1590     /**
1591      * Installs a Flow in the specified DPN's DMAC table. The flow is for a MAC
1592      * that is connected remotely in an External Device (TOR) and that is
1593      * accessible through an external tunnel. It also installs the flow for
1594      * dropping the packet if it came over an ITM tunnel (that is, if the
1595      * Split-Horizon flag is set)
1596      *
1597      * @param dpnId
1598      *            Id of the DPN where the flow must be installed
1599      * @param extDeviceNodeId
1600      *            the ext device node id
1601      * @param elanTag
1602      *            the elan tag
1603      * @param vni
1604      *            the vni
1605      * @param macAddress
1606      *            the mac address
1607      * @param displayName
1608      *            the display name
1609      * @param interfaceName
1610      *            the interface name
1611      *
1612      * @return the dmac flows
1613      * @throws ElanException in case of issues creating the flow objects
1614      */
1615     public List<ListenableFuture<Void>> installDmacFlowsToExternalRemoteMac(BigInteger dpnId,
1616             String extDeviceNodeId, Long elanTag, Long vni, String macAddress, String displayName,
1617             String interfaceName) throws ElanException {
1618         List<ListenableFuture<Void>> futures = new ArrayList<>();
1619         synchronized (getElanMacDPNKey(elanTag, macAddress, dpnId)) {
1620             Flow flow = buildDmacFlowForExternalRemoteMac(dpnId, extDeviceNodeId, elanTag, vni, macAddress,
1621                     displayName);
1622             futures.add(mdsalManager.installFlow(dpnId, flow));
1623
1624             Flow dropFlow = buildDmacFlowDropIfPacketComingFromTunnel(dpnId, extDeviceNodeId, elanTag, macAddress);
1625             futures.add(mdsalManager.installFlow(dpnId, dropFlow));
1626             installEtreeDmacFlowsToExternalRemoteMac(dpnId, extDeviceNodeId, elanTag, vni, macAddress, displayName,
1627                     interfaceName, futures);
1628         }
1629         return futures;
1630     }
1631
1632     private void installEtreeDmacFlowsToExternalRemoteMac(BigInteger dpnId, String extDeviceNodeId, Long elanTag,
1633             Long vni, String macAddress, String displayName, String interfaceName,
1634             List<ListenableFuture<Void>> futures) throws ElanException {
1635         EtreeLeafTagName etreeLeafTag = getEtreeLeafTagByElanTag(elanTag);
1636         if (etreeLeafTag != null) {
1637             buildEtreeDmacFlowDropIfPacketComingFromTunnel(dpnId, extDeviceNodeId, elanTag, macAddress, futures,
1638                     etreeLeafTag);
1639             buildEtreeDmacFlowForExternalRemoteMac(dpnId, extDeviceNodeId, vni, macAddress, displayName, interfaceName,
1640                     futures, etreeLeafTag);
1641         }
1642     }
1643
1644     private void buildEtreeDmacFlowForExternalRemoteMac(BigInteger dpnId, String extDeviceNodeId, Long vni,
1645             String macAddress, String displayName, String interfaceName, List<ListenableFuture<Void>> futures,
1646             EtreeLeafTagName etreeLeafTag) throws ElanException {
1647         boolean isRoot = false;
1648         if (interfaceName == null) {
1649             isRoot = true;
1650         } else {
1651             EtreeInterface etreeInterface = getEtreeInterfaceByElanInterfaceName(broker, interfaceName);
1652             if (etreeInterface != null) {
1653                 if (etreeInterface.getEtreeInterfaceType() == EtreeInterfaceType.Root) {
1654                     isRoot = true;
1655                 }
1656             }
1657         }
1658         if (isRoot) {
1659             Flow flow = buildDmacFlowForExternalRemoteMac(dpnId, extDeviceNodeId,
1660                     etreeLeafTag.getEtreeLeafTag().getValue(), vni, macAddress, displayName);
1661             futures.add(mdsalManager.installFlow(dpnId, flow));
1662         }
1663     }
1664
1665     private void buildEtreeDmacFlowDropIfPacketComingFromTunnel(BigInteger dpnId, String extDeviceNodeId,
1666             Long elanTag, String macAddress, List<ListenableFuture<Void>> futures, EtreeLeafTagName etreeLeafTag) {
1667         if (etreeLeafTag != null) {
1668             Flow dropFlow = buildDmacFlowDropIfPacketComingFromTunnel(dpnId, extDeviceNodeId,
1669                     etreeLeafTag.getEtreeLeafTag().getValue(), macAddress);
1670             futures.add(mdsalManager.installFlow(dpnId, dropFlow));
1671         }
1672     }
1673
1674     public static List<MatchInfo> buildMatchesForElanTagShFlagAndDstMac(long elanTag, boolean shFlag, String macAddr) {
1675         List<MatchInfo> mkMatches = new ArrayList<>();
1676         mkMatches.add(
1677                 new MatchMetadata(getElanMetadataLabel(elanTag, shFlag), MetaDataUtil.METADATA_MASK_SERVICE_SH_FLAG));
1678         mkMatches.add(new MatchEthernetDestination(new MacAddress(macAddr)));
1679         return mkMatches;
1680     }
1681
1682     /**
1683      * Builds a Flow to be programmed in a DPN's DMAC table. This method must be
1684      * used when the MAC is located in an External Device (TOR). The flow
1685      * matches on the specified MAC and 1) sends the packet over the CSS-TOR
1686      * tunnel if SHFlag is not set, or 2) drops it if SHFlag is set (what means
1687      * the packet came from an external tunnel)
1688      *
1689      * @param dpId
1690      *            DPN whose DMAC table is going to be modified
1691      * @param extDeviceNodeId
1692      *            Hwvtep node where the mac is attached to
1693      * @param elanTag
1694      *            ElanId to which the MAC is being added to
1695      * @param vni
1696      *            the vni
1697      * @param dstMacAddress
1698      *            The mac address to be programmed
1699      * @param displayName
1700      *            the display name
1701      * @return the flow
1702      * @throws ElanException in case of issues creating the flow objects
1703      */
1704     @SuppressWarnings("checkstyle:IllegalCatch")
1705     public Flow buildDmacFlowForExternalRemoteMac(BigInteger dpId, String extDeviceNodeId, long elanTag,
1706             Long vni, String dstMacAddress, String displayName) throws ElanException {
1707         List<MatchInfo> mkMatches = buildMatchesForElanTagShFlagAndDstMac(elanTag, /* shFlag */ false, dstMacAddress);
1708         List<Instruction> mkInstructions = new ArrayList<>();
1709         try {
1710             List<Action> actions = getExternalTunnelItmEgressAction(dpId, new NodeId(extDeviceNodeId), vni);
1711             mkInstructions.add(MDSALUtil.buildApplyActionsInstruction(actions));
1712         } catch (Exception e) {
1713             LOG.error("Could not get Egress Actions for DpId=" + dpId + ", externalNode=" + extDeviceNodeId, e);
1714         }
1715
1716         Flow flow = MDSALUtil.buildFlowNew(NwConstants.ELAN_DMAC_TABLE,
1717                 getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, extDeviceNodeId, dstMacAddress, elanTag,
1718                         false),
1719                 20, /* prio */
1720                 displayName, 0, /* idleTimeout */
1721                 0, /* hardTimeout */
1722                 ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(BigInteger.valueOf(elanTag)), mkMatches, mkInstructions);
1723
1724         return flow;
1725     }
1726
1727     /**
1728      * Builds the flow that drops the packet if it came through an external
1729      * tunnel, that is, if the Split-Horizon flag is set.
1730      *
1731      * @param dpnId
1732      *            DPN whose DMAC table is going to be modified
1733      * @param extDeviceNodeId
1734      *            Hwvtep node where the mac is attached to
1735      * @param elanTag
1736      *            ElanId to which the MAC is being added to
1737      * @param dstMacAddress
1738      *            The mac address to be programmed
1739      */
1740     private static Flow buildDmacFlowDropIfPacketComingFromTunnel(BigInteger dpnId, String extDeviceNodeId,
1741             Long elanTag, String dstMacAddress) {
1742         List<MatchInfo> mkMatches = buildMatchesForElanTagShFlagAndDstMac(elanTag, SH_FLAG_SET, dstMacAddress);
1743         List<Instruction> mkInstructions = MDSALUtil.buildInstructionsDrop();
1744         String flowId = getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpnId, extDeviceNodeId, dstMacAddress,
1745                 elanTag, true);
1746         Flow flow = MDSALUtil.buildFlowNew(NwConstants.ELAN_DMAC_TABLE, flowId, 20, /* prio */
1747                 "Drop", 0, /* idleTimeout */
1748                 0, /* hardTimeout */
1749                 ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(BigInteger.valueOf(elanTag)), mkMatches, mkInstructions);
1750
1751         return flow;
1752     }
1753
1754     private static String getDmacDropFlowId(Long elanTag, String dstMacAddress) {
1755         return new StringBuilder(NwConstants.ELAN_DMAC_TABLE).append(elanTag).append(dstMacAddress).append("Drop")
1756                 .toString();
1757     }
1758
1759     /**
1760      * Installs or removes flows in DMAC table for MACs that are/were located in
1761      * an external Elan Device.
1762      *
1763      * @param dpId
1764      *            Id of the DPN where the DMAC table is going to be modified
1765      * @param extNodeId
1766      *            Id of the External Device where the MAC is located
1767      * @param elanTag
1768      *            Id of the ELAN
1769      * @param vni
1770      *            VNI of the LogicalSwitch to which the MAC belongs to, and that
1771      *            is associated with the ELAN
1772      * @param macAddress
1773      *            the mac address
1774      * @param elanInstanceName
1775      *            the elan instance name
1776      * @param addOrRemove
1777      *            Indicates if flows must be installed or removed.
1778      * @param interfaceName
1779      *            the interface name
1780      * @throws ElanException in case of issues creating the flow objects
1781      * @see org.opendaylight.genius.mdsalutil.MDSALUtil.MdsalOp
1782      */
1783     public void setupDmacFlowsToExternalRemoteMac(BigInteger dpId, String extNodeId, Long elanTag, Long vni,
1784             String macAddress, String elanInstanceName, MdsalOp addOrRemove, String interfaceName)
1785             throws ElanException {
1786         if (addOrRemove == MdsalOp.CREATION_OP) {
1787             installDmacFlowsToExternalRemoteMac(dpId, extNodeId, elanTag, vni, macAddress, elanInstanceName,
1788                     interfaceName);
1789         } else if (addOrRemove == MdsalOp.REMOVAL_OP) {
1790             deleteDmacFlowsToExternalMac(elanTag, dpId, extNodeId, macAddress);
1791         }
1792     }
1793
1794     /**
1795      * Delete dmac flows to external mac.
1796      *
1797      * @param elanTag
1798      *            the elan tag
1799      * @param dpId
1800      *            the dp id
1801      * @param extDeviceNodeId
1802      *            the ext device node id
1803      * @param macToRemove
1804      *            the mac to remove
1805      * @return dmac flow
1806      */
1807     public List<ListenableFuture<Void>> deleteDmacFlowsToExternalMac(long elanTag, BigInteger dpId,
1808             String extDeviceNodeId, String macToRemove) {
1809         List<ListenableFuture<Void>> futures = new ArrayList<>();
1810         synchronized (getElanMacDPNKey(elanTag, macToRemove, dpId)) {
1811             // Removing the flows that sends the packet on an external tunnel
1812             removeFlowThatSendsThePacketOnAnExternalTunnel(elanTag, dpId, extDeviceNodeId, macToRemove, futures);
1813
1814             // And now removing the drop flow
1815             removeTheDropFlow(elanTag, dpId, extDeviceNodeId, macToRemove, futures);
1816
1817             deleteEtreeDmacFlowsToExternalMac(elanTag, dpId, extDeviceNodeId, macToRemove, futures);
1818         }
1819         return futures;
1820     }
1821
1822     private void deleteEtreeDmacFlowsToExternalMac(long elanTag, BigInteger dpId, String extDeviceNodeId,
1823             String macToRemove, List<ListenableFuture<Void>> futures) {
1824         EtreeLeafTagName etreeLeafTag = getEtreeLeafTagByElanTag(elanTag);
1825         if (etreeLeafTag != null) {
1826             removeFlowThatSendsThePacketOnAnExternalTunnel(etreeLeafTag.getEtreeLeafTag().getValue(), dpId,
1827                     extDeviceNodeId, macToRemove, futures);
1828             removeTheDropFlow(etreeLeafTag.getEtreeLeafTag().getValue(), dpId, extDeviceNodeId, macToRemove, futures);
1829         }
1830     }
1831
1832     private void removeTheDropFlow(long elanTag, BigInteger dpId, String extDeviceNodeId, String macToRemove,
1833             List<ListenableFuture<Void>> futures) {
1834         String flowId = getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, extDeviceNodeId, macToRemove,
1835                 elanTag, true);
1836         Flow flowToRemove = new FlowBuilder().setId(new FlowId(flowId)).setTableId(NwConstants.ELAN_DMAC_TABLE).build();
1837         futures.add(mdsalManager.removeFlow(dpId, flowToRemove));
1838     }
1839
1840     private void removeFlowThatSendsThePacketOnAnExternalTunnel(long elanTag, BigInteger dpId,
1841             String extDeviceNodeId, String macToRemove, List<ListenableFuture<Void>> futures) {
1842         String flowId = getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, extDeviceNodeId, macToRemove,
1843                 elanTag, false);
1844         Flow flowToRemove = new FlowBuilder().setId(new FlowId(flowId)).setTableId(NwConstants.ELAN_DMAC_TABLE).build();
1845         futures.add(mdsalManager.removeFlow(dpId, flowToRemove));
1846     }
1847
1848     /**
1849      * Gets the dpid from interface.
1850      *
1851      * @param interfaceName
1852      *            the interface name
1853      * @return the dpid from interface
1854      */
1855     public BigInteger getDpidFromInterface(String interfaceName) {
1856         BigInteger dpId = null;
1857         Future<RpcResult<GetDpidFromInterfaceOutput>> output = interfaceManagerRpcService
1858                 .getDpidFromInterface(new GetDpidFromInterfaceInputBuilder().setIntfName(interfaceName).build());
1859         try {
1860             RpcResult<GetDpidFromInterfaceOutput> rpcResult = output.get();
1861             if (rpcResult.isSuccessful()) {
1862                 dpId = rpcResult.getResult().getDpid();
1863             }
1864         } catch (NullPointerException | InterruptedException | ExecutionException e) {
1865             LOG.error("Failed to get the DPN ID: {} for interface {}: {} ", dpId, interfaceName, e);
1866         }
1867         return dpId;
1868     }
1869
1870     /**
1871      * Checks if is interface operational.
1872      *
1873      * @param interfaceName
1874      *            the interface name
1875      * @param dataBroker
1876      *            the data broker
1877      * @return true, if is interface operational
1878      */
1879     public static boolean isInterfaceOperational(String interfaceName, DataBroker dataBroker) {
1880         if (StringUtils.isBlank(interfaceName)) {
1881             return false;
1882         }
1883         Interface ifState = getInterfaceStateFromOperDS(interfaceName, dataBroker);
1884         if (ifState == null) {
1885             return false;
1886         }
1887         return ifState.getOperStatus() == OperStatus.Up && ifState.getAdminStatus() == AdminStatus.Up;
1888     }
1889
1890     /**
1891      * Gets the interface state from operational ds.
1892      *
1893      * @param interfaceName
1894      *            the interface name
1895      * @param dataBroker
1896      *            the data broker
1897      * @return the interface state from oper ds
1898      */
1899     public static org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1900         .ietf.interfaces.rev140508.interfaces.state.Interface getInterfaceStateFromOperDS(
1901             String interfaceName, DataBroker dataBroker) {
1902         InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1903             .ietf.interfaces.rev140508.interfaces.state.Interface> ifStateId = createInterfaceStateInstanceIdentifier(
1904                 interfaceName);
1905         return MDSALUtil.read(dataBroker, LogicalDatastoreType.OPERATIONAL, ifStateId).orNull();
1906     }
1907
1908     /**
1909      * Creates the interface state instance identifier.
1910      *
1911      * @param interfaceName
1912      *            the interface name
1913      * @return the instance identifier
1914      */
1915     public static InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1916         .ietf.interfaces.rev140508.interfaces.state.Interface> createInterfaceStateInstanceIdentifier(
1917             String interfaceName) {
1918         InstanceIdentifierBuilder<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1919             .ietf.interfaces.rev140508.interfaces.state.Interface> idBuilder = InstanceIdentifier
1920                 .builder(InterfacesState.class)
1921                 .child(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1922                         .ietf.interfaces.rev140508.interfaces.state.Interface.class,
1923                         new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1924                             .ietf.interfaces.rev140508.interfaces.state.InterfaceKey(
1925                                 interfaceName));
1926         return idBuilder.build();
1927     }
1928
1929     public static CheckedFuture<Void, TransactionCommitFailedException> waitForTransactionToComplete(
1930             WriteTransaction tx) {
1931         CheckedFuture<Void, TransactionCommitFailedException> futures = tx.submit();
1932         try {
1933             futures.get();
1934         } catch (InterruptedException | ExecutionException e) {
1935             LOG.error("Error writing to datastore {}", e);
1936         }
1937         return futures;
1938     }
1939
1940     public static boolean isVxlanNetwork(DataBroker broker, String elanInstanceName) {
1941         ElanInstance elanInstance = getElanInstanceByName(broker, elanInstanceName);
1942         return (elanInstance != null && isVxlan(elanInstance));
1943     }
1944
1945     public static boolean isVxlan(ElanInstance elanInstance) {
1946         return elanInstance != null && elanInstance.getSegmentType() != null
1947                 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
1948                 && elanInstance.getSegmentationId() != null && elanInstance.getSegmentationId() != 0;
1949     }
1950
1951     private static boolean isVxlanSegment(ElanInstance elanInstance) {
1952         if (elanInstance != null) {
1953             List<ElanSegments> elanSegments = elanInstance.getElanSegments();
1954             if (elanSegments != null) {
1955                 for (ElanSegments segment : elanSegments) {
1956                     if (segment != null && segment.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
1957                             && segment.getSegmentationId() != null
1958                             && segment.getSegmentationId().longValue() != 0) {
1959                         return true;
1960                     }
1961                 }
1962             }
1963         }
1964         return false;
1965     }
1966
1967     public static boolean isVxlanNetworkOrVxlanSegment(ElanInstance elanInstance) {
1968         return isVxlan(elanInstance) || isVxlanSegment(elanInstance);
1969     }
1970
1971     public static Long getVxlanSegmentationId(ElanInstance elanInstance) {
1972         Long segmentationId = 0L;
1973
1974         if (elanInstance != null && elanInstance.getSegmentType() != null
1975                 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
1976                 && elanInstance.getSegmentationId() != null && elanInstance.getSegmentationId().longValue() != 0) {
1977             segmentationId = elanInstance.getSegmentationId();
1978         } else {
1979             for (ElanSegments segment: elanInstance.getElanSegments()) {
1980                 if (segment != null && segment.getSegmentType().isAssignableFrom(SegmentTypeVxlan.class)
1981                     && segment.getSegmentationId() != null
1982                     && segment.getSegmentationId().longValue() != 0) {
1983                     segmentationId = segment.getSegmentationId();
1984                 }
1985             }
1986         }
1987         return segmentationId;
1988     }
1989
1990     public static boolean isVlan(ElanInstance elanInstance) {
1991         return elanInstance != null && elanInstance.getSegmentType() != null
1992                 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeVlan.class)
1993                 && elanInstance.getSegmentationId() != null && elanInstance.getSegmentationId() != 0;
1994     }
1995
1996     public static boolean isFlat(ElanInstance elanInstance) {
1997         return elanInstance != null && elanInstance.getSegmentType() != null
1998                 && elanInstance.getSegmentType().isAssignableFrom(SegmentTypeFlat.class);
1999     }
2000
2001     public void handleDmacRedirectToDispatcherFlows(Long elanTag, String displayName,
2002             String macAddress, int addOrRemove, List<BigInteger> dpnIds) {
2003         for (BigInteger dpId : dpnIds) {
2004             if (addOrRemove == NwConstants.ADD_FLOW) {
2005                 WriteTransaction writeTx = broker.newWriteOnlyTransaction();
2006                 mdsalManager.addFlowToTx(buildDmacRedirectToDispatcherFlow(dpId, macAddress, displayName, elanTag),
2007                         writeTx);
2008                 writeTx.submit();
2009             } else {
2010                 String flowId = getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, macAddress, elanTag);
2011                 mdsalManager.removeFlow(dpId, MDSALUtil.buildFlow(NwConstants.ELAN_DMAC_TABLE, flowId));
2012             }
2013         }
2014     }
2015
2016     public static FlowEntity buildDmacRedirectToDispatcherFlow(BigInteger dpId, String dstMacAddress,
2017             String displayName, long elanTag) {
2018         List<MatchInfo> matches = new ArrayList<>();
2019         matches.add(new MatchMetadata(getElanMetadataLabel(elanTag), MetaDataUtil.METADATA_MASK_SERVICE));
2020         matches.add(new MatchEthernetDestination(new MacAddress(dstMacAddress)));
2021         List<InstructionInfo> instructions = new ArrayList<>();
2022         List<ActionInfo> actions = new ArrayList<>();
2023         actions.add(new ActionNxResubmit(NwConstants.LPORT_DISPATCHER_TABLE));
2024
2025         instructions.add(new InstructionApplyActions(actions));
2026         String flowId = getKnownDynamicmacFlowRef(NwConstants.ELAN_DMAC_TABLE, dpId, dstMacAddress, elanTag);
2027         FlowEntity flow  = MDSALUtil.buildFlowEntity(dpId, NwConstants.ELAN_DMAC_TABLE, flowId, 20, displayName, 0, 0,
2028                 ElanConstants.COOKIE_ELAN_KNOWN_DMAC.add(BigInteger.valueOf(elanTag)),
2029                 matches, instructions);
2030         return flow;
2031     }
2032
2033     /**
2034      * Add Mac Address to ElanInterfaceForwardingEntries and ElanForwardingTables
2035      * Install SMAC and DMAC flows.
2036      */
2037     public void addMacEntryToDsAndSetupFlows(IInterfaceManager interfaceManager, String interfaceName,
2038             String macAddress, String elanName, WriteTransaction tx, WriteTransaction flowWritetx, int macTimeOut)
2039             throws ElanException {
2040         LOG.trace("Adding mac address {} and interface name {} to ElanInterfaceForwardingEntries and "
2041             + "ElanForwardingTables DS", macAddress, interfaceName);
2042         BigInteger timeStamp = new BigInteger(String.valueOf(System.currentTimeMillis()));
2043         PhysAddress physAddress = new PhysAddress(macAddress);
2044         MacEntry macEntry = new MacEntryBuilder().setInterface(interfaceName).setMacAddress(physAddress)
2045                 .setKey(new MacEntryKey(physAddress)).setControllerLearnedForwardingEntryTimestamp(timeStamp)
2046                 .setIsStaticAddress(false).build();
2047         InstanceIdentifier<MacEntry> macEntryId = ElanUtils
2048                 .getInterfaceMacEntriesIdentifierOperationalDataPath(interfaceName, physAddress);
2049         tx.put(LogicalDatastoreType.OPERATIONAL, macEntryId, macEntry);
2050         InstanceIdentifier<MacEntry> elanMacEntryId = ElanUtils.getMacEntryOperationalDataPath(elanName, physAddress);
2051         tx.put(LogicalDatastoreType.OPERATIONAL, elanMacEntryId, macEntry);
2052         ElanInstance elanInstance = ElanUtils.getElanInstanceByName(broker, elanName);
2053         setupMacFlows(elanInstance, interfaceManager.getInterfaceInfo(interfaceName), macTimeOut, macAddress, true,
2054                 flowWritetx);
2055     }
2056
2057     /**
2058      * Remove Mac Address from ElanInterfaceForwardingEntries and ElanForwardingTables
2059      * Remove SMAC and DMAC flows.
2060      */
2061     public void deleteMacEntryFromDsAndRemoveFlows(IInterfaceManager interfaceManager, String interfaceName,
2062             String macAddress, String elanName, WriteTransaction tx, WriteTransaction deleteFlowTx) {
2063         LOG.trace("Deleting mac address {} and interface name {} from ElanInterfaceForwardingEntries "
2064                 + "and ElanForwardingTables DS", macAddress, interfaceName);
2065         PhysAddress physAddress = new PhysAddress(macAddress);
2066         MacEntry macEntry = getInterfaceMacEntriesOperationalDataPath(interfaceName, physAddress);
2067         InterfaceInfo interfaceInfo = interfaceManager.getInterfaceInfo(interfaceName);
2068         if (macEntry != null && interfaceInfo != null) {
2069             deleteMacFlows(ElanUtils.getElanInstanceByName(broker, elanName), interfaceInfo, macEntry, deleteFlowTx);
2070         }
2071         tx.delete(LogicalDatastoreType.OPERATIONAL,
2072                 ElanUtils.getInterfaceMacEntriesIdentifierOperationalDataPath(interfaceName, physAddress));
2073         tx.delete(LogicalDatastoreType.OPERATIONAL,
2074                 ElanUtils.getMacEntryOperationalDataPath(elanName, physAddress));
2075     }
2076
2077     public String getExternalElanInterface(String elanInstanceName, BigInteger dpnId) {
2078         DpnInterfaces dpnInterfaces = getElanInterfaceInfoByElanDpn(elanInstanceName, dpnId);
2079         if (dpnInterfaces == null || dpnInterfaces.getInterfaces() == null) {
2080             LOG.trace("Elan {} does not have interfaces in DPN {}", elanInstanceName, dpnId);
2081             return null;
2082         }
2083
2084         for (String dpnInterface : dpnInterfaces.getInterfaces()) {
2085             if (interfaceManager.isExternalInterface(dpnInterface)) {
2086                 return dpnInterface;
2087             }
2088         }
2089
2090         LOG.trace("Elan {} does not have any external interace attached to DPN {}", elanInstanceName, dpnId);
2091         return null;
2092     }
2093
2094     public static String getElanMacDPNKey(long elanTag, String macAddress, BigInteger dpnId) {
2095         String elanMacDmacDpnKey = "MAC-" + macAddress + " ELAN_TAG-" + elanTag + "DPN_ID-" + dpnId;
2096         return elanMacDmacDpnKey.intern();
2097     }
2098
2099     public static String getElanMacKey(long elanTag, String macAddress) {
2100         String elanMacKey = "MAC-" + macAddress + " ELAN_TAG-" + elanTag;
2101         return elanMacKey.intern();
2102     }
2103
2104
2105     public static void addToListenableFutureIfTxException(RuntimeException exception,
2106             List<ListenableFuture<Void>> futures) {
2107         Throwable cause = exception.getCause();
2108         if (cause != null && cause instanceof TransactionCommitFailedException) {
2109             futures.add(Futures.immediateFailedCheckedFuture((TransactionCommitFailedException) cause));
2110         }
2111     }
2112
2113     public static List<PhysAddress> getPhysAddress(List<String> macAddress) {
2114         Preconditions.checkNotNull(macAddress, "macAddress cannot be null");
2115         List<PhysAddress> physAddresses = new ArrayList<>();
2116         for (String mac : macAddress) {
2117             physAddresses.add(new PhysAddress(mac));
2118         }
2119         return physAddresses;
2120     }
2121
2122     public static List<StaticMacEntries> getStaticMacEntries(List<String> staticMacAddresses) {
2123         if (isEmpty(staticMacAddresses)) {
2124             return Collections.EMPTY_LIST;
2125         }
2126         StaticMacEntriesBuilder staticMacEntriesBuilder = new StaticMacEntriesBuilder();
2127         List<StaticMacEntries> staticMacEntries = new ArrayList<>();
2128         List<PhysAddress> physAddressList = getPhysAddress(staticMacAddresses);
2129         for (PhysAddress physAddress : physAddressList) {
2130             staticMacEntries.add(staticMacEntriesBuilder.setMacAddress(physAddress).build());
2131         }
2132         return staticMacEntries;
2133     }
2134
2135     public static InstanceIdentifier<StaticMacEntries> getStaticMacEntriesCfgDataPathIdentifier(String interfaceName,
2136                                                                                                 String macAddress) {
2137         return InstanceIdentifier.builder(ElanInterfaces.class)
2138                 .child(ElanInterface.class, new ElanInterfaceKey(interfaceName)).child(StaticMacEntries.class,
2139                         new StaticMacEntriesKey(new PhysAddress(macAddress))).build();
2140     }
2141
2142     public static List<StaticMacEntries> getDeletedEntries(List<StaticMacEntries> originalStaticMacEntries,
2143                                                            List<StaticMacEntries> updatedStaticMacEntries) {
2144         if (isEmpty(originalStaticMacEntries)) {
2145             return Collections.EMPTY_LIST;
2146         }
2147         List<StaticMacEntries> deleted = Lists.newArrayList(originalStaticMacEntries);
2148         if (isNotEmpty(updatedStaticMacEntries)) {
2149             deleted.removeAll(updatedStaticMacEntries);
2150         }
2151         return deleted;
2152     }
2153
2154     public static <T> List<T> diffOf(List<T> orig, List<T> updated) {
2155         if (isEmpty(orig)) {
2156             return Collections.EMPTY_LIST;
2157         }
2158         List<T> diff = Lists.newArrayList(orig);
2159         if (isNotEmpty(updated)) {
2160             diff.removeAll(updated);
2161         }
2162         return diff;
2163     }
2164
2165     public static void segregateToBeDeletedAndAddEntries(List<StaticMacEntries> originalStaticMacEntries,
2166                                                              List<StaticMacEntries> updatedStaticMacEntries) {
2167         if (isNotEmpty(updatedStaticMacEntries)) {
2168             List<StaticMacEntries> existingClonedStaticMacEntries = new ArrayList<>();
2169             if (isNotEmpty(originalStaticMacEntries)) {
2170                 existingClonedStaticMacEntries.addAll(0, originalStaticMacEntries);
2171                 originalStaticMacEntries.removeAll(updatedStaticMacEntries);
2172                 updatedStaticMacEntries.removeAll(existingClonedStaticMacEntries);
2173             }
2174         }
2175     }
2176
2177     public static boolean isEmpty(Collection collection) {
2178         return collection == null || collection.isEmpty();
2179     }
2180
2181     public static boolean isNotEmpty(Collection collection) {
2182         return !isEmpty(collection);
2183     }
2184
2185     public static void setElanInstancToDpnsCache(Map<String, Set<DpnInterfaces>> elanInstancToDpnsCache) {
2186         ElanUtils.elanInstancToDpnsCache = elanInstancToDpnsCache;
2187     }
2188
2189     public static Set<DpnInterfaces> getElanInvolvedDPNsFromCache(String elanName) {
2190         return elanInstancToDpnsCache.get(elanName);
2191     }
2192
2193     public static void addDPNInterfaceToElanInCache(String elanName, DpnInterfaces dpnInterfaces) {
2194         elanInstancToDpnsCache.computeIfAbsent(elanName, key -> new HashSet<>()).add(dpnInterfaces);
2195     }
2196
2197     public static void removeDPNInterfaceFromElanInCache(String elanName, DpnInterfaces dpnInterfaces) {
2198         elanInstancToDpnsCache.computeIfAbsent(elanName, key -> new HashSet<>()).remove(dpnInterfaces);
2199     }
2200
2201     public Optional<IpAddress> getSourceIpAddress(Ethernet ethernet) {
2202         Optional<IpAddress> srcIpAddress = Optional.absent();
2203         if (ethernet.getPayload() == null) {
2204             return srcIpAddress;
2205         }
2206         byte[] ipAddrBytes = null;
2207         if (ethernet.getPayload() instanceof IPv4) {
2208             IPv4 ipv4 = (IPv4) ethernet.getPayload();
2209             ipAddrBytes = Ints.toByteArray(ipv4.getSourceAddress());
2210         } else if (ethernet.getPayload() instanceof ARP) {
2211             ipAddrBytes = ((ARP) ethernet.getPayload()).getSenderProtocolAddress();
2212         }
2213         if (ipAddrBytes != null) {
2214             String ipAddr = NWUtil.toStringIpAddress(ipAddrBytes);
2215             return Optional.of(IpAddressBuilder.getDefaultInstance(ipAddr));
2216         }
2217         return srcIpAddress;
2218     }
2219
2220     public List<MacEntry> getElanMacEntries(String elanName) {
2221         MacTable macTable = getElanMacTable(elanName);
2222         if (macTable == null) {
2223             return Collections.emptyList();
2224         }
2225         return macTable.getMacEntry();
2226     }
2227
2228     public boolean isTunnelInLogicalGroup(String interfaceName, DataBroker broker) {
2229         org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
2230             .ietf.interfaces.rev140508.interfaces.Interface configIface =
2231             interfaceManager.getInterfaceInfoFromConfigDataStore(interfaceName);
2232         IfTunnel ifTunnel = configIface.getAugmentation(IfTunnel.class);
2233         if (ifTunnel != null && ifTunnel.getTunnelInterfaceType().isAssignableFrom(TunnelTypeVxlan.class)) {
2234             ParentRefs refs = configIface.getAugmentation(ParentRefs.class);
2235             if (refs != null && !Strings.isNullOrEmpty(refs.getParentInterface())) {
2236                 return true; //multiple VxLAN tunnels enabled, i.e. only logical tunnel should be treated
2237             }
2238         }
2239         return false;
2240     }
2241
2242     public static void addElanInterfaceToElanInstanceCache(String elanInstanceName, String elanInterfaceName) {
2243         elanInstanceToInterfacesCache.computeIfAbsent(elanInstanceName, key -> new HashSet<>()).add(elanInterfaceName);
2244     }
2245
2246     public static void removeElanInterfaceToElanInstanceCache(String elanInstanceName, String interfaceName) {
2247         Set<String> elanInterfaces = elanInstanceToInterfacesCache.get(elanInstanceName);
2248         if (!elanInterfaces.isEmpty()) {
2249             elanInterfaces.remove(interfaceName);
2250         }
2251     }
2252
2253     public static Set<String> removeAndGetElanInterfaces(String elanInstanceName) {
2254         return elanInstanceToInterfacesCache.remove(elanInstanceName);
2255     }
2256 }