a6623cb37807274cbce4b9fa68c6381548c51699
[netvirt.git] / elanmanager / impl / src / main / java / org / opendaylight / netvirt / elan / l2gw / utils / ElanL2GatewayUtils.java
1 /*
2  * Copyright (c) 2016 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.l2gw.utils;
9
10 import static org.opendaylight.genius.infra.Datastore.CONFIGURATION;
11
12 import com.google.common.base.Optional;
13 import com.google.common.collect.Lists;
14 import com.google.common.util.concurrent.FutureCallback;
15 import com.google.common.util.concurrent.Futures;
16 import com.google.common.util.concurrent.ListenableFuture;
17 import com.google.common.util.concurrent.MoreExecutors;
18 import java.math.BigInteger;
19 import java.util.ArrayList;
20 import java.util.Collection;
21 import java.util.Collections;
22 import java.util.HashSet;
23 import java.util.List;
24 import java.util.Objects;
25 import java.util.Set;
26 import java.util.concurrent.ConcurrentHashMap;
27 import java.util.concurrent.ConcurrentMap;
28 import java.util.concurrent.ExecutionException;
29 import java.util.concurrent.Future;
30 import java.util.concurrent.ScheduledFuture;
31 import java.util.concurrent.TimeUnit;
32 import java.util.function.Function;
33 import java.util.stream.Collectors;
34 import javax.annotation.Nonnull;
35 import javax.annotation.Nullable;
36 import javax.annotation.PreDestroy;
37 import javax.inject.Inject;
38 import javax.inject.Singleton;
39 import org.apache.commons.lang3.tuple.ImmutablePair;
40 import org.apache.commons.lang3.tuple.Pair;
41 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
42 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
43 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
44 import org.opendaylight.genius.datastoreutils.SingleTransactionDataBroker;
45 import org.opendaylight.genius.infra.ManagedNewTransactionRunner;
46 import org.opendaylight.genius.infra.ManagedNewTransactionRunnerImpl;
47 import org.opendaylight.genius.mdsalutil.MDSALUtil;
48 import org.opendaylight.genius.utils.SystemPropertyReader;
49 import org.opendaylight.genius.utils.hwvtep.HwvtepSouthboundConstants;
50 import org.opendaylight.genius.utils.hwvtep.HwvtepSouthboundUtils;
51 import org.opendaylight.genius.utils.hwvtep.HwvtepUtils;
52 import org.opendaylight.infrautils.jobcoordinator.JobCoordinator;
53 import org.opendaylight.infrautils.utils.concurrent.JdkFutures;
54 import org.opendaylight.netvirt.elan.cache.ElanInstanceCache;
55 import org.opendaylight.netvirt.elan.cache.ElanInstanceDpnsCache;
56 import org.opendaylight.netvirt.elan.l2gw.ha.HwvtepHAUtil;
57 import org.opendaylight.netvirt.elan.l2gw.jobs.DeleteL2GwDeviceMacsFromElanJob;
58 import org.opendaylight.netvirt.elan.l2gw.jobs.DeleteLogicalSwitchJob;
59 import org.opendaylight.netvirt.elan.utils.ElanClusterUtils;
60 import org.opendaylight.netvirt.elan.utils.ElanConstants;
61 import org.opendaylight.netvirt.elan.utils.ElanDmacUtils;
62 import org.opendaylight.netvirt.elan.utils.ElanItmUtils;
63 import org.opendaylight.netvirt.elan.utils.ElanUtils;
64 import org.opendaylight.netvirt.elan.utils.Scheduler;
65 import org.opendaylight.netvirt.elanmanager.utils.ElanL2GwCacheUtils;
66 import org.opendaylight.netvirt.neutronvpn.api.l2gw.L2GatewayDevice;
67 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
68 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.Interfaces;
69 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.Interface;
70 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.InterfaceKey;
71 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.IetfYangUtil;
72 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress;
73 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.PhysAddress;
74 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetDpidFromInterfaceInputBuilder;
75 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetDpidFromInterfaceOutput;
76 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.OdlInterfaceRpcService;
77 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rev160406.TransportZones;
78 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rev160406.transport.zones.transport.zone.subnets.DeviceVteps;
79 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.AddL2GwDeviceInputBuilder;
80 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.AddL2GwDeviceOutput;
81 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.ItmRpcService;
82 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.config.rev150710.ElanConfig;
83 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInstances;
84 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan._interface.forwarding.entries.ElanInterfaceMac;
85 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.elan.dpn.interfaces.list.DpnInterfaces;
86 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.forwarding.tables.MacTable;
87 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.ElanInstance;
88 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.elan.instance.ExternalTeps;
89 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.forwarding.entries.MacEntry;
90 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l2gateways.rev150712.l2gateway.attributes.Devices;
91 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.HwvtepGlobalAugmentation;
92 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.HwvtepLogicalSwitchRef;
93 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.HwvtepMacTableGenericAttributes;
94 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.HwvtepNodeName;
95 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.HwvtepPhysicalLocatorAugmentation;
96 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.HwvtepPhysicalLocatorRef;
97 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.hwvtep.global.attributes.LocalUcastMacs;
98 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.hwvtep.global.attributes.LogicalSwitches;
99 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.hwvtep.global.attributes.RemoteMcastMacs;
100 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.hwvtep.global.attributes.RemoteMcastMacsKey;
101 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.hwvtep.global.attributes.RemoteUcastMacs;
102 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.hwvtep.physical.locator.set.attributes.LocatorSet;
103 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.hwvtep.physical.port.attributes.VlanBindings;
104 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
105 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
106 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
107 import org.opendaylight.yangtools.yang.common.RpcResult;
108 import org.slf4j.Logger;
109 import org.slf4j.LoggerFactory;
110
111 /**
112  * It gathers a set of utility methods that handle ELAN configuration in
113  * external Devices (where external means "not-CSS". As of now: TORs).
114  *
115  * <p>It makes use of HwvtepUtils class located under ovsdb/hwvtepsouthbound
116  * project for low-level mdsal operations
117  *
118  * @author eperefr
119  */
120 @Singleton
121 public class ElanL2GatewayUtils {
122     private static final Logger LOG = LoggerFactory.getLogger(ElanL2GatewayUtils.class);
123     private static final int DEFAULT_LOGICAL_SWITCH_DELETE_DELAY_SECS = 20;
124
125     private final DataBroker broker;
126     private final ManagedNewTransactionRunner txRunner;
127     private final ElanDmacUtils elanDmacUtils;
128     private final ElanItmUtils elanItmUtils;
129     private final ElanClusterUtils elanClusterUtils;
130     private final OdlInterfaceRpcService interfaceManagerRpcService;
131     private final JobCoordinator jobCoordinator;
132     private final ElanUtils elanUtils;
133     private final ElanInstanceCache elanInstanceCache;
134     private final ElanInstanceDpnsCache elanInstanceDpnsCache;
135
136     private final ConcurrentMap<Pair<NodeId, String>, ScheduledFuture> logicalSwitchDeletedTasks
137             = new ConcurrentHashMap<>();
138     private final ConcurrentMap<Pair<NodeId, String>, DeleteLogicalSwitchJob> deleteJobs = new ConcurrentHashMap<>();
139     private final Scheduler scheduler;
140     private final ElanConfig elanConfig;
141
142     @Inject
143     public ElanL2GatewayUtils(DataBroker broker, ElanDmacUtils elanDmacUtils, ElanItmUtils elanItmUtils,
144             ElanClusterUtils elanClusterUtils, OdlInterfaceRpcService interfaceManagerRpcService,
145             JobCoordinator jobCoordinator, ElanUtils elanUtils,
146             Scheduler scheduler, ElanConfig elanConfig, ElanInstanceCache elanInstanceCache,
147             ElanInstanceDpnsCache elanInstanceDpnsCache) {
148         this.broker = broker;
149         this.txRunner = new ManagedNewTransactionRunnerImpl(broker);
150         this.elanDmacUtils = elanDmacUtils;
151         this.elanItmUtils = elanItmUtils;
152         this.elanClusterUtils = elanClusterUtils;
153         this.interfaceManagerRpcService = interfaceManagerRpcService;
154         this.jobCoordinator = jobCoordinator;
155         this.elanUtils = elanUtils;
156         this.scheduler = scheduler;
157         this.elanConfig = elanConfig;
158         this.elanInstanceCache = elanInstanceCache;
159         this.elanInstanceDpnsCache = elanInstanceDpnsCache;
160     }
161
162     @PreDestroy
163     public void close() {
164     }
165
166     public long getLogicalSwitchDeleteDelaySecs() {
167         return elanConfig.getL2gwLogicalSwitchDelaySecs() != null
168                 ? elanConfig.getL2gwLogicalSwitchDelaySecs() : DEFAULT_LOGICAL_SWITCH_DELETE_DELAY_SECS;
169     }
170
171     /**
172      * gets the macs addresses for elan interfaces.
173      *
174      * @param lstElanInterfaceNames
175      *            the lst elan interface names
176      * @return the list
177      */
178     public List<PhysAddress> getElanDpnMacsFromInterfaces(Set<String> lstElanInterfaceNames) {
179         List<PhysAddress> result = new ArrayList<>();
180         for (String interfaceName : lstElanInterfaceNames) {
181             ElanInterfaceMac elanInterfaceMac = ElanUtils.getElanInterfaceMacByInterfaceName(broker, interfaceName);
182             if (elanInterfaceMac != null && elanInterfaceMac.getMacEntry() != null) {
183                 for (MacEntry macEntry : elanInterfaceMac.getMacEntry()) {
184                     result.add(macEntry.getMacAddress());
185                 }
186             }
187         }
188         return result;
189     }
190
191     /**
192      * Check if phy locator already exists in remote mcast entry.
193      *
194      * @param nodeId
195      *            the node id
196      * @param remoteMcastMac
197      *            the remote mcast mac
198      * @param expectedPhyLocatorIp
199      *            the expected phy locator ip
200      * @return true, if successful
201      */
202     public static boolean checkIfPhyLocatorAlreadyExistsInRemoteMcastEntry(NodeId nodeId,
203             RemoteMcastMacs remoteMcastMac, IpAddress expectedPhyLocatorIp) {
204         if (remoteMcastMac != null) {
205             HwvtepPhysicalLocatorAugmentation expectedPhyLocatorAug = HwvtepSouthboundUtils
206                     .createHwvtepPhysicalLocatorAugmentation(expectedPhyLocatorIp);
207             HwvtepPhysicalLocatorRef expectedPhyLocRef = new HwvtepPhysicalLocatorRef(
208                     HwvtepSouthboundUtils.createPhysicalLocatorInstanceIdentifier(nodeId, expectedPhyLocatorAug));
209             if (remoteMcastMac.getLocatorSet() != null) {
210                 for (LocatorSet locatorSet : remoteMcastMac.getLocatorSet()) {
211                     if (Objects.equals(locatorSet.getLocatorRef(), expectedPhyLocRef)) {
212                         LOG.trace("matched phyLocRef: {}", expectedPhyLocRef);
213                         return true;
214                     }
215                 }
216             }
217         }
218         return false;
219     }
220
221     /**
222      * Gets the remote mcast mac.
223      *
224      * @param nodeId
225      *            the node id
226      * @param logicalSwitchName
227      *            the logical switch name
228      * @param datastoreType
229      *            the datastore type
230      * @return the remote mcast mac
231      */
232     public RemoteMcastMacs readRemoteMcastMac(NodeId nodeId, String logicalSwitchName,
233             LogicalDatastoreType datastoreType) {
234         InstanceIdentifier<LogicalSwitches> logicalSwitch = HwvtepSouthboundUtils
235                 .createLogicalSwitchesInstanceIdentifier(nodeId, new HwvtepNodeName(logicalSwitchName));
236         RemoteMcastMacsKey remoteMcastMacsKey = new RemoteMcastMacsKey(new HwvtepLogicalSwitchRef(logicalSwitch),
237                 new MacAddress(ElanConstants.UNKNOWN_DMAC));
238         return HwvtepUtils.getRemoteMcastMac(broker, datastoreType, nodeId, remoteMcastMacsKey);
239     }
240
241     /**
242      * Removes the given MAC Addresses from all the External Devices belonging
243      * to the specified ELAN.
244      *
245      * @param elanInstance
246      *            the elan instance
247      * @param macAddresses
248      *            the mac addresses
249      */
250     public void removeMacsFromElanExternalDevices(ElanInstance elanInstance, List<PhysAddress> macAddresses) {
251         ConcurrentMap<String, L2GatewayDevice> elanL2GwDevices = ElanL2GwCacheUtils
252                 .getInvolvedL2GwDevices(elanInstance.getElanInstanceName());
253         for (L2GatewayDevice l2GatewayDevice : elanL2GwDevices.values()) {
254             removeRemoteUcastMacsFromExternalDevice(l2GatewayDevice.getHwvtepNodeId(),
255                     elanInstance.getElanInstanceName(), macAddresses);
256         }
257     }
258
259     /**
260      * Removes the given MAC Addresses from the specified External Device.
261      *
262      * @param deviceNodeId
263      *            the device node id
264      * @param macAddresses
265      *            the mac addresses
266      * @return the listenable future
267      */
268     private ListenableFuture<Void> removeRemoteUcastMacsFromExternalDevice(String deviceNodeId,
269             String logicalSwitchName, List<PhysAddress> macAddresses) {
270         NodeId nodeId = new NodeId(deviceNodeId);
271
272         // TODO (eperefr)
273         List<MacAddress> lstMac = macAddresses.stream().filter(Objects::nonNull).map(
274             physAddress -> new MacAddress(physAddress.getValue())).collect(Collectors.toList());
275         return HwvtepUtils.deleteRemoteUcastMacs(broker, nodeId, logicalSwitchName, lstMac);
276     }
277
278     /**
279      * Install external device local macs in dpn.
280      *
281      * @param dpnId
282      *            the dpn id
283      * @param l2gwDeviceNodeId
284      *            the l2gw device node id
285      * @param elan
286      *            the elan
287      * @param interfaceName
288      *            the interface name
289      */
290     public void installL2gwDeviceMacsInDpn(BigInteger dpnId, NodeId l2gwDeviceNodeId, ElanInstance elan,
291             String interfaceName) {
292         L2GatewayDevice l2gwDevice = ElanL2GwCacheUtils.getL2GatewayDeviceFromCache(elan.getElanInstanceName(),
293                 l2gwDeviceNodeId.getValue());
294         if (l2gwDevice == null) {
295             LOG.debug("L2 gw device not found in elan cache for device name {}", l2gwDeviceNodeId.getValue());
296             return;
297         }
298
299         installDmacFlowsOnDpn(dpnId, l2gwDevice, elan, interfaceName);
300     }
301
302     /**
303      * Install dmac flows on dpn.
304      *
305      * @param dpnId
306      *            the dpn id
307      * @param l2gwDevice
308      *            the l2gw device
309      * @param elan
310      *            the elan
311      * @param interfaceName
312      *            the interface name
313      */
314     public void installDmacFlowsOnDpn(BigInteger dpnId, L2GatewayDevice l2gwDevice, ElanInstance elan,
315             String interfaceName) {
316         String elanName = elan.getElanInstanceName();
317
318         Collection<LocalUcastMacs> l2gwDeviceLocalMacs = l2gwDevice.getUcastLocalMacs();
319         if (!l2gwDeviceLocalMacs.isEmpty()) {
320             for (LocalUcastMacs localUcastMac : l2gwDeviceLocalMacs) {
321                 elanDmacUtils.installDmacFlowsToExternalRemoteMacInBatch(dpnId, l2gwDevice.getHwvtepNodeId(),
322                         elan.getElanTag(), ElanUtils.getVxlanSegmentationId(elan),
323                         localUcastMac.getMacEntryKey().getValue(), elanName, interfaceName);
324             }
325             LOG.debug("Installing L2gw device [{}] local macs [size: {}] in dpn [{}] for elan [{}]",
326                     l2gwDevice.getHwvtepNodeId(), l2gwDeviceLocalMacs.size(), dpnId, elanName);
327         }
328     }
329
330     /**
331      * Install elan l2gw devices local macs in dpn.
332      *
333      * @param dpnId
334      *            the dpn id
335      * @param elan
336      *            the elan
337      * @param interfaceName
338      *            the interface name
339      */
340     public void installElanL2gwDevicesLocalMacsInDpn(BigInteger dpnId, ElanInstance elan, String interfaceName) {
341         ConcurrentMap<String, L2GatewayDevice> elanL2GwDevicesFromCache = ElanL2GwCacheUtils
342                 .getInvolvedL2GwDevices(elan.getElanInstanceName());
343         if (elanL2GwDevicesFromCache != null) {
344             for (L2GatewayDevice l2gwDevice : elanL2GwDevicesFromCache.values()) {
345                 installDmacFlowsOnDpn(dpnId, l2gwDevice, elan, interfaceName);
346             }
347         } else {
348             LOG.debug("No Elan l2 gateway devices in cache for [{}] ", elan.getElanInstanceName());
349         }
350     }
351
352     public void installL2GwUcastMacInElan(final ElanInstance elan, final L2GatewayDevice extL2GwDevice,
353             final String macToBeAdded, final LocalUcastMacs localUcastMacs, @Nullable String interfaceName) {
354         final String extDeviceNodeId = extL2GwDevice.getHwvtepNodeId();
355         final String elanInstanceName = elan.getElanInstanceName();
356         final Collection<DpnInterfaces> elanDpns = getElanDpns(elanInstanceName);
357         ConcurrentMap<String, L2GatewayDevice> elanL2GwDevices = ElanL2GwCacheUtils
358                 .getInvolvedL2GwDevices(elanInstanceName);
359
360         // Retrieve all participating DPNs in this Elan. Populate this MAC in
361         // DMAC table.
362         // Looping through all DPNs in order to add/remove mac flows in their
363         // DMAC table
364         if (elanDpns.size() > 0 || elanL2GwDevices.values().size() > 0) {
365             String jobKey = elanInstanceName + ":" + macToBeAdded;
366             IpAddress extL2GwDeviceTepIp = extL2GwDevice.getTunnelIp();
367             List<PhysAddress> macList = Lists.newArrayList(new PhysAddress(macToBeAdded));
368
369             elanClusterUtils.runOnlyInOwnerNode(jobKey, "install l2gw macs in dmac table", () -> {
370                 if (doesLocalUcastMacExistsInCache(extL2GwDevice, localUcastMacs)) {
371                     List<ListenableFuture<Void>> futures = new ArrayList<>();
372                     for (DpnInterfaces elanDpn : elanDpns) {
373                         futures.addAll(elanDmacUtils.installDmacFlowsToExternalRemoteMacInBatch(elanDpn.getDpId(),
374                                 extDeviceNodeId, elan.getElanTag(), ElanUtils.getVxlanSegmentationId(elan),
375                                 macToBeAdded, elanInstanceName, interfaceName));
376                     }
377                     for (L2GatewayDevice otherDevice : elanL2GwDevices.values()) {
378                         if (!otherDevice.getHwvtepNodeId().equals(extDeviceNodeId)
379                                 && !areMLAGDevices(extL2GwDevice, otherDevice)) {
380                             final String hwvtepId = otherDevice.getHwvtepNodeId();
381                             final String logicalSwitchName = elanInstanceName;
382                             futures.add(HwvtepUtils.installUcastMacs(
383                                     broker, hwvtepId, macList, logicalSwitchName, extL2GwDeviceTepIp));
384                         }
385                     }
386                     return futures;
387                 } else {
388                     LOG.trace("Skipping install of dmac flows for mac {} as it is not found in cache",
389                             macToBeAdded);
390                 }
391                 return Collections.emptyList();
392             });
393         }
394     }
395
396     /**
397      * Does local ucast mac exists in cache.
398      *
399      * @param elanL2GwDevice
400      *            the elan L2 Gw device
401      * @param macAddress
402      *            the mac address to be verified
403      * @return true, if successful
404      */
405     private static boolean doesLocalUcastMacExistsInCache(L2GatewayDevice elanL2GwDevice, LocalUcastMacs macAddress) {
406         return elanL2GwDevice.containsUcastMac(macAddress);
407     }
408
409     /**
410      * Uninstall l2gw macs from other l2gw devices in the elanName provided.
411      * @param elanName - Elan Name for which other l2gw devices will be scanned.
412      * @param l2GwDevice - l2gwDevice whose macs are required to be cleared from other devices.
413      * @param macAddresses - Mac address to be cleared.
414      */
415     public void unInstallL2GwUcastMacFromL2gwDevices(final String elanName,
416                                                      final L2GatewayDevice l2GwDevice,
417                                                      final Collection<MacAddress> macAddresses) {
418         if (macAddresses == null || macAddresses.isEmpty()) {
419             return;
420         }
421
422         if (elanName == null) {
423             return;
424         }
425
426         DeleteL2GwDeviceMacsFromElanJob job = new DeleteL2GwDeviceMacsFromElanJob(elanName, l2GwDevice,
427                 macAddresses);
428         elanClusterUtils.runOnlyInOwnerNode(job.getJobKey(), "delete remote ucast macs in l2gw devices", job);
429     }
430
431     /**
432      * Uninstall l2gw macs from other DPNs in the elan instance provided.
433      * @param elan - Elan Instance for which other DPNs will be scanned.
434      * @param l2GwDevice - l2gwDevice whose macs are required to be cleared from other devices.
435      * @param macAddresses - Mac address to be cleared.
436      */
437     public void unInstallL2GwUcastMacFromElanDpns(final ElanInstance elan, final L2GatewayDevice l2GwDevice,
438                                                   final Collection<MacAddress> macAddresses) {
439         if (macAddresses == null || macAddresses.isEmpty()) {
440             return;
441         }
442         if (elan == null || elan.getElanInstanceName() == null) {
443             LOG.error("Could not delete l2gw ucast macs, Failed to find the elan for device {}",
444                     l2GwDevice.getHwvtepNodeId());
445             return;
446         }
447
448         final Collection<DpnInterfaces> elanDpns = getElanDpns(elan.getElanInstanceName());
449
450         // Retrieve all participating DPNs in this Elan. Populate this MAC in
451         // DMAC table. Looping through all DPNs in order to add/remove mac flows
452         // in their DMAC table
453         List<ListenableFuture<Void>> result = new ArrayList<>();
454         for (final MacAddress mac : macAddresses) {
455             elanClusterUtils.runOnlyInOwnerNode(elan.getElanInstanceName() + ":" + mac.getValue(),
456                     "delete remote ucast macs in elan DPNs", () -> {
457                     for (DpnInterfaces elanDpn : elanDpns) {
458                         BigInteger dpnId = elanDpn.getDpId();
459                         result.addAll(elanDmacUtils.deleteDmacFlowsToExternalMac(elan.getElanTag(), dpnId,
460                                 l2GwDevice.getHwvtepNodeId(),
461                                 IetfYangUtil.INSTANCE.canonizeMacAddress(mac).getValue()));
462                     }
463                     return result;
464                 });
465         }
466     }
467
468     /**
469      * Delete elan l2 gateway devices ucast local macs from dpn.
470      *
471      * @param elanName
472      *            the elan name
473      * @param dpnId
474      *            the dpn id
475      */
476     public void deleteElanL2GwDevicesUcastLocalMacsFromDpn(final String elanName, final BigInteger dpnId) {
477         ConcurrentMap<String, L2GatewayDevice> elanL2GwDevices = ElanL2GwCacheUtils.getInvolvedL2GwDevices(elanName);
478         if (elanL2GwDevices == null || elanL2GwDevices.isEmpty()) {
479             LOG.trace("No L2 gateway devices in Elan [{}] cache.", elanName);
480             return;
481         }
482         final ElanInstance elan = elanInstanceCache.get(elanName).orNull();
483         if (elan == null) {
484             LOG.error("Could not find Elan by name: {}", elanName);
485             return;
486         }
487         LOG.info("Deleting Elan [{}] L2GatewayDevices UcastLocalMacs from Dpn [{}]", elanName, dpnId);
488
489         final Long elanTag = elan.getElanTag();
490         for (final L2GatewayDevice l2GwDevice : elanL2GwDevices.values()) {
491             getL2GwDeviceLocalMacsAndRunCallback(elan.getElanInstanceName(), l2GwDevice, (localMacs) -> {
492                 for (MacAddress mac : localMacs) {
493                     String jobKey = elanName + ":" + mac.getValue();
494                     elanClusterUtils.runOnlyInOwnerNode(jobKey,
495                         () -> elanDmacUtils.deleteDmacFlowsToExternalMac(elanTag, dpnId,
496                                 l2GwDevice.getHwvtepNodeId(), mac.getValue()));
497                 }
498                 return null;
499             });
500         }
501     }
502
503     public void getL2GwDeviceLocalMacsAndRunCallback(String elanName, L2GatewayDevice l2gwDevice,
504                                                      Function<Collection<MacAddress>, Void> function) {
505         if (l2gwDevice == null) {
506             return;
507         }
508         Set<MacAddress> macs = new HashSet<>();
509         Collection<LocalUcastMacs> lstUcastLocalMacs = l2gwDevice.getUcastLocalMacs();
510         if (!lstUcastLocalMacs.isEmpty()) {
511             macs.addAll(lstUcastLocalMacs.stream().filter(Objects::nonNull)
512                     .map(mac -> new MacAddress(mac.getMacEntryKey().getValue().toLowerCase()))
513                     .collect(Collectors.toList()));
514         }
515
516         InstanceIdentifier<Node> nodeIid = HwvtepSouthboundUtils.createInstanceIdentifier(
517                 new NodeId(l2gwDevice.getHwvtepNodeId()));
518         Futures.addCallback(broker.newReadOnlyTransaction().read(LogicalDatastoreType.CONFIGURATION, nodeIid),
519                 new FutureCallback<Optional<Node>>() {
520                     @Override
521                     public void onSuccess(Optional<Node> configNode) {
522                         if (configNode != null && configNode.isPresent()) {
523                             HwvtepGlobalAugmentation augmentation = configNode.get().augmentation(
524                                     HwvtepGlobalAugmentation.class);
525                             if (augmentation != null && augmentation.getLocalUcastMacs() != null) {
526                                 macs.addAll(augmentation.getLocalUcastMacs().stream()
527                                         .filter(mac -> getLogicalSwitchName(mac).equals(elanName))
528                                         .map(HwvtepMacTableGenericAttributes::getMacEntryKey)
529                                         .collect(Collectors.toSet()));
530                             }
531                             function.apply(macs);
532                         }
533                     }
534
535                     @Override
536                     public void onFailure(Throwable throwable) {
537                         LOG.error("Failed to read config topology node {}", nodeIid);
538                     }
539                 }, MoreExecutors.directExecutor());
540     }
541
542     private String getLogicalSwitchName(LocalUcastMacs mac) {
543         return ((InstanceIdentifier<LogicalSwitches>)mac.getLogicalSwitchRef().getValue())
544                 .firstKeyOf(LogicalSwitches.class).getHwvtepNodeName().getValue();
545     }
546
547     /**
548      * Delete elan macs from L2 gateway device.<br>
549      * This includes deleting ELAN mac table entries plus external device
550      * UcastLocalMacs which are part of the same ELAN.
551      *
552      * @param hwvtepNodeId
553      *            the hwvtepNodeId
554      * @param elanName
555      *            the elan name
556      * @return the listenable future
557      */
558     public ListenableFuture<Void> deleteElanMacsFromL2GatewayDevice(String hwvtepNodeId, String elanName) {
559         String logicalSwitch = getLogicalSwitchFromElan(elanName);
560
561         List<MacAddress> lstElanMacs = getRemoteUcastMacs(new NodeId(hwvtepNodeId), logicalSwitch,
562                 LogicalDatastoreType.CONFIGURATION);
563         ListenableFuture<Void> future = HwvtepUtils.deleteRemoteUcastMacs(broker, new NodeId(hwvtepNodeId),
564                 logicalSwitch, lstElanMacs);
565
566         Futures.addCallback(future, new FutureCallback<Void>() {
567             @Override
568             public void onSuccess(Void noarg) {
569                 LOG.trace("Successful in batch deletion of elan [{}] macs from l2gw device [{}]", elanName,
570                         hwvtepNodeId);
571             }
572
573             @Override
574             public void onFailure(Throwable error) {
575                 LOG.warn("Failed during batch delete of elan {} macs from l2gw device {}. "
576                         + "Retrying with sequential deletes.", elanName, hwvtepNodeId, error);
577                 if (lstElanMacs != null && !lstElanMacs.isEmpty()) {
578                     for (MacAddress mac : lstElanMacs) {
579                         HwvtepUtils.deleteRemoteUcastMac(broker, new NodeId(hwvtepNodeId), logicalSwitch, mac);
580                     }
581                 }
582             }
583         }, MoreExecutors.directExecutor());
584
585         if (LOG.isDebugEnabled()) {
586             List<String> elanMacs = lstElanMacs.stream().map(MacAddress::getValue).collect(Collectors.toList());
587             LOG.debug("Deleting elan [{}] macs from node [{}]. Deleted macs = {}", elanName, hwvtepNodeId, elanMacs);
588         }
589         return future;
590     }
591
592     /**
593      * Gets the remote ucast macs from hwvtep node filtering based on logical
594      * switch.
595      *
596      * @param hwvtepNodeId
597      *            the hwvtep node id
598      * @param logicalSwitch
599      *            the logical switch
600      * @param datastoreType
601      *            the datastore type
602      * @return the remote ucast macs
603      */
604     public List<MacAddress> getRemoteUcastMacs(NodeId hwvtepNodeId, String logicalSwitch,
605             LogicalDatastoreType datastoreType) {
606         List<MacAddress> lstMacs = Collections.emptyList();
607         Node hwvtepNode = HwvtepUtils.getHwVtepNode(broker, datastoreType, hwvtepNodeId);
608         if (hwvtepNode != null) {
609             List<RemoteUcastMacs> remoteUcastMacs = hwvtepNode.augmentation(HwvtepGlobalAugmentation.class)
610                     .getRemoteUcastMacs();
611             if (remoteUcastMacs != null && !remoteUcastMacs.isEmpty()) {
612                 // Filtering remoteUcastMacs based on the logical switch and
613                 // forming a list of MacAddress
614                 lstMacs = remoteUcastMacs.stream()
615                         .filter(mac -> logicalSwitch.equals(mac.getLogicalSwitchRef().getValue()
616                                 .firstKeyOf(LogicalSwitches.class).getHwvtepNodeName().getValue()))
617                         .map(HwvtepMacTableGenericAttributes::getMacEntryKey).collect(Collectors.toList());
618             }
619         }
620         return lstMacs;
621     }
622
623     /**
624      * Install ELAN macs in L2 Gateway device.<br>
625      * This includes installing ELAN mac table entries plus external device
626      * UcastLocalMacs which are part of the same ELAN.
627      *
628      * @param elanName
629      *            the elan name
630      * @param l2GatewayDevice
631      *            the l2 gateway device which has to be configured
632      * @return the listenable future
633      */
634     public ListenableFuture<Void> installElanMacsInL2GatewayDevice(String elanName,
635             L2GatewayDevice l2GatewayDevice) {
636         String logicalSwitchName = getLogicalSwitchFromElan(elanName);
637         NodeId hwVtepNodeId = new NodeId(l2GatewayDevice.getHwvtepNodeId());
638
639         List<RemoteUcastMacs> lstL2GatewayDevicesMacs = getOtherDevicesMacs(elanName, l2GatewayDevice, hwVtepNodeId,
640                 logicalSwitchName);
641         List<RemoteUcastMacs> lstElanMacTableEntries = getElanMacTableEntriesMacs(elanName,
642                 hwVtepNodeId, logicalSwitchName);
643
644         List<RemoteUcastMacs> lstRemoteUcastMacs = new ArrayList<>(lstL2GatewayDevicesMacs);
645         lstRemoteUcastMacs.addAll(lstElanMacTableEntries);
646
647         ListenableFuture<Void> future = HwvtepUtils.addRemoteUcastMacs(broker, hwVtepNodeId, lstRemoteUcastMacs);
648
649         LOG.info("Added RemoteUcastMacs entries [{}] in config DS. NodeID: {}, LogicalSwitch: {}",
650                 lstRemoteUcastMacs.size(), hwVtepNodeId.getValue(), logicalSwitchName);
651         return future;
652     }
653
654     /**
655      * Gets the l2 gateway devices ucast local macs as remote ucast macs.
656      *
657      * @param elanName
658      *            the elan name
659      * @param l2GatewayDeviceToBeConfigured
660      *            the l2 gateway device to be configured
661      * @param hwVtepNodeId
662      *            the hw vtep node Id to be configured
663      * @param logicalSwitchName
664      *            the logical switch name
665      * @return the l2 gateway devices macs as remote ucast macs
666      */
667     public static List<RemoteUcastMacs> getOtherDevicesMacs(String elanName,
668             L2GatewayDevice l2GatewayDeviceToBeConfigured, NodeId hwVtepNodeId, String logicalSwitchName) {
669         List<RemoteUcastMacs> lstRemoteUcastMacs = new ArrayList<>();
670         ConcurrentMap<String, L2GatewayDevice> elanL2GwDevicesFromCache = ElanL2GwCacheUtils
671                 .getInvolvedL2GwDevices(elanName);
672
673         if (elanL2GwDevicesFromCache != null) {
674             for (L2GatewayDevice otherDevice : elanL2GwDevicesFromCache.values()) {
675                 if (l2GatewayDeviceToBeConfigured.getHwvtepNodeId().equals(otherDevice.getHwvtepNodeId())) {
676                     continue;
677                 }
678                 if (!areMLAGDevices(l2GatewayDeviceToBeConfigured, otherDevice)) {
679                     for (LocalUcastMacs localUcastMac : otherDevice.getUcastLocalMacs()) {
680                         HwvtepPhysicalLocatorAugmentation physLocatorAug = HwvtepSouthboundUtils
681                                 .createHwvtepPhysicalLocatorAugmentation(otherDevice.getTunnelIp());
682                         RemoteUcastMacs remoteUcastMac = HwvtepSouthboundUtils.createRemoteUcastMac(hwVtepNodeId,
683                             IetfYangUtil.INSTANCE.canonizeMacAddress(localUcastMac.getMacEntryKey()).getValue(),
684                             localUcastMac.getIpaddr(), logicalSwitchName, physLocatorAug);
685                         lstRemoteUcastMacs.add(remoteUcastMac);
686                     }
687                 }
688             }
689         }
690         return lstRemoteUcastMacs;
691     }
692
693     /**
694      * Are MLAG devices.
695      *
696      * @param l2GatewayDevice
697      *            the l2 gateway device
698      * @param otherL2GatewayDevice
699      *            the other l2 gateway device
700      * @return true, if both the specified l2 gateway devices are part of same
701      *         MLAG
702      */
703     public static boolean areMLAGDevices(L2GatewayDevice l2GatewayDevice, L2GatewayDevice otherL2GatewayDevice) {
704         // If tunnel IPs are same, then it is considered to be part of same MLAG
705         return Objects.equals(l2GatewayDevice.getTunnelIp(), otherL2GatewayDevice.getTunnelIp());
706     }
707
708     /**
709      * Gets the elan mac table entries as remote ucast macs. <br>
710      * Note: ELAN MAC table only contains internal switches MAC's. It doesn't
711      * contain external device MAC's.
712      *
713      * @param elanName
714      *            the elan name
715      * @param hwVtepNodeId
716      *            the hw vtep node id
717      * @param logicalSwitchName
718      *            the logical switch name
719      * @return the elan mac table entries as remote ucast macs
720      */
721     public List<RemoteUcastMacs> getElanMacTableEntriesMacs(String elanName,
722             NodeId hwVtepNodeId, String logicalSwitchName) {
723         List<RemoteUcastMacs> lstRemoteUcastMacs = new ArrayList<>();
724
725         MacTable macTable = ElanUtils.getElanMacTable(broker, elanName);
726         if (macTable == null || macTable.getMacEntry() == null || macTable.getMacEntry().isEmpty()) {
727             LOG.trace("MacTable is empty for elan: {}", elanName);
728             return lstRemoteUcastMacs;
729         }
730
731         for (MacEntry macEntry : macTable.getMacEntry()) {
732             BigInteger dpnId = getDpidFromInterface(macEntry.getInterface());
733             if (dpnId == null) {
734                 LOG.error("DPN ID not found for interface {}", macEntry.getInterface());
735                 continue;
736             }
737
738             IpAddress dpnTepIp = elanItmUtils.getSourceDpnTepIp(dpnId, hwVtepNodeId);
739             LOG.trace("Dpn Tep IP: {} for dpnId: {} and nodeId: {}", dpnTepIp, dpnId, hwVtepNodeId.getValue());
740             if (dpnTepIp == null) {
741                 LOG.error("TEP IP not found for dpnId {} and nodeId {}", dpnId, hwVtepNodeId.getValue());
742                 continue;
743             }
744             HwvtepPhysicalLocatorAugmentation physLocatorAug = HwvtepSouthboundUtils
745                     .createHwvtepPhysicalLocatorAugmentation(dpnTepIp);
746             // TODO: Query ARP cache to get IP address corresponding to the
747             // MAC
748             RemoteUcastMacs remoteUcastMac = HwvtepSouthboundUtils.createRemoteUcastMac(hwVtepNodeId,
749                 IetfYangUtil.INSTANCE.canonizePhysAddress(macEntry.getMacAddress()).getValue(), null /*IpAddress*/,
750                     logicalSwitchName, physLocatorAug);
751             lstRemoteUcastMacs.add(remoteUcastMac);
752         }
753         return lstRemoteUcastMacs;
754     }
755
756     /**
757      * Gets the dpid from interface.
758      *
759      * @param interfaceName
760      *            the interface name
761      * @return the dpid from interface
762      */
763     @Nullable
764     public BigInteger getDpidFromInterface(String interfaceName) {
765         BigInteger dpId = null;
766         Future<RpcResult<GetDpidFromInterfaceOutput>> output = interfaceManagerRpcService
767                 .getDpidFromInterface(new GetDpidFromInterfaceInputBuilder().setIntfName(interfaceName).build());
768         try {
769             RpcResult<GetDpidFromInterfaceOutput> rpcResult = output.get();
770             if (rpcResult != null && rpcResult.isSuccessful()) {
771                 dpId = rpcResult.getResult().getDpid();
772             }
773         } catch (InterruptedException | ExecutionException e) {
774             LOG.error("Failed to get the DPN ID for interface {}", interfaceName, e);
775         }
776         return dpId;
777     }
778
779     /**
780      * Update vlan bindings in l2 gateway device.
781      *
782      * @param nodeId
783      *            the node id
784      * @param logicalSwitchName
785      *            the logical switch name
786      * @param hwVtepDevice
787      *            the hardware device
788      * @param defaultVlanId
789      *            the default vlan id
790      * @return the listenable future
791      */
792     public ListenableFuture<Void> updateVlanBindingsInL2GatewayDevice(NodeId nodeId, String logicalSwitchName,
793             Devices hwVtepDevice, Integer defaultVlanId) {
794         if (hwVtepDevice == null || hwVtepDevice.getInterfaces() == null || hwVtepDevice.getInterfaces().isEmpty()) {
795             String errMsg = "HwVtepDevice is null or interfaces are empty.";
796             LOG.error(errMsg);
797             return Futures.immediateFailedFuture(new RuntimeException(errMsg));
798         }
799
800         return txRunner.callWithNewWriteOnlyTransactionAndSubmit(CONFIGURATION, tx -> {
801             for (org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l2gateways.rev150712
802                     .l2gateway.attributes.devices.Interfaces deviceInterface : hwVtepDevice.getInterfaces()) {
803                 //Removed the check for checking terminationPoint present in OP or not
804                 //for coniguring vlan bindings
805                 //As we are not any more dependent on it , plugin takes care of this
806                 // with port reconcilation.
807                 List<VlanBindings> vlanBindings = new ArrayList<>();
808                 if (deviceInterface.getSegmentationIds() != null && !deviceInterface.getSegmentationIds().isEmpty()) {
809                     for (Integer vlanId : deviceInterface.getSegmentationIds()) {
810                         vlanBindings.add(HwvtepSouthboundUtils.createVlanBinding(nodeId, vlanId, logicalSwitchName));
811                     }
812                 } else {
813                     // Use defaultVlanId (specified in L2GatewayConnection) if Vlan
814                     // ID not specified at interface level.
815                     vlanBindings.add(HwvtepSouthboundUtils.createVlanBinding(nodeId, defaultVlanId, logicalSwitchName));
816                 }
817                 HwvtepUtils.mergeVlanBindings(tx, nodeId, hwVtepDevice.getDeviceName(),
818                         deviceInterface.getInterfaceName(), vlanBindings);
819             }
820             LOG.info("Updated Hwvtep VlanBindings in config DS. NodeID: {}, LogicalSwitch: {}", nodeId.getValue(),
821                     logicalSwitchName);
822         });
823     }
824
825     /**
826      * Update vlan bindings in l2 gateway device.
827      *
828      * @param nodeId
829      *            the node id
830      * @param psName
831      *            the physical switch name
832      * @param interfaceName
833      *            the interface in physical switch
834      * @param vlanBindings
835      *            the vlan bindings to be configured
836      * @return the listenable future
837      */
838     public ListenableFuture<Void> updateVlanBindingsInL2GatewayDevice(NodeId nodeId, String psName,
839             String interfaceName, List<VlanBindings> vlanBindings) {
840         return txRunner.callWithNewWriteOnlyTransactionAndSubmit(CONFIGURATION, tx -> {
841             HwvtepUtils.mergeVlanBindings(tx, nodeId, psName, interfaceName, vlanBindings);
842             LOG.info("Updated Hwvtep VlanBindings in config DS. NodeID: {}", nodeId.getValue());
843         });
844     }
845
846     /**
847      * Delete vlan bindings from l2 gateway device.
848      *
849      * @param nodeId
850      *            the node id
851      * @param hwVtepDevice
852      *            the hw vtep device
853      * @param defaultVlanId
854      *            the default vlan id
855      * @return the listenable future
856      */
857     public ListenableFuture<Void> deleteVlanBindingsFromL2GatewayDevice(NodeId nodeId, Devices hwVtepDevice,
858             Integer defaultVlanId) {
859         if (hwVtepDevice == null || hwVtepDevice.getInterfaces() == null || hwVtepDevice.getInterfaces().isEmpty()) {
860             String errMsg = "HwVtepDevice is null or interfaces are empty.";
861             LOG.error(errMsg);
862             return Futures.immediateFailedFuture(new RuntimeException(errMsg));
863         }
864         NodeId physicalSwitchNodeId = HwvtepSouthboundUtils.createManagedNodeId(nodeId, hwVtepDevice.getDeviceName());
865
866         return txRunner.callWithNewWriteOnlyTransactionAndSubmit(CONFIGURATION, tx -> {
867             for (org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l2gateways.rev150712
868                     .l2gateway.attributes.devices.Interfaces deviceInterface : hwVtepDevice.getInterfaces()) {
869                 String phyPortName = deviceInterface.getInterfaceName();
870                 if (deviceInterface.getSegmentationIds() != null && !deviceInterface.getSegmentationIds().isEmpty()) {
871                     for (Integer vlanId : deviceInterface.getSegmentationIds()) {
872                         HwvtepUtils.deleteVlanBinding(tx, physicalSwitchNodeId, phyPortName, vlanId);
873                     }
874                 } else {
875                     // Use defaultVlanId (specified in L2GatewayConnection) if Vlan
876                     // ID not specified at interface level.
877                     HwvtepUtils.deleteVlanBinding(tx, physicalSwitchNodeId, phyPortName, defaultVlanId);
878                 }
879             }
880             LOG.info("Deleted Hwvtep VlanBindings from config DS. NodeID: {}, hwVtepDevice: {}, defaultVlanId: {} ",
881                     nodeId.getValue(), hwVtepDevice, defaultVlanId);
882         });
883     }
884
885     /**
886      * Gets the logical switch name from elan name.
887      *
888      * @param elanName
889      *            the elan name
890      * @return the logical switch from elan name
891      */
892     public static String getLogicalSwitchFromElan(String elanName) {
893         // Assuming logical switch name is same as elan name
894         String logicalSwitchName = elanName;
895         return logicalSwitchName;
896     }
897
898     /**
899      * Gets the l2 gateway connection job key.
900      *
901      * @param logicalSwitchName
902      *            the logical switch name
903      * @return the l2 gateway connection job key
904      */
905     public static String getL2GatewayConnectionJobKey(String logicalSwitchName) {
906         return logicalSwitchName;
907     }
908
909     public static InstanceIdentifier<Interface> getInterfaceIdentifier(InterfaceKey interfaceKey) {
910         InstanceIdentifier.InstanceIdentifierBuilder<Interface> interfaceInstanceIdentifierBuilder = InstanceIdentifier
911                 .builder(Interfaces.class).child(Interface.class, interfaceKey);
912         return interfaceInstanceIdentifierBuilder.build();
913     }
914
915     @Nullable
916     public static Interface getInterfaceFromConfigDS(InterfaceKey interfaceKey, DataBroker dataBroker) {
917         InstanceIdentifier<Interface> interfaceId = getInterfaceIdentifier(interfaceKey);
918         try {
919             return SingleTransactionDataBroker
920                     .syncReadOptional(dataBroker, LogicalDatastoreType.CONFIGURATION, interfaceId).orNull();
921         } catch (ReadFailedException e) {
922             // TODO remove this, and propagate ReadFailedException instead of re-throw RuntimeException
923             LOG.error("getInterfaceFromConfigDS({}) failed", interfaceKey, e);
924             throw new RuntimeException(e);
925         }
926     }
927
928     /**
929      * Delete l2 gateway device ucast local macs from elan.<br>
930      * Deletes macs from internal ELAN nodes and also on rest of external l2
931      * gateway devices which are part of the ELAN.
932      *
933      * @param l2GatewayDevice
934      *            the l2 gateway device whose ucast local macs to be deleted
935      *            from elan
936      * @param elanName
937      *            the elan name
938      */
939     public void deleteL2GwDeviceUcastLocalMacsFromElan(L2GatewayDevice l2GatewayDevice,
940             String elanName) {
941         LOG.info("Deleting L2GatewayDevice [{}] UcastLocalMacs from elan [{}]", l2GatewayDevice.getHwvtepNodeId(),
942                 elanName);
943
944         ElanInstance elan = elanInstanceCache.get(elanName).orNull();
945         if (elan == null) {
946             LOG.error("Could not find Elan by name: {}", elanName);
947             return;
948         }
949
950         Collection<MacAddress> localMacs = getL2GwDeviceLocalMacs(elanName, l2GatewayDevice);
951         unInstallL2GwUcastMacFromL2gwDevices(elanName, l2GatewayDevice, localMacs);
952         unInstallL2GwUcastMacFromElanDpns(elan, l2GatewayDevice, localMacs);
953     }
954
955     public static void createItmTunnels(DataBroker dataBroker, ItmRpcService itmRpcService,
956                                         String hwvtepId, String psName, IpAddress tunnelIp) {
957         AddL2GwDeviceInputBuilder builder = new AddL2GwDeviceInputBuilder();
958         builder.setTopologyId(HwvtepSouthboundConstants.HWVTEP_TOPOLOGY_ID.getValue());
959         builder.setNodeId(HwvtepSouthboundUtils.createManagedNodeId(new NodeId(hwvtepId), psName).getValue());
960         builder.setIpAddress(tunnelIp);
961         try {
962             deleteStaleTunnelsOfHwvtepInITM(dataBroker, itmRpcService, hwvtepId, psName, tunnelIp);
963             RpcResult<AddL2GwDeviceOutput> rpcResult = itmRpcService.addL2GwDevice(builder.build()).get();
964             if (rpcResult.isSuccessful()) {
965                 LOG.info("Created ITM tunnels for {}", hwvtepId);
966             } else {
967                 LOG.error("Failed to create ITM Tunnels: {}", rpcResult.getErrors());
968             }
969         } catch (InterruptedException | ExecutionException e) {
970             LOG.error("RPC to create ITM tunnels failed", e);
971         }
972     }
973
974     private static void deleteStaleTunnelsOfHwvtepInITM(DataBroker dataBroker,
975                                                         ItmRpcService itmRpcService,
976                                                         String globalNodeId,
977                                                         String psName,
978                                                         IpAddress tunnelIp) {
979         try {
980             Optional<TransportZones> tzonesoptional = readTransportZone(dataBroker);
981             if (!tzonesoptional.isPresent() || tzonesoptional.get().getTransportZone() == null) {
982                 return;
983             }
984             String psNodeId = globalNodeId + HwvtepHAUtil.PHYSICALSWITCH + psName;
985             tzonesoptional.get().nonnullTransportZone().stream()
986                 .filter(transportZone -> transportZone.getSubnets() != null)
987                 .flatMap(transportZone -> transportZone.getSubnets().stream())
988                 .filter(subnet -> subnet.getDeviceVteps() != null)
989                 .flatMap(subnet -> subnet.getDeviceVteps().stream())
990                 .filter(deviceVteps -> Objects.equals(getPsName(deviceVteps), psName)) //get device with same ps name
991                 .filter(deviceVteps -> !Objects.equals(psNodeId, deviceVteps.getNodeId())
992                         || !Objects.equals(tunnelIp, deviceVteps.getIpAddress()))//node id or tunnel ip is changed
993                 .forEach(deviceVteps -> deleteStaleL2gwTep(dataBroker, itmRpcService, deviceVteps));
994         } catch (ReadFailedException e) {
995             LOG.error("Failed delete stale tunnels for {}", globalNodeId);
996         }
997     }
998
999     private static Optional<TransportZones> readTransportZone(DataBroker dataBroker) throws ReadFailedException {
1000         return new SingleTransactionDataBroker(dataBroker).syncReadOptional(LogicalDatastoreType.CONFIGURATION,
1001                 InstanceIdentifier.builder(TransportZones.class).build());
1002     }
1003
1004     private static Optional<ElanInstances> readElanInstances(DataBroker dataBroker) throws ReadFailedException {
1005         return new SingleTransactionDataBroker(dataBroker).syncReadOptional(LogicalDatastoreType.CONFIGURATION,
1006                 InstanceIdentifier.builder(ElanInstances.class).build());
1007     }
1008
1009     private static String getPsName(DeviceVteps deviceVteps) {
1010         return HwvtepHAUtil.getPsName(HwvtepHAUtil.convertToInstanceIdentifier(deviceVteps.getNodeId()));
1011     }
1012
1013     private static void deleteStaleL2gwTep(DataBroker dataBroker,
1014                                            ItmRpcService itmRpcService,
1015                                            DeviceVteps deviceVteps) {
1016         String psName = HwvtepHAUtil.getPsName(HwvtepHAUtil.convertToInstanceIdentifier(deviceVteps.getNodeId()));
1017         String globalNodeId = HwvtepHAUtil.convertToGlobalNodeId(deviceVteps.getNodeId());
1018         try {
1019             LOG.info("Deleting stale tep {} ", deviceVteps);
1020             L2GatewayUtils.deleteItmTunnels(itmRpcService, globalNodeId, psName, deviceVteps.getIpAddress());
1021             Optional<ElanInstances> optionalElan = readElanInstances(dataBroker);
1022             if (!optionalElan.isPresent()) {
1023                 return;
1024             }
1025             JdkFutures.addErrorLogging(
1026                 new ManagedNewTransactionRunnerImpl(dataBroker).callWithNewReadWriteTransactionAndSubmit(CONFIGURATION,
1027                     tx -> optionalElan.get().nonnullElanInstance().stream()
1028                         .flatMap(elan -> elan.nonnullExternalTeps().stream()
1029                             .map(externalTep -> ElanL2GatewayMulticastUtils.buildExternalTepPath(
1030                                 elan.getElanInstanceName(), externalTep.getTepIp())))
1031                         .filter(externalTepIid -> Objects.equals(
1032                             deviceVteps.getIpAddress(), externalTepIid.firstKeyOf(ExternalTeps.class).getTepIp()))
1033                         .peek(externalTepIid -> LOG.info("Deleting stale external tep {}", externalTepIid))
1034                         .forEach(tx::delete)), LOG,
1035                 "Failed to delete stale external teps {}", deviceVteps);
1036             Thread.sleep(10000);//TODO remove the sleep currently it waits for interfacemgr to finish the cleanup
1037         } catch (ReadFailedException | InterruptedException e) {
1038             LOG.error("Failed to delete stale l2gw tep {}", deviceVteps, e);
1039         }
1040     }
1041
1042     public void scheduleAddDpnMacInExtDevices(String elanName, BigInteger dpId,
1043             List<PhysAddress> staticMacAddresses) {
1044         ConcurrentMap<String, L2GatewayDevice> elanDevices = ElanL2GwCacheUtils.getInvolvedL2GwDevices(elanName);
1045         for (final L2GatewayDevice externalDevice : elanDevices.values()) {
1046             scheduleAddDpnMacsInExtDevice(elanName, dpId, staticMacAddresses, externalDevice);
1047         }
1048     }
1049
1050     public void scheduleAddDpnMacsInExtDevice(final String elanName, BigInteger dpId,
1051             final List<PhysAddress> staticMacAddresses, final L2GatewayDevice externalDevice) {
1052         NodeId nodeId = new NodeId(externalDevice.getHwvtepNodeId());
1053         final IpAddress dpnTepIp = elanItmUtils.getSourceDpnTepIp(dpId, nodeId);
1054         LOG.trace("Dpn Tep IP: {} for dpnId: {} and nodeId: {}", dpnTepIp, dpId, nodeId);
1055         if (dpnTepIp == null) {
1056             LOG.error("could not install dpn mac in l2gw TEP IP not found for dpnId {} and nodeId {}", dpId, nodeId);
1057             return;
1058         }
1059
1060         //TODO: to  be batched in genius
1061         HwvtepUtils.installUcastMacs(broker, externalDevice.getHwvtepNodeId(), staticMacAddresses, elanName, dpnTepIp);
1062     }
1063
1064     public void scheduleDeleteLogicalSwitch(NodeId hwvtepNodeId, String lsName) {
1065         scheduleDeleteLogicalSwitch(hwvtepNodeId, lsName, false);
1066     }
1067
1068     public void scheduleDeleteLogicalSwitch(final NodeId hwvtepNodeId, final String lsName, final boolean clearUcast) {
1069         final Pair<NodeId, String> nodeIdLogicalSwitchNamePair = new ImmutablePair<>(hwvtepNodeId, lsName);
1070         logicalSwitchDeletedTasks.computeIfAbsent(nodeIdLogicalSwitchNamePair,
1071             (key) -> scheduler.getScheduledExecutorService().schedule(() -> {
1072                 DeleteLogicalSwitchJob deleteLsJob = new DeleteLogicalSwitchJob(broker,
1073                         ElanL2GatewayUtils.this, hwvtepNodeId, lsName, clearUcast);
1074                 jobCoordinator.enqueueJob(deleteLsJob.getJobKey(), deleteLsJob,
1075                         SystemPropertyReader.getDataStoreJobCoordinatorMaxRetries());
1076                 deleteJobs.put(nodeIdLogicalSwitchNamePair, deleteLsJob);
1077                 logicalSwitchDeletedTasks.remove(nodeIdLogicalSwitchNamePair);
1078             }, getLogicalSwitchDeleteDelaySecs(), TimeUnit.SECONDS));
1079     }
1080
1081     public void cancelDeleteLogicalSwitch(final NodeId hwvtepNodeId, final String lsName) {
1082         Pair<NodeId, String> nodeIdLogicalSwitchNamePair = new ImmutablePair<>(hwvtepNodeId, lsName);
1083         ScheduledFuture logicalSwitchDeleteTask = logicalSwitchDeletedTasks.remove(nodeIdLogicalSwitchNamePair);
1084         if (logicalSwitchDeleteTask != null) {
1085             LOG.debug("Delete logical switch {} action on node {} cancelled", lsName, hwvtepNodeId);
1086             logicalSwitchDeleteTask.cancel(true);
1087             DeleteLogicalSwitchJob deleteLogicalSwitchJob = deleteJobs.remove(nodeIdLogicalSwitchNamePair);
1088             if (deleteLogicalSwitchJob != null) {
1089                 deleteLogicalSwitchJob.cancel();
1090             }
1091         }
1092     }
1093
1094     @Nonnull
1095     public Collection<DpnInterfaces> getElanDpns(String elanName) {
1096         Collection<DpnInterfaces> dpnInterfaces = elanInstanceDpnsCache.get(elanName);
1097         if (!dpnInterfaces.isEmpty()) {
1098             return dpnInterfaces;
1099         }
1100
1101         return elanUtils.getElanDPNByName(elanName);
1102     }
1103
1104     /**
1105      * Gets the l2 gw device local macs.
1106      * @param elanName
1107      *            name of the elan
1108      * @param l2gwDevice
1109      *            the l2gw device
1110      * @return the l2 gw device local macs
1111      */
1112     public Collection<MacAddress> getL2GwDeviceLocalMacs(String elanName, L2GatewayDevice l2gwDevice) {
1113         if (l2gwDevice == null) {
1114             return Collections.emptyList();
1115         }
1116         Collection<LocalUcastMacs> lstUcastLocalMacs = l2gwDevice.getUcastLocalMacs();
1117         Set<MacAddress> macs = new HashSet<>();
1118         if (!lstUcastLocalMacs.isEmpty()) {
1119             macs.addAll(lstUcastLocalMacs.stream().filter(Objects::nonNull)
1120                     .map(mac -> new MacAddress(mac.getMacEntryKey().getValue().toLowerCase()))
1121                     .collect(Collectors.toList()));
1122         }
1123         Optional<Node> configNode = MDSALUtil.read(broker, LogicalDatastoreType.CONFIGURATION,
1124                 HwvtepSouthboundUtils.createInstanceIdentifier(new NodeId(l2gwDevice.getHwvtepNodeId())));
1125         if (configNode.isPresent()) {
1126             HwvtepGlobalAugmentation augmentation = configNode.get().augmentation(HwvtepGlobalAugmentation.class);
1127             if (augmentation != null && augmentation.getLocalUcastMacs() != null) {
1128                 macs.addAll(augmentation.getLocalUcastMacs().stream()
1129                         .filter(mac -> getLogicalSwitchName(mac).equals(elanName))
1130                         .map(HwvtepMacTableGenericAttributes::getMacEntryKey)
1131                         .collect(Collectors.toSet()));
1132             }
1133         }
1134         return macs;
1135     }
1136 }