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