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