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