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