Bc Group population during cluster reboot
[netvirt.git] / elanmanager / impl / src / main / java / org / opendaylight / netvirt / elan / l2gw / utils / ElanL2GatewayMulticastUtils.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 java.util.Collections.emptyList;
11 import static org.opendaylight.genius.infra.Datastore.CONFIGURATION;
12 import static org.opendaylight.netvirt.elan.utils.ElanUtils.isVxlanNetworkOrVxlanSegment;
13
14 import com.google.common.base.Optional;
15 import com.google.common.util.concurrent.Futures;
16 import com.google.common.util.concurrent.ListenableFuture;
17 import java.math.BigInteger;
18 import java.util.ArrayList;
19 import java.util.Arrays;
20 import java.util.Collection;
21 import java.util.HashSet;
22 import java.util.List;
23 import java.util.Objects;
24 import java.util.Set;
25 import javax.inject.Inject;
26 import javax.inject.Singleton;
27 import org.eclipse.jdt.annotation.NonNull;
28 import org.eclipse.jdt.annotation.Nullable;
29 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
30 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
31 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
32 import org.opendaylight.genius.datastoreutils.SingleTransactionDataBroker;
33 import org.opendaylight.genius.infra.Datastore;
34 import org.opendaylight.genius.infra.ManagedNewTransactionRunner;
35 import org.opendaylight.genius.infra.ManagedNewTransactionRunnerImpl;
36 import org.opendaylight.genius.infra.TypedWriteTransaction;
37 import org.opendaylight.genius.interfacemanager.interfaces.IInterfaceManager;
38 import org.opendaylight.genius.mdsalutil.MDSALUtil;
39 import org.opendaylight.genius.mdsalutil.actions.ActionGroup;
40 import org.opendaylight.genius.mdsalutil.interfaces.IMdsalApiManager;
41 import org.opendaylight.genius.utils.batching.ResourceBatchingManager;
42 import org.opendaylight.genius.utils.hwvtep.HwvtepSouthboundUtils;
43 import org.opendaylight.genius.utils.hwvtep.HwvtepUtils;
44 import org.opendaylight.infrautils.jobcoordinator.JobCoordinator;
45 import org.opendaylight.infrautils.utils.concurrent.LoggingFutures;
46 import org.opendaylight.netvirt.elan.l2gw.jobs.HwvtepDeviceMcastMacUpdateJob;
47 import org.opendaylight.netvirt.elan.l2gw.jobs.McastUpdateJob;
48 import org.opendaylight.netvirt.elan.utils.ElanClusterUtils;
49 import org.opendaylight.netvirt.elan.utils.ElanConstants;
50 import org.opendaylight.netvirt.elan.utils.ElanItmUtils;
51 import org.opendaylight.netvirt.elan.utils.ElanUtils;
52 import org.opendaylight.netvirt.elan.utils.Scheduler;
53 import org.opendaylight.netvirt.elanmanager.utils.ElanL2GwCacheUtils;
54 import org.opendaylight.netvirt.neutronvpn.api.l2gw.L2GatewayDevice;
55 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
56 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupTypes;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.group.buckets.Bucket;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.Group;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.dhcp.rev160428.DesignatedSwitchesForExternalTunnels;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.dhcp.rev160428.designated.switches._for.external.tunnels.DesignatedSwitchForTunnel;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.dhcp.rev160428.designated.switches._for.external.tunnels.DesignatedSwitchForTunnelKey;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInstance;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInstances;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.ElanDpnInterfacesList;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.elan.dpn.interfaces.list.DpnInterfaces;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.ElanInstance;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.ElanInstanceKey;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.elan.instance.ExternalTeps;
71 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.elan.instance.ExternalTepsBuilder;
72 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.elan.instance.ExternalTepsKey;
73 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.HwvtepLogicalSwitchRef;
74 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.HwvtepNodeName;
75 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.HwvtepPhysicalLocatorAugmentation;
76 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.HwvtepPhysicalLocatorRef;
77 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.hwvtep.global.attributes.LogicalSwitches;
78 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.hwvtep.global.attributes.RemoteMcastMacs;
79 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.hwvtep.global.attributes.RemoteMcastMacsBuilder;
80 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.hwvtep.global.attributes.RemoteMcastMacsKey;
81 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.hwvtep.physical.locator.set.attributes.LocatorSet;
82 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.hwvtep.physical.locator.set.attributes.LocatorSetBuilder;
83 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
84 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.node.TerminationPoint;
85 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.node.TerminationPointBuilder;
86 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
87 import org.slf4j.Logger;
88 import org.slf4j.LoggerFactory;
89
90 /**
91  * The utility class to handle ELAN L2 Gateway related to multicast.
92  */
93 @Singleton
94 public class ElanL2GatewayMulticastUtils {
95
96     /** The Constant LOG. */
97     private static final Logger LOG = LoggerFactory.getLogger(ElanL2GatewayMulticastUtils.class);
98
99     /** The broker. */
100     private final DataBroker broker;
101     private final ManagedNewTransactionRunner txRunner;
102
103     private final ElanItmUtils elanItmUtils;
104     private final JobCoordinator jobCoordinator;
105     private final ElanUtils elanUtils;
106     private final IMdsalApiManager mdsalManager;
107     private final IInterfaceManager interfaceManager;
108     private final ElanRefUtil elanRefUtil;
109     private final ElanClusterUtils elanClusterUtils;
110     private final Scheduler scheduler;
111
112
113     @Inject
114     public ElanL2GatewayMulticastUtils(ElanItmUtils elanItmUtils, ElanUtils elanUtils, IMdsalApiManager mdsalManager,
115                                        IInterfaceManager interfaceManager, ElanRefUtil elanRefUtil) {
116         this.elanRefUtil = elanRefUtil;
117         this.broker = elanRefUtil.getDataBroker();
118         this.txRunner = new ManagedNewTransactionRunnerImpl(elanRefUtil.getDataBroker());
119         this.elanItmUtils = elanItmUtils;
120         this.jobCoordinator = elanRefUtil.getJobCoordinator();
121         this.elanUtils = elanUtils;
122         this.mdsalManager = mdsalManager;
123         this.interfaceManager = interfaceManager;
124         this.elanClusterUtils = elanRefUtil.getElanClusterUtils();
125         this.scheduler = elanRefUtil.getScheduler();
126     }
127
128     /**
129      * Handle mcast for elan l2 gw device add.
130      * @param elanName the elan name
131      * @param device the device
132      */
133     public void handleMcastForElanL2GwDeviceAdd(String elanName, L2GatewayDevice device) {
134         InstanceIdentifier<ExternalTeps> tepPath = buildExternalTepPath(elanName, device.getTunnelIp());
135         LoggingFutures.addErrorLogging(txRunner.callWithNewWriteOnlyTransactionAndSubmit(CONFIGURATION,
136             tx -> tx.put(tepPath, buildExternalTeps(device))), LOG, "Failed to write to config external tep {}",
137             tepPath);
138         updateMcastMacsForAllElanDevices(elanName, device, true/* updateThisDevice */);
139     }
140
141     public static InstanceIdentifier<ExternalTeps> buildExternalTepPath(String elan, IpAddress tepIp) {
142         return InstanceIdentifier.builder(ElanInstances.class).child(ElanInstance.class, new ElanInstanceKey(elan))
143                 .child(ExternalTeps.class, new ExternalTepsKey(tepIp)).build();
144     }
145
146     protected ExternalTeps buildExternalTeps(L2GatewayDevice device) {
147         return new ExternalTepsBuilder().setTepIp(device.getTunnelIp()).setNodeid(device.getHwvtepNodeId()).build();
148     }
149
150     /**
151      * Updates the remote mcast mac table for all the devices in this elan
152      * includes all the dpn tep ips and other devices tep ips in broadcast
153      * locator set.
154      *
155      * @param elanName
156      *            the elan to be updated
157      */
158     public void updateRemoteMcastMacOnElanL2GwDevices(String elanName) {
159         for (L2GatewayDevice device : ElanL2GwCacheUtils.getInvolvedL2GwDevices(elanName)) {
160             prepareRemoteMcastMacUpdateOnDevice(elanName, device, false, null);
161         }
162     }
163
164     public void scheduleMcastMacUpdateJob(String elanName, L2GatewayDevice device) {
165         HwvtepDeviceMcastMacUpdateJob job = new HwvtepDeviceMcastMacUpdateJob(this, elanName,device);
166         jobCoordinator.enqueueJob(job.getJobKey(), job);
167     }
168
169     /**
170      * Update remote mcast mac on elan l2 gw device.
171      *
172      * @param elanName
173      *            the elan name
174      * @param device
175      *            the device
176      */
177     public void updateRemoteMcastMacOnElanL2GwDevice(String elanName, L2GatewayDevice device) {
178         prepareRemoteMcastMacUpdateOnDevice(elanName, device, false, null);
179     }
180
181     public ListenableFuture<Void> prepareRemoteMcastMacUpdateOnDevice(String elanName, L2GatewayDevice device,
182                                                                       boolean addCase, IpAddress removedDstTep) {
183         NodeId dstNodeId = new NodeId(device.getHwvtepNodeId());
184         RemoteMcastMacs existingMac = null;
185         try {
186             Optional<RemoteMcastMacs> mac  = elanRefUtil.getConfigMcastCache().get(getRemoteMcastIid(dstNodeId,
187                     elanName));
188             if (mac.isPresent()) {
189                 existingMac = mac.get();
190             }
191         } catch (ReadFailedException e) {
192             LOG.error("Failed to read iid for elan {}", elanName, e);
193         }
194
195         if (!addCase && removedDstTep != null) {
196             LOG.debug(" RemoteMcast update delete tep {} of elan {} ", removedDstTep.getIpv4Address().getValue(),
197                     elanName);
198             //incase of dpn flap immediately after cluster reboot just remove its tep alone
199             if (existingMac != null) {
200                 return deleteLocatorFromMcast(elanName, dstNodeId, removedDstTep, existingMac);
201             }
202         }
203         Collection<L2GatewayDevice> elanL2gwDevices = ElanL2GwCacheUtils.getInvolvedL2GwDevices(elanName);
204         Collection<DpnInterfaces> dpns = elanRefUtil.getElanInstanceDpnsCache().get(elanName);
205         List<IpAddress> dpnsTepIps = getAllTepIpsOfDpns(device, dpns);
206         List<IpAddress> l2GwDevicesTepIps = getAllTepIpsOfL2GwDevices(elanL2gwDevices);
207         return prepareRemoteMcastMacEntry(elanName, device, dpnsTepIps, l2GwDevicesTepIps, addCase);
208     }
209
210     private ListenableFuture<Void> deleteLocatorFromMcast(String elanName, NodeId dstNodeId,
211                                                           IpAddress removedDstTep,
212                                                           RemoteMcastMacs existingMac) {
213         InstanceIdentifier<RemoteMcastMacs> macIid = HwvtepSouthboundUtils
214                 .createRemoteMcastMacsInstanceIdentifier(dstNodeId, existingMac.key());
215         LocatorSet tobeDeleted = buildLocatorSet(dstNodeId, removedDstTep);
216         RemoteMcastMacsBuilder newMacBuilder = new RemoteMcastMacsBuilder(existingMac);
217         newMacBuilder.getLocatorSet().remove(tobeDeleted);
218         RemoteMcastMacs mac = newMacBuilder.build();
219         //configMcastCache.add(macIid, mac);
220         return ResourceBatchingManager.getInstance().put(
221                 ResourceBatchingManager.ShardResource.CONFIG_TOPOLOGY, macIid, mac);
222     }
223
224     LocatorSet buildLocatorSet(NodeId nodeId, IpAddress tepIp) {
225         HwvtepPhysicalLocatorAugmentation phyLocatorAug = HwvtepSouthboundUtils
226                 .createHwvtepPhysicalLocatorAugmentation(tepIp.stringValue());
227         HwvtepPhysicalLocatorRef phyLocRef = new HwvtepPhysicalLocatorRef(
228                 HwvtepSouthboundUtils.createPhysicalLocatorInstanceIdentifier(nodeId, phyLocatorAug));
229         return new LocatorSetBuilder().setLocatorRef(phyLocRef).build();
230     }
231
232     /**
233      * Update mcast macs for this elan.
234      * for all dpns in this elan  recompute and update broadcast group
235      * for all l2gw devices in this elan recompute and update remote mcast mac entry
236      *
237      * @param elanName
238      *            the elan name
239      * @param device
240      *            the device
241      * @param updateThisDevice
242      *            the update this device
243      */
244     public void updateMcastMacsForAllElanDevices(String elanName, L2GatewayDevice device,
245                                                                     boolean updateThisDevice) {
246         if (updateThisDevice) {
247             McastUpdateJob.updateAllMcastsForConnectionAdd(elanName, this, elanClusterUtils);
248         } else {
249             McastUpdateJob.updateAllMcastsForConnectionDelete(elanName, this, elanClusterUtils, device);
250         }
251     }
252
253     public void updateRemoteBroadcastGroupForAllElanDpns(ElanInstance elanInfo, boolean createCase,
254             TypedWriteTransaction<Datastore.Configuration> confTx) {
255         List<DpnInterfaces> dpns = elanUtils.getInvolvedDpnsInElan(elanInfo.getElanInstanceName());
256         for (DpnInterfaces dpn : dpns) {
257             setupStandardElanBroadcastGroups(elanInfo, null, dpn.getDpId(), createCase, confTx);
258         }
259     }
260
261     public void setupElanBroadcastGroups(ElanInstance elanInfo, BigInteger dpnId,
262             TypedWriteTransaction<Datastore.Configuration> confTx) {
263         setupElanBroadcastGroups(elanInfo, null, dpnId, confTx);
264     }
265
266     public void setupElanBroadcastGroups(ElanInstance elanInfo, @Nullable DpnInterfaces dpnInterfaces, BigInteger dpnId,
267                                          TypedWriteTransaction<Datastore.Configuration> confTx) {
268         setupStandardElanBroadcastGroups(elanInfo, dpnInterfaces, dpnId, confTx);
269         setupLeavesEtreeBroadcastGroups(elanInfo, dpnInterfaces, dpnId, confTx);
270     }
271
272     public void setupStandardElanBroadcastGroups(ElanInstance elanInfo, DpnInterfaces dpnInterfaces, BigInteger dpnId,
273                                                  TypedWriteTransaction<Datastore.Configuration> confTx) {
274         setupStandardElanBroadcastGroups(elanInfo, dpnInterfaces, dpnId, true, confTx);
275     }
276
277     public void setupStandardElanBroadcastGroups(ElanInstance elanInfo, @Nullable DpnInterfaces dpnInterfaces,
278             BigInteger dpnId, boolean createCase, TypedWriteTransaction<Datastore.Configuration> confTx) {
279         List<Bucket> listBucket = new ArrayList<>();
280         int bucketId = 0;
281         int actionKey = 0;
282         Long elanTag = elanInfo.getElanTag();
283         List<Action> listAction = new ArrayList<>();
284         listAction.add(new ActionGroup(ElanUtils.getElanLocalBCGId(elanTag)).buildAction(++actionKey));
285         listBucket.add(MDSALUtil.buildBucket(listAction, MDSALUtil.GROUP_WEIGHT, bucketId, MDSALUtil.WATCH_PORT,
286                 MDSALUtil.WATCH_GROUP));
287         bucketId++;
288         List<Bucket> listBucketInfoRemote = getRemoteBCGroupBuckets(elanInfo, dpnInterfaces, dpnId, bucketId, elanTag);
289         listBucket.addAll(listBucketInfoRemote);
290         long groupId = ElanUtils.getElanRemoteBCGId(elanTag);
291         Group group = MDSALUtil.buildGroup(groupId, elanInfo.getElanInstanceName(), GroupTypes.GroupAll,
292                 MDSALUtil.buildBucketLists(listBucket));
293         LOG.trace("Installing the remote BroadCast Group:{}", group);
294         if (createCase) {
295             elanUtils.syncUpdateGroup(dpnId, group, ElanConstants.DELAY_TIME_IN_MILLISECOND, confTx);
296         } else {
297             mdsalManager.addGroup(confTx, dpnId, group);
298         }
299     }
300
301     public void setupLeavesEtreeBroadcastGroups(ElanInstance elanInfo, @Nullable DpnInterfaces dpnInterfaces,
302             BigInteger dpnId, TypedWriteTransaction<Datastore.Configuration> confTx) {
303         EtreeInstance etreeInstance = elanInfo.augmentation(EtreeInstance.class);
304         if (etreeInstance != null) {
305             long etreeLeafTag = etreeInstance.getEtreeLeafTagVal().getValue();
306             List<Bucket> listBucket = new ArrayList<>();
307             int bucketId = 0;
308             int actionKey = 0;
309             List<Action> listAction = new ArrayList<>();
310             listAction.add(new ActionGroup(ElanUtils.getEtreeLeafLocalBCGId(etreeLeafTag)).buildAction(++actionKey));
311             listBucket.add(MDSALUtil.buildBucket(listAction, MDSALUtil.GROUP_WEIGHT, bucketId, MDSALUtil.WATCH_PORT,
312                     MDSALUtil.WATCH_GROUP));
313             bucketId++;
314             List<Bucket> listBucketInfoRemote = getRemoteBCGroupBuckets(elanInfo, dpnInterfaces, dpnId, bucketId,
315                     etreeLeafTag);
316             listBucket.addAll(listBucketInfoRemote);
317             long groupId = ElanUtils.getEtreeLeafRemoteBCGId(etreeLeafTag);
318             Group group = MDSALUtil.buildGroup(groupId, elanInfo.getElanInstanceName(), GroupTypes.GroupAll,
319                     MDSALUtil.buildBucketLists(listBucket));
320             LOG.trace("Installing the remote BroadCast Group:{}", group);
321             mdsalManager.addGroup(confTx, dpnId, group);
322         }
323     }
324
325     @Nullable
326     private static DpnInterfaces getDpnInterfaces(ElanDpnInterfacesList elanDpns, BigInteger dpnId) {
327         if (elanDpns != null) {
328             for (DpnInterfaces dpnInterface : elanDpns.nonnullDpnInterfaces()) {
329                 if (Objects.equals(dpnInterface.getDpId(), dpnId)) {
330                     return dpnInterface;
331                 }
332             }
333         }
334         return null;
335     }
336
337     private List<Bucket> getRemoteBCGroupExternalPortBuckets(ElanDpnInterfacesList elanDpns,
338             DpnInterfaces dpnInterfaces, BigInteger dpnId, int bucketId) {
339         DpnInterfaces currDpnInterfaces = dpnInterfaces != null ? dpnInterfaces : getDpnInterfaces(elanDpns, dpnId);
340         if (currDpnInterfaces == null || !elanUtils.isDpnPresent(currDpnInterfaces.getDpId())
341                 || currDpnInterfaces.getInterfaces() == null || currDpnInterfaces.getInterfaces().isEmpty()) {
342             return emptyList();
343         }
344         List<Bucket> listBucketInfo = new ArrayList<>();
345         for (String interfaceName : currDpnInterfaces.getInterfaces()) {
346             if (interfaceManager.isExternalInterface(interfaceName)) {
347                 List<Action> listActionInfo = elanItmUtils.getExternalPortItmEgressAction(interfaceName);
348                 if (!listActionInfo.isEmpty()) {
349                     listBucketInfo.add(MDSALUtil.buildBucket(listActionInfo, MDSALUtil.GROUP_WEIGHT, bucketId,
350                             MDSALUtil.WATCH_PORT, MDSALUtil.WATCH_GROUP));
351                     bucketId++;
352                 }
353             }
354         }
355         return listBucketInfo;
356     }
357
358     @NonNull
359     public List<Bucket> getRemoteBCGroupBuckets(ElanInstance elanInfo, @Nullable DpnInterfaces dpnInterfaces,
360                                                 BigInteger dpnId, int bucketId, long elanTag) {
361         List<Bucket> listBucketInfo = new ArrayList<>();
362         ElanDpnInterfacesList elanDpns = elanUtils.getElanDpnInterfacesList(elanInfo.getElanInstanceName());
363
364         if (isVxlanNetworkOrVxlanSegment(elanInfo)) {
365             listBucketInfo.addAll(getRemoteBCGroupTunnelBuckets(elanDpns, dpnId, bucketId,
366                     elanUtils.isOpenstackVniSemanticsEnforced()
367                             ? ElanUtils.getVxlanSegmentationId(elanInfo) : elanTag));
368         }
369         listBucketInfo.addAll(getRemoteBCGroupExternalPortBuckets(elanDpns, dpnInterfaces, dpnId,
370                 getNextAvailableBucketId(listBucketInfo.size())));
371         listBucketInfo.addAll(getRemoteBCGroupBucketsOfElanExternalTeps(elanInfo, dpnId,
372                 getNextAvailableBucketId(listBucketInfo.size())));
373         return listBucketInfo;
374     }
375
376     public List<Bucket> getRemoteBCGroupBucketsOfElanL2GwDevices(ElanInstance elanInfo, BigInteger dpnId,
377             int bucketId) {
378         List<Bucket> listBucketInfo = new ArrayList<>();
379         for (L2GatewayDevice device : ElanL2GwCacheUtils.getInvolvedL2GwDevices(elanInfo.getElanInstanceName())) {
380             String interfaceName = elanItmUtils.getExternalTunnelInterfaceName(String.valueOf(dpnId),
381                     device.getHwvtepNodeId());
382             if (interfaceName == null) {
383                 continue;
384             }
385             List<Action> listActionInfo = elanItmUtils.buildTunnelItmEgressActions(interfaceName,
386                     ElanUtils.getVxlanSegmentationId(elanInfo), true);
387             listBucketInfo.add(MDSALUtil.buildBucket(listActionInfo, MDSALUtil.GROUP_WEIGHT, bucketId,
388                     MDSALUtil.WATCH_PORT, MDSALUtil.WATCH_GROUP));
389             bucketId++;
390         }
391         return listBucketInfo;
392     }
393
394     public List<Bucket> getRemoteBCGroupBucketsOfElanExternalTeps(ElanInstance elanInfo, BigInteger dpnId,
395             int bucketId) {
396         ElanInstance operElanInstance = null;
397         try {
398             operElanInstance = new SingleTransactionDataBroker(broker).syncReadOptional(
399                 LogicalDatastoreType.OPERATIONAL,
400                 InstanceIdentifier.builder(ElanInstances.class).child(ElanInstance.class, elanInfo.key())
401                     .build()).orNull();
402         } catch (ReadFailedException e) {
403             LOG.error("Failed to read elan instance operational path {}", elanInfo, e);
404             return emptyList();
405         }
406         if (operElanInstance == null) {
407             return emptyList();
408         }
409         List<ExternalTeps> teps = operElanInstance.getExternalTeps();
410         if (teps == null || teps.isEmpty()) {
411             return emptyList();
412         }
413         List<Bucket> listBucketInfo = new ArrayList<>();
414         for (ExternalTeps tep : teps) {
415             String externalTep = tep.getNodeid() != null ? tep.getNodeid() : tep.getTepIp().toString();
416             String interfaceName = elanItmUtils.getExternalTunnelInterfaceName(String.valueOf(dpnId),
417                     externalTep);
418             if (interfaceName == null) {
419                 LOG.error("Could not get interface name to ext tunnel {} {}", dpnId, tep.getTepIp());
420                 continue;
421             }
422             List<Action> listActionInfo = elanItmUtils.buildTunnelItmEgressActions(interfaceName,
423                     ElanUtils.getVxlanSegmentationId(elanInfo), false);
424             listBucketInfo.add(MDSALUtil.buildBucket(listActionInfo, MDSALUtil.GROUP_WEIGHT, bucketId,
425                     MDSALUtil.WATCH_PORT, MDSALUtil.WATCH_GROUP));
426             bucketId++;
427         }
428         return listBucketInfo;
429     }
430
431     private static int getNextAvailableBucketId(int bucketSize) {
432         return bucketSize + 1;
433     }
434
435     @SuppressWarnings("checkstyle:IllegalCatch")
436     private List<Bucket> getRemoteBCGroupTunnelBuckets(ElanDpnInterfacesList elanDpns, BigInteger dpnId, int bucketId,
437             long elanTagOrVni) {
438         List<Bucket> listBucketInfo = new ArrayList<>();
439         if (elanDpns != null) {
440             for (DpnInterfaces dpnInterface : elanDpns.nonnullDpnInterfaces())  {
441                 if (!Objects.equals(dpnInterface.getDpId(), dpnId) && dpnInterface.getInterfaces() != null
442                         && !dpnInterface.getInterfaces().isEmpty()) {
443                     try {
444                         List<Action> listActionInfo = elanItmUtils.getInternalTunnelItmEgressAction(dpnId,
445                                 dpnInterface.getDpId(), elanTagOrVni);
446                         if (listActionInfo.isEmpty()) {
447                             continue;
448                         }
449                         listBucketInfo.add(MDSALUtil.buildBucket(listActionInfo, MDSALUtil.GROUP_WEIGHT, bucketId,
450                                 MDSALUtil.WATCH_PORT, MDSALUtil.WATCH_GROUP));
451                         bucketId++;
452                     } catch (Exception ex) {
453                         LOG.error("Logical Group Interface not found between source Dpn - {}, destination Dpn - {} ",
454                                 dpnId, dpnInterface.getDpId(), ex);
455                     }
456                 }
457             }
458         }
459         return listBucketInfo;
460     }
461
462     /**
463      * Update remote mcast mac.
464      *
465      * @param elanName
466      *            the elan name
467      * @param device
468      *            the device
469      * @param dpnsTepIps
470      *            the dpns tep ips
471      * @param l2GwDevicesTepIps
472      *            the l2 gw devices tep ips
473      * @return the write transaction
474      */
475     private ListenableFuture<Void> prepareRemoteMcastMacEntry(String elanName,
476                                              L2GatewayDevice device, List<IpAddress> dpnsTepIps,
477                                              List<IpAddress> l2GwDevicesTepIps, boolean addCase) {
478         NodeId nodeId = new NodeId(device.getHwvtepNodeId());
479
480         ArrayList<IpAddress> remoteTepIps = new ArrayList<>(l2GwDevicesTepIps);
481         remoteTepIps.remove(device.getTunnelIp());
482         remoteTepIps.addAll(dpnsTepIps);
483         IpAddress dhcpDesignatedSwitchTepIp = getTepIpOfDesignatedSwitchForExternalTunnel(device, elanName);
484         if (dpnsTepIps.isEmpty()) {
485             // If no dpns in elan, configure dhcp designated switch Tep Ip as a
486             // physical locator in l2 gw device
487             if (dhcpDesignatedSwitchTepIp != null) {
488                 remoteTepIps.add(dhcpDesignatedSwitchTepIp);
489
490                 HwvtepPhysicalLocatorAugmentation phyLocatorAug = HwvtepSouthboundUtils
491                         .createHwvtepPhysicalLocatorAugmentation(dhcpDesignatedSwitchTepIp);
492                 InstanceIdentifier<TerminationPoint> iid =
493                         HwvtepSouthboundUtils.createPhysicalLocatorInstanceIdentifier(nodeId, phyLocatorAug);
494                 TerminationPoint terminationPoint = new TerminationPointBuilder()
495                                 .withKey(HwvtepSouthboundUtils.getTerminationPointKey(phyLocatorAug))
496                                 .addAugmentation(HwvtepPhysicalLocatorAugmentation.class, phyLocatorAug).build();
497                 ResourceBatchingManager.getInstance().put(ResourceBatchingManager.ShardResource.CONFIG_TOPOLOGY,
498                         iid, terminationPoint);
499                 LOG.info("Adding PhysicalLocator for node: {} with Dhcp designated switch Tep Ip {} "
500                         + "as physical locator, elan {}", device.getHwvtepNodeId(),
501                         dhcpDesignatedSwitchTepIp.stringValue(), elanName);
502             } else {
503                 LOG.warn("Dhcp designated switch Tep Ip not found for l2 gw node {} and elan {}",
504                         device.getHwvtepNodeId(), elanName);
505             }
506         }
507         if (dhcpDesignatedSwitchTepIp != null && !remoteTepIps.contains(dhcpDesignatedSwitchTepIp)) {
508             remoteTepIps.add(dhcpDesignatedSwitchTepIp);
509         }
510         String logicalSwitchName = ElanL2GatewayUtils.getLogicalSwitchFromElan(elanName);
511         LOG.info("Adding RemoteMcastMac for node: {} with physical locators: {}", device.getHwvtepNodeId(),
512                 remoteTepIps);
513         return putRemoteMcastMac(nodeId, logicalSwitchName, remoteTepIps, addCase);
514     }
515
516     /**
517      * Put remote mcast mac in config DS.
518      *
519      * @param nodeId
520      *            the node id
521      * @param logicalSwitchName
522      *            the logical switch name
523      * @param tepIps
524      *            the tep ips
525      */
526     private ListenableFuture<Void> putRemoteMcastMac(NodeId nodeId, String logicalSwitchName,
527             ArrayList<IpAddress> tepIps, boolean addCase) {
528         List<LocatorSet> locators = new ArrayList<>();
529         for (IpAddress tepIp : tepIps) {
530             HwvtepPhysicalLocatorAugmentation phyLocatorAug = HwvtepSouthboundUtils
531                     .createHwvtepPhysicalLocatorAugmentation(tepIp);
532             HwvtepPhysicalLocatorRef phyLocRef = new HwvtepPhysicalLocatorRef(
533                     HwvtepSouthboundUtils.createPhysicalLocatorInstanceIdentifier(nodeId, phyLocatorAug));
534             locators.add(new LocatorSetBuilder().setLocatorRef(phyLocRef).build());
535         }
536
537         HwvtepLogicalSwitchRef lsRef = new HwvtepLogicalSwitchRef(HwvtepSouthboundUtils
538                 .createLogicalSwitchesInstanceIdentifier(nodeId, new HwvtepNodeName(logicalSwitchName)));
539         RemoteMcastMacs newRemoteMcastMac = new RemoteMcastMacsBuilder()
540                 .setMacEntryKey(new MacAddress(ElanConstants.UNKNOWN_DMAC)).setLogicalSwitchRef(lsRef)
541                 .setLocatorSet(locators).build();
542         InstanceIdentifier<RemoteMcastMacs> iid = HwvtepSouthboundUtils.createRemoteMcastMacsInstanceIdentifier(nodeId,
543                 newRemoteMcastMac.key());
544         RemoteMcastMacs existingRemoteMcastMac = null;
545         try {
546             Optional<RemoteMcastMacs> mac  = elanRefUtil.getConfigMcastCache().get(iid);
547             if (mac.isPresent()) {
548                 existingRemoteMcastMac = mac.get();
549             }
550         } catch (ReadFailedException e) {
551             LOG.error("Failed to read iid {}", iid, e);
552         }
553
554         if (addCase && areLocatorsAlreadyConfigured(existingRemoteMcastMac, newRemoteMcastMac)) {
555             return Futures.immediateFuture(null);
556         }
557
558         return ResourceBatchingManager.getInstance().put(ResourceBatchingManager.ShardResource.CONFIG_TOPOLOGY,
559                 iid, newRemoteMcastMac);
560
561     }
562
563     private boolean areLocatorsAlreadyConfigured(RemoteMcastMacs existingMac, RemoteMcastMacs newMac) {
564         if (existingMac == null) {
565             return false;
566         }
567         Set existingLocators = new HashSet<>(existingMac.getLocatorSet());
568         List newLocators = newMac.getLocatorSet();
569         return existingLocators.containsAll(newLocators);
570     }
571
572     private InstanceIdentifier<RemoteMcastMacs> getRemoteMcastIid(NodeId nodeId, String logicalSwitchName) {
573         HwvtepLogicalSwitchRef lsRef = new HwvtepLogicalSwitchRef(HwvtepSouthboundUtils
574                 .createLogicalSwitchesInstanceIdentifier(nodeId, new HwvtepNodeName(logicalSwitchName)));
575         RemoteMcastMacs remoteMcastMac = new RemoteMcastMacsBuilder()
576                 .setMacEntryKey(new MacAddress(ElanConstants.UNKNOWN_DMAC)).setLogicalSwitchRef(lsRef)
577                 .build();
578         return HwvtepSouthboundUtils.createRemoteMcastMacsInstanceIdentifier(nodeId,
579                 remoteMcastMac.key());
580     }
581
582     /**
583      * Gets all the tep ips of dpns.
584      *
585      * @param l2GwDevice
586      *            the device
587      * @param dpns
588      *            the dpns
589      * @return the all tep ips of dpns and devices
590      */
591     private List<IpAddress> getAllTepIpsOfDpns(L2GatewayDevice l2GwDevice, Collection<DpnInterfaces> dpns) {
592         List<IpAddress> tepIps = new ArrayList<>();
593         for (DpnInterfaces dpn : dpns) {
594             IpAddress internalTunnelIp = elanItmUtils.getSourceDpnTepIp(dpn.getDpId(),
595                     new NodeId(l2GwDevice.getHwvtepNodeId()));
596             if (internalTunnelIp != null) {
597                 tepIps.add(internalTunnelIp);
598             }
599         }
600         return tepIps;
601     }
602
603     /**
604      * Gets the all tep ips of l2 gw devices.
605      *
606      * @param devices
607      *            the devices
608      * @return the all tep ips of l2 gw devices
609      */
610     private static List<IpAddress> getAllTepIpsOfL2GwDevices(Collection<L2GatewayDevice> devices) {
611         List<IpAddress> tepIps = new ArrayList<>();
612         for (L2GatewayDevice otherDevice : devices) {
613             // There is no need to add the same tep ip to the list.
614             if (!tepIps.contains(otherDevice.getTunnelIp())) {
615                 tepIps.add(otherDevice.getTunnelIp());
616             }
617         }
618         return tepIps;
619     }
620
621     /**
622      * Handle mcast for elan l2 gw device delete.
623      *
624      * @param elanName
625      *            the elan instance name
626      * @param l2GatewayDevice
627      *            the l2 gateway device
628      * @return the listenable future
629      */
630     public List<ListenableFuture<Void>> handleMcastForElanL2GwDeviceDelete(String elanName,
631                                                                            L2GatewayDevice l2GatewayDevice) {
632         ListenableFuture<Void> deleteTepFuture =
633             txRunner.callWithNewWriteOnlyTransactionAndSubmit(CONFIGURATION,
634                 tx -> tx.delete(buildExternalTepPath(elanName, l2GatewayDevice.getTunnelIp())));
635         updateMcastMacsForAllElanDevices(elanName, l2GatewayDevice, false/* updateThisDevice */);
636         ListenableFuture<Void> deleteRemoteMcastMacFuture = deleteRemoteMcastMac(
637                 new NodeId(l2GatewayDevice.getHwvtepNodeId()), elanName);
638         return Arrays.asList(deleteRemoteMcastMacFuture, deleteTepFuture);
639     }
640
641     /**
642      * Delete remote mcast mac from Hwvtep node.
643      *
644      * @param nodeId
645      *            the node id
646      * @param logicalSwitchName
647      *            the logical switch name
648      * @return the listenable future
649      */
650     public ListenableFuture<Void> deleteRemoteMcastMac(NodeId nodeId, String logicalSwitchName) {
651         InstanceIdentifier<LogicalSwitches> logicalSwitch = HwvtepSouthboundUtils
652                 .createLogicalSwitchesInstanceIdentifier(nodeId, new HwvtepNodeName(logicalSwitchName));
653         RemoteMcastMacsKey remoteMcastMacsKey = new RemoteMcastMacsKey(new HwvtepLogicalSwitchRef(logicalSwitch),
654                 new MacAddress(ElanConstants.UNKNOWN_DMAC));
655
656         LOG.info("Deleting RemoteMcastMacs entry on node: {} for logical switch: {}", nodeId.getValue(),
657                 logicalSwitchName);
658         return HwvtepUtils.deleteRemoteMcastMac(broker, nodeId, remoteMcastMacsKey);
659     }
660
661     /**
662      * Gets the tep ip of designated switch for external tunnel.
663      *
664      * @param l2GwDevice
665      *            the l2 gw device
666      * @param elanInstanceName
667      *            the elan instance name
668      * @return the tep ip of designated switch for external tunnel
669      */
670     public IpAddress getTepIpOfDesignatedSwitchForExternalTunnel(L2GatewayDevice l2GwDevice,
671             String elanInstanceName) {
672         IpAddress tepIp = null;
673         if (l2GwDevice.getTunnelIp() == null) {
674             LOG.warn("Tunnel IP not found for {}", l2GwDevice.getDeviceName());
675             return tepIp;
676         }
677         DesignatedSwitchForTunnel desgSwitch = getDesignatedSwitchForExternalTunnel(l2GwDevice.getTunnelIp(),
678                 elanInstanceName);
679         if (desgSwitch != null) {
680             tepIp = elanItmUtils.getSourceDpnTepIp(BigInteger.valueOf(desgSwitch.getDpId()),
681                     new NodeId(l2GwDevice.getHwvtepNodeId()));
682         }
683         return tepIp;
684     }
685
686     /**
687      * Gets the designated switch for external tunnel.
688      *
689      * @param tunnelIp
690      *            the tunnel ip
691      * @param elanInstanceName
692      *            the elan instance name
693      * @return the designated switch for external tunnel
694      */
695     public DesignatedSwitchForTunnel getDesignatedSwitchForExternalTunnel(IpAddress tunnelIp,
696             String elanInstanceName) {
697         InstanceIdentifier<DesignatedSwitchForTunnel> instanceIdentifier = InstanceIdentifier
698                 .builder(DesignatedSwitchesForExternalTunnels.class)
699                 .child(DesignatedSwitchForTunnel.class, new DesignatedSwitchForTunnelKey(elanInstanceName, tunnelIp))
700                 .build();
701         return MDSALUtil.read(broker, LogicalDatastoreType.CONFIGURATION, instanceIdentifier).orNull();
702     }
703
704 }