2 * Copyright (c) 2016 Ericsson India Global Services Pvt Ltd. and others. All rights reserved.
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
8 package org.opendaylight.netvirt.elan.l2gw.utils;
10 import static org.opendaylight.genius.infra.Datastore.CONFIGURATION;
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;
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;
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).
115 * <p>It makes use of HwvtepUtils class located under ovsdb/hwvtepsouthbound
116 * project for low-level mdsal operations
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;
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;
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;
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;
163 public void close() {
166 public long getLogicalSwitchDeleteDelaySecs() {
167 return elanConfig.getL2gwLogicalSwitchDelaySecs() != null
168 ? elanConfig.getL2gwLogicalSwitchDelaySecs() : DEFAULT_LOGICAL_SWITCH_DELETE_DELAY_SECS;
172 * gets the macs addresses for elan interfaces.
174 * @param lstElanInterfaceNames
175 * the lst elan interface names
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());
192 * Check if phy locator already exists in remote mcast entry.
196 * @param remoteMcastMac
197 * the remote mcast mac
198 * @param expectedPhyLocatorIp
199 * the expected phy locator ip
200 * @return true, if successful
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);
222 * Gets the remote mcast mac.
226 * @param logicalSwitchName
227 * the logical switch name
228 * @param datastoreType
230 * @return the remote mcast mac
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);
242 * Removes the given MAC Addresses from all the External Devices belonging
243 * to the specified ELAN.
245 * @param elanInstance
247 * @param macAddresses
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);
260 * Removes the given MAC Addresses from the specified External Device.
262 * @param deviceNodeId
264 * @param macAddresses
266 * @return the listenable future
268 private ListenableFuture<Void> removeRemoteUcastMacsFromExternalDevice(String deviceNodeId,
269 String logicalSwitchName, List<PhysAddress> macAddresses) {
270 NodeId nodeId = new NodeId(deviceNodeId);
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);
279 public ElanInstance getElanInstanceForUcastLocalMac(LocalUcastMacs localUcastMac) {
280 Optional<LogicalSwitches> lsOpc = ElanUtils.read(broker, LogicalDatastoreType.OPERATIONAL,
281 (InstanceIdentifier<LogicalSwitches>) localUcastMac.getLogicalSwitchRef().getValue());
282 if (lsOpc.isPresent()) {
283 LogicalSwitches ls = lsOpc.get();
284 // Logical switch name is Elan name
285 String elanName = getElanFromLogicalSwitch(ls.getHwvtepNodeName().getValue());
286 return elanInstanceCache.get(elanName).orNull();
292 * Install external device local macs in dpn.
296 * @param l2gwDeviceNodeId
297 * the l2gw device node id
300 * @param interfaceName
303 public void installL2gwDeviceMacsInDpn(BigInteger dpnId, NodeId l2gwDeviceNodeId, ElanInstance elan,
304 String interfaceName) {
305 L2GatewayDevice l2gwDevice = ElanL2GwCacheUtils.getL2GatewayDeviceFromCache(elan.getElanInstanceName(),
306 l2gwDeviceNodeId.getValue());
307 if (l2gwDevice == null) {
308 LOG.debug("L2 gw device not found in elan cache for device name {}", l2gwDeviceNodeId.getValue());
312 installDmacFlowsOnDpn(dpnId, l2gwDevice, elan, interfaceName);
316 * Install dmac flows on dpn.
324 * @param interfaceName
327 public void installDmacFlowsOnDpn(BigInteger dpnId, L2GatewayDevice l2gwDevice, ElanInstance elan,
328 String interfaceName) {
329 String elanName = elan.getElanInstanceName();
331 Collection<LocalUcastMacs> l2gwDeviceLocalMacs = l2gwDevice.getUcastLocalMacs();
332 if (!l2gwDeviceLocalMacs.isEmpty()) {
333 for (LocalUcastMacs localUcastMac : l2gwDeviceLocalMacs) {
334 elanDmacUtils.installDmacFlowsToExternalRemoteMacInBatch(dpnId, l2gwDevice.getHwvtepNodeId(),
335 elan.getElanTag(), ElanUtils.getVxlanSegmentationId(elan),
336 localUcastMac.getMacEntryKey().getValue(), elanName, interfaceName);
338 LOG.debug("Installing L2gw device [{}] local macs [size: {}] in dpn [{}] for elan [{}]",
339 l2gwDevice.getHwvtepNodeId(), l2gwDeviceLocalMacs.size(), dpnId, elanName);
344 * Install elan l2gw devices local macs in dpn.
350 * @param interfaceName
353 public void installElanL2gwDevicesLocalMacsInDpn(BigInteger dpnId, ElanInstance elan, String interfaceName) {
354 ConcurrentMap<String, L2GatewayDevice> elanL2GwDevicesFromCache = ElanL2GwCacheUtils
355 .getInvolvedL2GwDevices(elan.getElanInstanceName());
356 if (elanL2GwDevicesFromCache != null) {
357 for (L2GatewayDevice l2gwDevice : elanL2GwDevicesFromCache.values()) {
358 installDmacFlowsOnDpn(dpnId, l2gwDevice, elan, interfaceName);
361 LOG.debug("No Elan l2 gateway devices in cache for [{}] ", elan.getElanInstanceName());
365 public void installL2GwUcastMacInElan(final ElanInstance elan, final L2GatewayDevice extL2GwDevice,
366 final String macToBeAdded, final LocalUcastMacs localUcastMacs, @Nullable String interfaceName) {
367 final String extDeviceNodeId = extL2GwDevice.getHwvtepNodeId();
368 final String elanInstanceName = elan.getElanInstanceName();
369 final Collection<DpnInterfaces> elanDpns = getElanDpns(elanInstanceName);
370 ConcurrentMap<String, L2GatewayDevice> elanL2GwDevices = ElanL2GwCacheUtils
371 .getInvolvedL2GwDevices(elanInstanceName);
373 // Retrieve all participating DPNs in this Elan. Populate this MAC in
375 // Looping through all DPNs in order to add/remove mac flows in their
377 if (elanDpns.size() > 0 || elanL2GwDevices.values().size() > 0) {
378 String jobKey = elanInstanceName + ":" + macToBeAdded;
379 IpAddress extL2GwDeviceTepIp = extL2GwDevice.getTunnelIp();
380 List<PhysAddress> macList = Lists.newArrayList(new PhysAddress(macToBeAdded));
382 elanClusterUtils.runOnlyInOwnerNode(jobKey, "install l2gw macs in dmac table", () -> {
383 if (doesLocalUcastMacExistsInCache(extL2GwDevice, localUcastMacs)) {
384 List<ListenableFuture<Void>> futures = new ArrayList<>();
385 for (DpnInterfaces elanDpn : elanDpns) {
386 futures.addAll(elanDmacUtils.installDmacFlowsToExternalRemoteMacInBatch(elanDpn.getDpId(),
387 extDeviceNodeId, elan.getElanTag(), ElanUtils.getVxlanSegmentationId(elan),
388 macToBeAdded, elanInstanceName, interfaceName));
390 for (L2GatewayDevice otherDevice : elanL2GwDevices.values()) {
391 if (!otherDevice.getHwvtepNodeId().equals(extDeviceNodeId)
392 && !areMLAGDevices(extL2GwDevice, otherDevice)) {
393 final String hwvtepId = otherDevice.getHwvtepNodeId();
394 final String logicalSwitchName = elanInstanceName;
395 futures.add(HwvtepUtils.installUcastMacs(
396 broker, hwvtepId, macList, logicalSwitchName, extL2GwDeviceTepIp));
401 LOG.trace("Skipping install of dmac flows for mac {} as it is not found in cache",
404 return Collections.emptyList();
410 * Does local ucast mac exists in cache.
412 * @param elanL2GwDevice
413 * the elan L2 Gw device
415 * the mac address to be verified
416 * @return true, if successful
418 private static boolean doesLocalUcastMacExistsInCache(L2GatewayDevice elanL2GwDevice, LocalUcastMacs macAddress) {
419 return elanL2GwDevice.containsUcastMac(macAddress);
423 * Uninstall l2gw macs from other l2gw devices in the elanName provided.
424 * @param elanName - Elan Name for which other l2gw devices will be scanned.
425 * @param l2GwDevice - l2gwDevice whose macs are required to be cleared from other devices.
426 * @param macAddresses - Mac address to be cleared.
428 public void unInstallL2GwUcastMacFromL2gwDevices(final String elanName,
429 final L2GatewayDevice l2GwDevice,
430 final Collection<MacAddress> macAddresses) {
431 if (macAddresses == null || macAddresses.isEmpty()) {
435 if (elanName == null) {
439 DeleteL2GwDeviceMacsFromElanJob job = new DeleteL2GwDeviceMacsFromElanJob(elanName, l2GwDevice,
441 elanClusterUtils.runOnlyInOwnerNode(job.getJobKey(), "delete remote ucast macs in l2gw devices", job);
445 * Uninstall l2gw macs from other DPNs in the elan instance provided.
446 * @param elan - Elan Instance for which other DPNs will be scanned.
447 * @param l2GwDevice - l2gwDevice whose macs are required to be cleared from other devices.
448 * @param macAddresses - Mac address to be cleared.
450 public void unInstallL2GwUcastMacFromElanDpns(final ElanInstance elan, final L2GatewayDevice l2GwDevice,
451 final Collection<MacAddress> macAddresses) {
452 if (macAddresses == null || macAddresses.isEmpty()) {
455 if (elan == null || elan.getElanInstanceName() == null) {
456 LOG.error("Could not delete l2gw ucast macs, Failed to find the elan for device {}",
457 l2GwDevice.getHwvtepNodeId());
461 final Collection<DpnInterfaces> elanDpns = getElanDpns(elan.getElanInstanceName());
463 // Retrieve all participating DPNs in this Elan. Populate this MAC in
464 // DMAC table. Looping through all DPNs in order to add/remove mac flows
465 // in their DMAC table
466 List<ListenableFuture<Void>> result = new ArrayList<>();
467 for (final MacAddress mac : macAddresses) {
468 elanClusterUtils.runOnlyInOwnerNode(elan.getElanInstanceName() + ":" + mac.getValue(),
469 "delete remote ucast macs in elan DPNs", () -> {
470 for (DpnInterfaces elanDpn : elanDpns) {
471 BigInteger dpnId = elanDpn.getDpId();
472 result.addAll(elanDmacUtils.deleteDmacFlowsToExternalMac(elan.getElanTag(), dpnId,
473 l2GwDevice.getHwvtepNodeId(),
474 IetfYangUtil.INSTANCE.canonizeMacAddress(mac).getValue()));
482 * Delete elan l2 gateway devices ucast local macs from dpn.
489 public void deleteElanL2GwDevicesUcastLocalMacsFromDpn(final String elanName, final BigInteger dpnId) {
490 ConcurrentMap<String, L2GatewayDevice> elanL2GwDevices = ElanL2GwCacheUtils.getInvolvedL2GwDevices(elanName);
491 if (elanL2GwDevices == null || elanL2GwDevices.isEmpty()) {
492 LOG.trace("No L2 gateway devices in Elan [{}] cache.", elanName);
495 final ElanInstance elan = elanInstanceCache.get(elanName).orNull();
497 LOG.error("Could not find Elan by name: {}", elanName);
500 LOG.info("Deleting Elan [{}] L2GatewayDevices UcastLocalMacs from Dpn [{}]", elanName, dpnId);
502 final Long elanTag = elan.getElanTag();
503 for (final L2GatewayDevice l2GwDevice : elanL2GwDevices.values()) {
504 getL2GwDeviceLocalMacsAndRunCallback(elan.getElanInstanceName(), l2GwDevice, (localMacs) -> {
505 for (MacAddress mac : localMacs) {
506 String jobKey = elanName + ":" + mac.getValue();
507 elanClusterUtils.runOnlyInOwnerNode(jobKey,
508 () -> elanDmacUtils.deleteDmacFlowsToExternalMac(elanTag, dpnId,
509 l2GwDevice.getHwvtepNodeId(), mac.getValue()));
516 public void getL2GwDeviceLocalMacsAndRunCallback(String elanName, L2GatewayDevice l2gwDevice,
517 Function<Collection<MacAddress>, Void> function) {
518 if (l2gwDevice == null) {
521 Set<MacAddress> macs = new HashSet<>();
522 Collection<LocalUcastMacs> lstUcastLocalMacs = l2gwDevice.getUcastLocalMacs();
523 if (!lstUcastLocalMacs.isEmpty()) {
524 macs.addAll(lstUcastLocalMacs.stream().filter(Objects::nonNull)
525 .map(mac -> new MacAddress(mac.getMacEntryKey().getValue().toLowerCase()))
526 .collect(Collectors.toList()));
529 InstanceIdentifier<Node> nodeIid = HwvtepSouthboundUtils.createInstanceIdentifier(
530 new NodeId(l2gwDevice.getHwvtepNodeId()));
531 Futures.addCallback(broker.newReadOnlyTransaction().read(LogicalDatastoreType.CONFIGURATION, nodeIid),
532 new FutureCallback<Optional<Node>>() {
534 public void onSuccess(Optional<Node> configNode) {
535 if (configNode != null && configNode.isPresent()) {
536 HwvtepGlobalAugmentation augmentation = configNode.get().augmentation(
537 HwvtepGlobalAugmentation.class);
538 if (augmentation != null && augmentation.getLocalUcastMacs() != null) {
539 macs.addAll(augmentation.getLocalUcastMacs().stream()
540 .filter(mac -> getLogicalSwitchName(mac).equals(elanName))
541 .map(HwvtepMacTableGenericAttributes::getMacEntryKey)
542 .collect(Collectors.toSet()));
544 function.apply(macs);
549 public void onFailure(Throwable throwable) {
550 LOG.error("Failed to read config topology node {}", nodeIid);
552 }, MoreExecutors.directExecutor());
555 private String getLogicalSwitchName(LocalUcastMacs mac) {
556 return ((InstanceIdentifier<LogicalSwitches>)mac.getLogicalSwitchRef().getValue())
557 .firstKeyOf(LogicalSwitches.class).getHwvtepNodeName().getValue();
561 * Delete elan macs from L2 gateway device.<br>
562 * This includes deleting ELAN mac table entries plus external device
563 * UcastLocalMacs which are part of the same ELAN.
565 * @param hwvtepNodeId
569 * @return the listenable future
571 public ListenableFuture<Void> deleteElanMacsFromL2GatewayDevice(String hwvtepNodeId, String elanName) {
572 String logicalSwitch = getLogicalSwitchFromElan(elanName);
574 List<MacAddress> lstElanMacs = getRemoteUcastMacs(new NodeId(hwvtepNodeId), logicalSwitch,
575 LogicalDatastoreType.CONFIGURATION);
576 ListenableFuture<Void> future = HwvtepUtils.deleteRemoteUcastMacs(broker, new NodeId(hwvtepNodeId),
577 logicalSwitch, lstElanMacs);
579 Futures.addCallback(future, new FutureCallback<Void>() {
581 public void onSuccess(Void noarg) {
582 LOG.trace("Successful in batch deletion of elan [{}] macs from l2gw device [{}]", elanName,
587 public void onFailure(Throwable error) {
588 LOG.warn("Failed during batch delete of elan {} macs from l2gw device {}. "
589 + "Retrying with sequential deletes.", elanName, hwvtepNodeId, error);
590 if (lstElanMacs != null && !lstElanMacs.isEmpty()) {
591 for (MacAddress mac : lstElanMacs) {
592 HwvtepUtils.deleteRemoteUcastMac(broker, new NodeId(hwvtepNodeId), logicalSwitch, mac);
596 }, MoreExecutors.directExecutor());
598 if (LOG.isDebugEnabled()) {
599 List<String> elanMacs = lstElanMacs.stream().map(MacAddress::getValue).collect(Collectors.toList());
600 LOG.debug("Deleting elan [{}] macs from node [{}]. Deleted macs = {}", elanName, hwvtepNodeId, elanMacs);
606 * Gets the remote ucast macs from hwvtep node filtering based on logical
609 * @param hwvtepNodeId
611 * @param logicalSwitch
613 * @param datastoreType
615 * @return the remote ucast macs
617 public List<MacAddress> getRemoteUcastMacs(NodeId hwvtepNodeId, String logicalSwitch,
618 LogicalDatastoreType datastoreType) {
619 List<MacAddress> lstMacs = Collections.emptyList();
620 Node hwvtepNode = HwvtepUtils.getHwVtepNode(broker, datastoreType, hwvtepNodeId);
621 if (hwvtepNode != null) {
622 List<RemoteUcastMacs> remoteUcastMacs = hwvtepNode.augmentation(HwvtepGlobalAugmentation.class)
623 .getRemoteUcastMacs();
624 if (remoteUcastMacs != null && !remoteUcastMacs.isEmpty()) {
625 // Filtering remoteUcastMacs based on the logical switch and
626 // forming a list of MacAddress
627 lstMacs = remoteUcastMacs.stream()
628 .filter(mac -> logicalSwitch.equals(mac.getLogicalSwitchRef().getValue()
629 .firstKeyOf(LogicalSwitches.class).getHwvtepNodeName().getValue()))
630 .map(HwvtepMacTableGenericAttributes::getMacEntryKey).collect(Collectors.toList());
637 * Install ELAN macs in L2 Gateway device.<br>
638 * This includes installing ELAN mac table entries plus external device
639 * UcastLocalMacs which are part of the same ELAN.
643 * @param l2GatewayDevice
644 * the l2 gateway device which has to be configured
645 * @return the listenable future
647 public ListenableFuture<Void> installElanMacsInL2GatewayDevice(String elanName,
648 L2GatewayDevice l2GatewayDevice) {
649 String logicalSwitchName = getLogicalSwitchFromElan(elanName);
650 NodeId hwVtepNodeId = new NodeId(l2GatewayDevice.getHwvtepNodeId());
652 List<RemoteUcastMacs> lstL2GatewayDevicesMacs = getOtherDevicesMacs(elanName, l2GatewayDevice, hwVtepNodeId,
654 List<RemoteUcastMacs> lstElanMacTableEntries = getElanMacTableEntriesMacs(elanName,
655 hwVtepNodeId, logicalSwitchName);
657 List<RemoteUcastMacs> lstRemoteUcastMacs = new ArrayList<>(lstL2GatewayDevicesMacs);
658 lstRemoteUcastMacs.addAll(lstElanMacTableEntries);
660 ListenableFuture<Void> future = HwvtepUtils.addRemoteUcastMacs(broker, hwVtepNodeId, lstRemoteUcastMacs);
662 LOG.info("Added RemoteUcastMacs entries [{}] in config DS. NodeID: {}, LogicalSwitch: {}",
663 lstRemoteUcastMacs.size(), hwVtepNodeId.getValue(), logicalSwitchName);
668 * Gets the l2 gateway devices ucast local macs as remote ucast macs.
672 * @param l2GatewayDeviceToBeConfigured
673 * the l2 gateway device to be configured
674 * @param hwVtepNodeId
675 * the hw vtep node Id to be configured
676 * @param logicalSwitchName
677 * the logical switch name
678 * @return the l2 gateway devices macs as remote ucast macs
680 public static List<RemoteUcastMacs> getOtherDevicesMacs(String elanName,
681 L2GatewayDevice l2GatewayDeviceToBeConfigured, NodeId hwVtepNodeId, String logicalSwitchName) {
682 List<RemoteUcastMacs> lstRemoteUcastMacs = new ArrayList<>();
683 ConcurrentMap<String, L2GatewayDevice> elanL2GwDevicesFromCache = ElanL2GwCacheUtils
684 .getInvolvedL2GwDevices(elanName);
686 if (elanL2GwDevicesFromCache != null) {
687 for (L2GatewayDevice otherDevice : elanL2GwDevicesFromCache.values()) {
688 if (l2GatewayDeviceToBeConfigured.getHwvtepNodeId().equals(otherDevice.getHwvtepNodeId())) {
691 if (!areMLAGDevices(l2GatewayDeviceToBeConfigured, otherDevice)) {
692 for (LocalUcastMacs localUcastMac : otherDevice.getUcastLocalMacs()) {
693 HwvtepPhysicalLocatorAugmentation physLocatorAug = HwvtepSouthboundUtils
694 .createHwvtepPhysicalLocatorAugmentation(otherDevice.getTunnelIp());
695 RemoteUcastMacs remoteUcastMac = HwvtepSouthboundUtils.createRemoteUcastMac(hwVtepNodeId,
696 IetfYangUtil.INSTANCE.canonizeMacAddress(localUcastMac.getMacEntryKey()).getValue(),
697 localUcastMac.getIpaddr(), logicalSwitchName, physLocatorAug);
698 lstRemoteUcastMacs.add(remoteUcastMac);
703 return lstRemoteUcastMacs;
709 * @param l2GatewayDevice
710 * the l2 gateway device
711 * @param otherL2GatewayDevice
712 * the other l2 gateway device
713 * @return true, if both the specified l2 gateway devices are part of same
716 public static boolean areMLAGDevices(L2GatewayDevice l2GatewayDevice, L2GatewayDevice otherL2GatewayDevice) {
717 // If tunnel IPs are same, then it is considered to be part of same MLAG
718 return Objects.equals(l2GatewayDevice.getTunnelIp(), otherL2GatewayDevice.getTunnelIp());
722 * Gets the elan mac table entries as remote ucast macs. <br>
723 * Note: ELAN MAC table only contains internal switches MAC's. It doesn't
724 * contain external device MAC's.
728 * @param hwVtepNodeId
729 * the hw vtep node id
730 * @param logicalSwitchName
731 * the logical switch name
732 * @return the elan mac table entries as remote ucast macs
734 public List<RemoteUcastMacs> getElanMacTableEntriesMacs(String elanName,
735 NodeId hwVtepNodeId, String logicalSwitchName) {
736 List<RemoteUcastMacs> lstRemoteUcastMacs = new ArrayList<>();
738 MacTable macTable = ElanUtils.getElanMacTable(broker, elanName);
739 if (macTable == null || macTable.getMacEntry() == null || macTable.getMacEntry().isEmpty()) {
740 LOG.trace("MacTable is empty for elan: {}", elanName);
741 return lstRemoteUcastMacs;
744 for (MacEntry macEntry : macTable.getMacEntry()) {
745 BigInteger dpnId = getDpidFromInterface(macEntry.getInterface());
747 LOG.error("DPN ID not found for interface {}", macEntry.getInterface());
751 IpAddress dpnTepIp = elanItmUtils.getSourceDpnTepIp(dpnId, hwVtepNodeId);
752 LOG.trace("Dpn Tep IP: {} for dpnId: {} and nodeId: {}", dpnTepIp, dpnId, hwVtepNodeId.getValue());
753 if (dpnTepIp == null) {
754 LOG.error("TEP IP not found for dpnId {} and nodeId {}", dpnId, hwVtepNodeId.getValue());
757 HwvtepPhysicalLocatorAugmentation physLocatorAug = HwvtepSouthboundUtils
758 .createHwvtepPhysicalLocatorAugmentation(dpnTepIp);
759 // TODO: Query ARP cache to get IP address corresponding to the
761 RemoteUcastMacs remoteUcastMac = HwvtepSouthboundUtils.createRemoteUcastMac(hwVtepNodeId,
762 IetfYangUtil.INSTANCE.canonizePhysAddress(macEntry.getMacAddress()).getValue(), null /*IpAddress*/,
763 logicalSwitchName, physLocatorAug);
764 lstRemoteUcastMacs.add(remoteUcastMac);
766 return lstRemoteUcastMacs;
770 * Gets the dpid from interface.
772 * @param interfaceName
774 * @return the dpid from interface
777 public BigInteger getDpidFromInterface(String interfaceName) {
778 BigInteger dpId = null;
779 Future<RpcResult<GetDpidFromInterfaceOutput>> output = interfaceManagerRpcService
780 .getDpidFromInterface(new GetDpidFromInterfaceInputBuilder().setIntfName(interfaceName).build());
782 RpcResult<GetDpidFromInterfaceOutput> rpcResult = output.get();
783 if (rpcResult != null && rpcResult.isSuccessful()) {
784 dpId = rpcResult.getResult().getDpid();
786 } catch (InterruptedException | ExecutionException e) {
787 LOG.error("Failed to get the DPN ID for interface {}", interfaceName, e);
793 * Update vlan bindings in l2 gateway device.
797 * @param logicalSwitchName
798 * the logical switch name
799 * @param hwVtepDevice
800 * the hardware device
801 * @param defaultVlanId
802 * the default vlan id
803 * @return the listenable future
805 public ListenableFuture<Void> updateVlanBindingsInL2GatewayDevice(NodeId nodeId, String logicalSwitchName,
806 Devices hwVtepDevice, Integer defaultVlanId) {
807 if (hwVtepDevice == null || hwVtepDevice.getInterfaces() == null || hwVtepDevice.getInterfaces().isEmpty()) {
808 String errMsg = "HwVtepDevice is null or interfaces are empty.";
810 return Futures.immediateFailedFuture(new RuntimeException(errMsg));
813 return txRunner.callWithNewWriteOnlyTransactionAndSubmit(CONFIGURATION, tx -> {
814 for (org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l2gateways.rev150712
815 .l2gateway.attributes.devices.Interfaces deviceInterface : hwVtepDevice.getInterfaces()) {
816 //Removed the check for checking terminationPoint present in OP or not
817 //for coniguring vlan bindings
818 //As we are not any more dependent on it , plugin takes care of this
819 // with port reconcilation.
820 List<VlanBindings> vlanBindings = new ArrayList<>();
821 if (deviceInterface.getSegmentationIds() != null && !deviceInterface.getSegmentationIds().isEmpty()) {
822 for (Integer vlanId : deviceInterface.getSegmentationIds()) {
823 vlanBindings.add(HwvtepSouthboundUtils.createVlanBinding(nodeId, vlanId, logicalSwitchName));
826 // Use defaultVlanId (specified in L2GatewayConnection) if Vlan
827 // ID not specified at interface level.
828 vlanBindings.add(HwvtepSouthboundUtils.createVlanBinding(nodeId, defaultVlanId, logicalSwitchName));
830 HwvtepUtils.mergeVlanBindings(tx, nodeId, hwVtepDevice.getDeviceName(),
831 deviceInterface.getInterfaceName(), vlanBindings);
833 LOG.info("Updated Hwvtep VlanBindings in config DS. NodeID: {}, LogicalSwitch: {}", nodeId.getValue(),
839 * Update vlan bindings in l2 gateway device.
844 * the physical switch name
845 * @param interfaceName
846 * the interface in physical switch
847 * @param vlanBindings
848 * the vlan bindings to be configured
849 * @return the listenable future
851 public ListenableFuture<Void> updateVlanBindingsInL2GatewayDevice(NodeId nodeId, String psName,
852 String interfaceName, List<VlanBindings> vlanBindings) {
853 return txRunner.callWithNewWriteOnlyTransactionAndSubmit(CONFIGURATION, tx -> {
854 HwvtepUtils.mergeVlanBindings(tx, nodeId, psName, interfaceName, vlanBindings);
855 LOG.info("Updated Hwvtep VlanBindings in config DS. NodeID: {}", nodeId.getValue());
860 * Delete vlan bindings from l2 gateway device.
864 * @param hwVtepDevice
866 * @param defaultVlanId
867 * the default vlan id
868 * @return the listenable future
870 public ListenableFuture<Void> deleteVlanBindingsFromL2GatewayDevice(NodeId nodeId, Devices hwVtepDevice,
871 Integer defaultVlanId) {
872 if (hwVtepDevice == null || hwVtepDevice.getInterfaces() == null || hwVtepDevice.getInterfaces().isEmpty()) {
873 String errMsg = "HwVtepDevice is null or interfaces are empty.";
875 return Futures.immediateFailedFuture(new RuntimeException(errMsg));
877 NodeId physicalSwitchNodeId = HwvtepSouthboundUtils.createManagedNodeId(nodeId, hwVtepDevice.getDeviceName());
879 return txRunner.callWithNewWriteOnlyTransactionAndSubmit(CONFIGURATION, tx -> {
880 for (org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l2gateways.rev150712
881 .l2gateway.attributes.devices.Interfaces deviceInterface : hwVtepDevice.getInterfaces()) {
882 String phyPortName = deviceInterface.getInterfaceName();
883 if (deviceInterface.getSegmentationIds() != null && !deviceInterface.getSegmentationIds().isEmpty()) {
884 for (Integer vlanId : deviceInterface.getSegmentationIds()) {
885 HwvtepUtils.deleteVlanBinding(tx, physicalSwitchNodeId, phyPortName, vlanId);
888 // Use defaultVlanId (specified in L2GatewayConnection) if Vlan
889 // ID not specified at interface level.
890 HwvtepUtils.deleteVlanBinding(tx, physicalSwitchNodeId, phyPortName, defaultVlanId);
893 LOG.info("Deleted Hwvtep VlanBindings from config DS. NodeID: {}, hwVtepDevice: {}, defaultVlanId: {} ",
894 nodeId.getValue(), hwVtepDevice, defaultVlanId);
899 * Gets the elan name from logical switch name.
901 * @param logicalSwitchName
902 * the logical switch name
903 * @return the elan name from logical switch name
905 public static String getElanFromLogicalSwitch(String logicalSwitchName) {
906 // Assuming elan name is same as logical switch name
907 String elanName = logicalSwitchName;
912 * Gets the logical switch name from elan name.
916 * @return the logical switch from elan name
918 public static String getLogicalSwitchFromElan(String elanName) {
919 // Assuming logical switch name is same as elan name
920 String logicalSwitchName = elanName;
921 return logicalSwitchName;
925 * Gets the l2 gateway connection job key.
927 * @param logicalSwitchName
928 * the logical switch name
929 * @return the l2 gateway connection job key
931 public static String getL2GatewayConnectionJobKey(String logicalSwitchName) {
932 return logicalSwitchName;
935 public static InstanceIdentifier<Interface> getInterfaceIdentifier(InterfaceKey interfaceKey) {
936 InstanceIdentifier.InstanceIdentifierBuilder<Interface> interfaceInstanceIdentifierBuilder = InstanceIdentifier
937 .builder(Interfaces.class).child(Interface.class, interfaceKey);
938 return interfaceInstanceIdentifierBuilder.build();
942 public static Interface getInterfaceFromConfigDS(InterfaceKey interfaceKey, DataBroker dataBroker) {
943 InstanceIdentifier<Interface> interfaceId = getInterfaceIdentifier(interfaceKey);
945 return SingleTransactionDataBroker
946 .syncReadOptional(dataBroker, LogicalDatastoreType.CONFIGURATION, interfaceId).orNull();
947 } catch (ReadFailedException e) {
948 // TODO remove this, and propagate ReadFailedException instead of re-throw RuntimeException
949 LOG.error("getInterfaceFromConfigDS({}) failed", interfaceKey, e);
950 throw new RuntimeException(e);
955 * Delete l2 gateway device ucast local macs from elan.<br>
956 * Deletes macs from internal ELAN nodes and also on rest of external l2
957 * gateway devices which are part of the ELAN.
959 * @param l2GatewayDevice
960 * the l2 gateway device whose ucast local macs to be deleted
965 public void deleteL2GwDeviceUcastLocalMacsFromElan(L2GatewayDevice l2GatewayDevice,
967 LOG.info("Deleting L2GatewayDevice [{}] UcastLocalMacs from elan [{}]", l2GatewayDevice.getHwvtepNodeId(),
970 ElanInstance elan = elanInstanceCache.get(elanName).orNull();
972 LOG.error("Could not find Elan by name: {}", elanName);
976 Collection<MacAddress> localMacs = getL2GwDeviceLocalMacs(elanName, l2GatewayDevice);
977 unInstallL2GwUcastMacFromL2gwDevices(elanName, l2GatewayDevice, localMacs);
978 unInstallL2GwUcastMacFromElanDpns(elan, l2GatewayDevice, localMacs);
981 public static void createItmTunnels(DataBroker dataBroker, ItmRpcService itmRpcService,
982 String hwvtepId, String psName, IpAddress tunnelIp) {
983 AddL2GwDeviceInputBuilder builder = new AddL2GwDeviceInputBuilder();
984 builder.setTopologyId(HwvtepSouthboundConstants.HWVTEP_TOPOLOGY_ID.getValue());
985 builder.setNodeId(HwvtepSouthboundUtils.createManagedNodeId(new NodeId(hwvtepId), psName).getValue());
986 builder.setIpAddress(tunnelIp);
988 deleteStaleTunnelsOfHwvtepInITM(dataBroker, itmRpcService, hwvtepId, psName, tunnelIp);
989 RpcResult<AddL2GwDeviceOutput> rpcResult = itmRpcService.addL2GwDevice(builder.build()).get();
990 if (rpcResult.isSuccessful()) {
991 LOG.info("Created ITM tunnels for {}", hwvtepId);
993 LOG.error("Failed to create ITM Tunnels: {}", rpcResult.getErrors());
995 } catch (InterruptedException | ExecutionException e) {
996 LOG.error("RPC to create ITM tunnels failed", e);
1000 private static void deleteStaleTunnelsOfHwvtepInITM(DataBroker dataBroker,
1001 ItmRpcService itmRpcService,
1002 String globalNodeId,
1004 IpAddress tunnelIp) {
1006 Optional<TransportZones> tzonesoptional = readTransportZone(dataBroker);
1007 if (!tzonesoptional.isPresent() || tzonesoptional.get().getTransportZone() == null) {
1010 String psNodeId = globalNodeId + HwvtepHAUtil.PHYSICALSWITCH + psName;
1011 tzonesoptional.get().nonnullTransportZone().stream()
1012 .filter(transportZone -> transportZone.getSubnets() != null)
1013 .flatMap(transportZone -> transportZone.getSubnets().stream())
1014 .filter(subnet -> subnet.getDeviceVteps() != null)
1015 .flatMap(subnet -> subnet.getDeviceVteps().stream())
1016 .filter(deviceVteps -> Objects.equals(getPsName(deviceVteps), psName)) //get device with same ps name
1017 .filter(deviceVteps -> !Objects.equals(psNodeId, deviceVteps.getNodeId())
1018 || !Objects.equals(tunnelIp, deviceVteps.getIpAddress()))//node id or tunnel ip is changed
1019 .forEach(deviceVteps -> deleteStaleL2gwTep(dataBroker, itmRpcService, deviceVteps));
1020 } catch (ReadFailedException e) {
1021 LOG.error("Failed delete stale tunnels for {}", globalNodeId);
1025 private static Optional<TransportZones> readTransportZone(DataBroker dataBroker) throws ReadFailedException {
1026 return new SingleTransactionDataBroker(dataBroker).syncReadOptional(LogicalDatastoreType.CONFIGURATION,
1027 InstanceIdentifier.builder(TransportZones.class).build());
1030 private static Optional<ElanInstances> readElanInstances(DataBroker dataBroker) throws ReadFailedException {
1031 return new SingleTransactionDataBroker(dataBroker).syncReadOptional(LogicalDatastoreType.CONFIGURATION,
1032 InstanceIdentifier.builder(ElanInstances.class).build());
1035 private static String getPsName(DeviceVteps deviceVteps) {
1036 return HwvtepHAUtil.getPsName(HwvtepHAUtil.convertToInstanceIdentifier(deviceVteps.getNodeId()));
1039 private static void deleteStaleL2gwTep(DataBroker dataBroker,
1040 ItmRpcService itmRpcService,
1041 DeviceVteps deviceVteps) {
1042 String psName = HwvtepHAUtil.getPsName(HwvtepHAUtil.convertToInstanceIdentifier(deviceVteps.getNodeId()));
1043 String globalNodeId = HwvtepHAUtil.convertToGlobalNodeId(deviceVteps.getNodeId());
1045 LOG.info("Deleting stale tep {} ", deviceVteps);
1046 L2GatewayUtils.deleteItmTunnels(itmRpcService, globalNodeId, psName, deviceVteps.getIpAddress());
1047 Optional<ElanInstances> optionalElan = readElanInstances(dataBroker);
1048 if (!optionalElan.isPresent()) {
1051 JdkFutures.addErrorLogging(
1052 new ManagedNewTransactionRunnerImpl(dataBroker).callWithNewReadWriteTransactionAndSubmit(CONFIGURATION,
1053 tx -> optionalElan.get().nonnullElanInstance().stream()
1054 .flatMap(elan -> elan.nonnullExternalTeps().stream()
1055 .map(externalTep -> ElanL2GatewayMulticastUtils.buildExternalTepPath(
1056 elan.getElanInstanceName(), externalTep.getTepIp())))
1057 .filter(externalTepIid -> Objects.equals(
1058 deviceVteps.getIpAddress(), externalTepIid.firstKeyOf(ExternalTeps.class).getTepIp()))
1059 .peek(externalTepIid -> LOG.info("Deleting stale external tep {}", externalTepIid))
1060 .forEach(tx::delete)), LOG,
1061 "Failed to delete stale external teps {}", deviceVteps);
1062 Thread.sleep(10000);//TODO remove the sleep currently it waits for interfacemgr to finish the cleanup
1063 } catch (ReadFailedException | InterruptedException e) {
1064 LOG.error("Failed to delete stale l2gw tep {}", deviceVteps, e);
1068 public static String getNodeIdFromDpnId(BigInteger dpnId) {
1069 return MDSALUtil.NODE_PREFIX + MDSALUtil.SEPARATOR + dpnId.toString();
1072 public void scheduleAddDpnMacInExtDevices(String elanName, BigInteger dpId,
1073 List<PhysAddress> staticMacAddresses) {
1074 ConcurrentMap<String, L2GatewayDevice> elanDevices = ElanL2GwCacheUtils.getInvolvedL2GwDevices(elanName);
1075 for (final L2GatewayDevice externalDevice : elanDevices.values()) {
1076 scheduleAddDpnMacsInExtDevice(elanName, dpId, staticMacAddresses, externalDevice);
1080 public void scheduleAddDpnMacsInExtDevice(final String elanName, BigInteger dpId,
1081 final List<PhysAddress> staticMacAddresses, final L2GatewayDevice externalDevice) {
1082 NodeId nodeId = new NodeId(externalDevice.getHwvtepNodeId());
1083 final IpAddress dpnTepIp = elanItmUtils.getSourceDpnTepIp(dpId, nodeId);
1084 LOG.trace("Dpn Tep IP: {} for dpnId: {} and nodeId: {}", dpnTepIp, dpId, nodeId);
1085 if (dpnTepIp == null) {
1086 LOG.error("could not install dpn mac in l2gw TEP IP not found for dpnId {} and nodeId {}", dpId, nodeId);
1090 //TODO: to be batched in genius
1091 HwvtepUtils.installUcastMacs(broker, externalDevice.getHwvtepNodeId(), staticMacAddresses, elanName, dpnTepIp);
1094 public void scheduleDeleteLogicalSwitch(NodeId hwvtepNodeId, String lsName) {
1095 scheduleDeleteLogicalSwitch(hwvtepNodeId, lsName, false);
1098 public void scheduleDeleteLogicalSwitch(final NodeId hwvtepNodeId, final String lsName, final boolean clearUcast) {
1099 final Pair<NodeId, String> nodeIdLogicalSwitchNamePair = new ImmutablePair<>(hwvtepNodeId, lsName);
1100 logicalSwitchDeletedTasks.computeIfAbsent(nodeIdLogicalSwitchNamePair,
1101 (key) -> scheduler.getScheduledExecutorService().schedule(() -> {
1102 DeleteLogicalSwitchJob deleteLsJob = new DeleteLogicalSwitchJob(broker,
1103 ElanL2GatewayUtils.this, hwvtepNodeId, lsName, clearUcast);
1104 jobCoordinator.enqueueJob(deleteLsJob.getJobKey(), deleteLsJob,
1105 SystemPropertyReader.getDataStoreJobCoordinatorMaxRetries());
1106 deleteJobs.put(nodeIdLogicalSwitchNamePair, deleteLsJob);
1107 logicalSwitchDeletedTasks.remove(nodeIdLogicalSwitchNamePair);
1108 }, getLogicalSwitchDeleteDelaySecs(), TimeUnit.SECONDS));
1111 public void cancelDeleteLogicalSwitch(final NodeId hwvtepNodeId, final String lsName) {
1112 Pair<NodeId, String> nodeIdLogicalSwitchNamePair = new ImmutablePair<>(hwvtepNodeId, lsName);
1113 ScheduledFuture logicalSwitchDeleteTask = logicalSwitchDeletedTasks.remove(nodeIdLogicalSwitchNamePair);
1114 if (logicalSwitchDeleteTask != null) {
1115 LOG.debug("Delete logical switch {} action on node {} cancelled", lsName, hwvtepNodeId);
1116 logicalSwitchDeleteTask.cancel(true);
1117 DeleteLogicalSwitchJob deleteLogicalSwitchJob = deleteJobs.remove(nodeIdLogicalSwitchNamePair);
1118 if (deleteLogicalSwitchJob != null) {
1119 deleteLogicalSwitchJob.cancel();
1125 public Collection<DpnInterfaces> getElanDpns(String elanName) {
1126 Collection<DpnInterfaces> dpnInterfaces = elanInstanceDpnsCache.get(elanName);
1127 if (!dpnInterfaces.isEmpty()) {
1128 return dpnInterfaces;
1131 return elanUtils.getElanDPNByName(elanName);
1135 * Gets the l2 gw device local macs.
1140 * @return the l2 gw device local macs
1142 public Collection<MacAddress> getL2GwDeviceLocalMacs(String elanName, L2GatewayDevice l2gwDevice) {
1143 if (l2gwDevice == null) {
1144 return Collections.emptyList();
1146 Collection<LocalUcastMacs> lstUcastLocalMacs = l2gwDevice.getUcastLocalMacs();
1147 Set<MacAddress> macs = new HashSet<>();
1148 if (!lstUcastLocalMacs.isEmpty()) {
1149 macs.addAll(lstUcastLocalMacs.stream().filter(Objects::nonNull)
1150 .map(mac -> new MacAddress(mac.getMacEntryKey().getValue().toLowerCase()))
1151 .collect(Collectors.toList()));
1153 Optional<Node> configNode = MDSALUtil.read(broker, LogicalDatastoreType.CONFIGURATION,
1154 HwvtepSouthboundUtils.createInstanceIdentifier(new NodeId(l2gwDevice.getHwvtepNodeId())));
1155 if (configNode.isPresent()) {
1156 HwvtepGlobalAugmentation augmentation = configNode.get().augmentation(HwvtepGlobalAugmentation.class);
1157 if (augmentation != null && augmentation.getLocalUcastMacs() != null) {
1158 macs.addAll(augmentation.getLocalUcastMacs().stream()
1159 .filter(mac -> getLogicalSwitchName(mac).equals(elanName))
1160 .map(HwvtepMacTableGenericAttributes::getMacEntryKey)
1161 .collect(Collectors.toSet()));