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