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