Clean up collections of Futures
[genius.git] / itm / itm-impl / src / main / java / org / opendaylight / genius / itm / confighelpers / ItmInternalTunnelDeleteWorker.java
1 /*
2  * Copyright (c) 2016, 2017 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.genius.itm.confighelpers;
9
10 import com.google.common.base.Optional;
11 import com.google.common.util.concurrent.ListenableFuture;
12 import java.math.BigInteger;
13 import java.util.ArrayList;
14 import java.util.Collection;
15 import java.util.Collections;
16 import java.util.List;
17 import java.util.concurrent.Callable;
18
19 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
20 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
21 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
22 import org.opendaylight.genius.datastoreutils.DataStoreJobCoordinator;
23 import org.opendaylight.genius.itm.impl.ItmUtils;
24 import org.opendaylight.genius.mdsalutil.interfaces.IMdsalApiManager;
25 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.Interface;
26 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.IdManagerService;
27 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelMonitoringTypeBase;
28 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelMonitoringTypeLldp;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelTypeBase;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelTypeLogicalGroup;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelTypeVxlan;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.DpnEndpoints;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.TunnelList;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.dpn.endpoints.DPNTEPsInfo;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.dpn.endpoints.dpn.teps.info.TunnelEndPoints;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.dpn.endpoints.dpn.teps.info.TunnelEndPointsBuilder;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.dpn.endpoints.dpn.teps.info.tunnel.end.points.TzMembership;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.tunnel.list.InternalTunnel;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.tunnel.list.InternalTunnelKey;
40 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43
44 public class ItmInternalTunnelDeleteWorker {
45     private static final Logger LOG = LoggerFactory.getLogger(ItmInternalTunnelDeleteWorker.class) ;
46
47     @SuppressWarnings("checkstyle:IllegalCatch")
48     public static List<ListenableFuture<Void>> deleteTunnels(DataBroker dataBroker, IdManagerService idManagerService,
49                                                              IMdsalApiManager mdsalManager,
50                                                              List<DPNTEPsInfo> dpnTepsList,
51                                                              List<DPNTEPsInfo> meshedDpnList) {
52         LOG.trace("TEPs to be deleted {} " , dpnTepsList);
53         List<ListenableFuture<Void>> futures = new ArrayList<>();
54         WriteTransaction writeTransaction = dataBroker.newWriteOnlyTransaction();
55         try {
56             if (dpnTepsList == null || dpnTepsList.size() == 0) {
57                 LOG.debug("no vtep to delete");
58                 return futures ;
59             }
60
61             if (meshedDpnList == null || meshedDpnList.size() == 0) {
62                 LOG.debug("No Meshed Vteps");
63                 return futures ;
64             }
65             for (DPNTEPsInfo srcDpn : dpnTepsList) {
66                 LOG.trace("Processing srcDpn {}", srcDpn);
67
68                 List<TunnelEndPoints> meshedEndPtCache = ItmUtils.getTEPsForDpn(srcDpn.getDPNID(), meshedDpnList);
69                 if (meshedEndPtCache == null) {
70                     LOG.debug("No Tunnel End Point configured for this DPN {}", srcDpn.getDPNID());
71                     continue ;
72                 }
73                 LOG.debug("Entries in meshEndPointCache {} for DPN Id{} ", meshedEndPtCache.size(), srcDpn.getDPNID());
74                 for (TunnelEndPoints srcTep : srcDpn.getTunnelEndPoints()) {
75                     LOG.trace("Processing srcTep {}", srcTep);
76                     List<TzMembership> srcTZones = srcTep.getTzMembership();
77                     boolean tepDeleteFlag = false;
78                     // First, take care of tunnel removal, so run through all other DPNS other than srcDpn
79                     // In the tep received from Delete DCN, the membership list will always be 1
80                     // as the DCN is at transport zone level
81                     // Hence if a tunnel is shared across TZs, compare the original membership list between end points
82                     // to decide if tunnel to be deleted.
83                     for (DPNTEPsInfo dstDpn : meshedDpnList) {
84                         if (!srcDpn.getDPNID().equals(dstDpn.getDPNID())) {
85                             for (TunnelEndPoints dstTep : dstDpn.getTunnelEndPoints()) {
86                                 if (!ItmUtils.getIntersection(dstTep.getTzMembership(), srcTZones).isEmpty()) {
87                                     List<TzMembership> originalTzMembership =
88                                             ItmUtils.getOriginalTzMembership(srcTep, srcDpn.getDPNID(), meshedDpnList);
89                                     if (ItmUtils.getIntersection(dstTep.getTzMembership(), originalTzMembership).size()
90                                             == 1) {
91                                         if (checkIfTrunkExists(dstDpn.getDPNID(), srcDpn.getDPNID(),
92                                                 srcTep.getTunnelType(), dataBroker)) {
93                                             // remove all trunk interfaces
94                                             LOG.trace("Invoking removeTrunkInterface between source TEP {} , "
95                                                     + "Destination TEP {} ", srcTep, dstTep);
96                                             removeTrunkInterface(dataBroker, idManagerService, srcTep, dstTep, srcDpn
97                                                     .getDPNID(), dstDpn.getDPNID(), writeTransaction, futures);
98                                         }
99                                     }
100                                 }
101                             }
102                         }
103                     }
104                     for (DPNTEPsInfo dstDpn : meshedDpnList) {
105                         // Second, take care of Tep TZ membership and identify if tep can be removed
106                         if (srcDpn.getDPNID().equals(dstDpn.getDPNID())) {
107                             // Same DPN, so remove the TZ membership
108                             for (TunnelEndPoints dstTep : dstDpn.getTunnelEndPoints()) {
109                                 if (dstTep.getIpAddress().equals(srcTep.getIpAddress())) {
110                                     // Remove the deleted TZ membership from the TEP
111                                     LOG.debug("Removing TZ list {} from Existing TZ list {} ",
112                                             srcTZones, dstTep.getTzMembership());
113                                     List<TzMembership> updatedList =
114                                             ItmUtils.removeTransportZoneMembership(dstTep, srcTZones);
115                                     if (updatedList.isEmpty()) {
116                                         LOG.debug(" This TEP can be deleted {}", srcTep);
117                                         tepDeleteFlag = true;
118                                     } else {
119                                         TunnelEndPointsBuilder modifiedTepBld = new TunnelEndPointsBuilder(dstTep);
120                                         modifiedTepBld.setTzMembership(updatedList);
121                                         TunnelEndPoints modifiedTep = modifiedTepBld.build() ;
122                                         InstanceIdentifier<TunnelEndPoints> tepPath = InstanceIdentifier
123                                                 .builder(DpnEndpoints.class)
124                                                 .child(DPNTEPsInfo.class, dstDpn.getKey())
125                                                 .child(TunnelEndPoints.class, dstTep.getKey()).build();
126
127                                         LOG.debug(" Store the modified Tep in DS {} ", modifiedTep);
128                                         writeTransaction.put(LogicalDatastoreType.CONFIGURATION, tepPath, modifiedTep);
129                                     }
130                                 }
131                             }
132                         }
133                     }
134                     if (tepDeleteFlag) {
135                         // Third, removing vtep / dpn from Tunnels OpDs.
136                         InstanceIdentifier<TunnelEndPoints> tepPath =
137                                 InstanceIdentifier.builder(DpnEndpoints.class).child(DPNTEPsInfo.class, srcDpn.getKey())
138                                         .child(TunnelEndPoints.class, srcTep.getKey()).build();
139
140                         LOG.trace("Tep Removal of TEP {} from DPNTEPSINFO CONFIG DS with Key {} ",
141                                 srcTep, srcTep.getKey());
142                         writeTransaction.delete(LogicalDatastoreType.CONFIGURATION, tepPath);
143                         // remove the tep from the cache
144                         meshedEndPtCache.remove(srcTep);
145                         Class<? extends TunnelMonitoringTypeBase> monitorProtocol =
146                                 ItmUtils.determineMonitorProtocol(dataBroker);
147                         InstanceIdentifier<DPNTEPsInfo> dpnPath =
148                                 InstanceIdentifier.builder(DpnEndpoints.class).child(DPNTEPsInfo.class, srcDpn.getKey())
149                                         .build();
150
151                         if (meshedEndPtCache.isEmpty()) {
152                             // remove dpn if no vteps exist on dpn
153                             if (monitorProtocol.isAssignableFrom(TunnelMonitoringTypeLldp.class)) {
154                                 LOG.debug("Removing Terminating Service Table Flow ");
155                                 ItmUtils.setUpOrRemoveTerminatingServiceTable(srcDpn.getDPNID(), mdsalManager, false);
156                             }
157                             LOG.trace("DPN Removal from DPNTEPSINFO CONFIG DS {}", srcDpn.getDPNID());
158                             writeTransaction.delete(LogicalDatastoreType.CONFIGURATION, dpnPath);
159                             InstanceIdentifier<DpnEndpoints> tnlContainerPath =
160                                     InstanceIdentifier.builder(DpnEndpoints.class).build();
161                             Optional<DpnEndpoints> containerOptional =
162                                     ItmUtils.read(LogicalDatastoreType.CONFIGURATION,
163                                             tnlContainerPath, dataBroker);
164                             // remove container if no DPNs are present
165                             if (containerOptional.isPresent()) {
166                                 DpnEndpoints deps = containerOptional.get();
167                                 if (deps.getDPNTEPsInfo() == null || deps.getDPNTEPsInfo().isEmpty()) {
168                                     LOG.trace("Container Removal from DPNTEPSINFO CONFIG DS");
169                                     writeTransaction.delete(LogicalDatastoreType.CONFIGURATION, tnlContainerPath);
170                                 }
171                             }
172                         }
173                     }
174                 }
175             }
176             futures.add(writeTransaction.submit());
177         } catch (Exception e1) {
178             LOG.error("exception while deleting tep", e1);
179         }
180         return futures ;
181     }
182
183     private static void removeTrunkInterface(DataBroker dataBroker, IdManagerService idManagerService,
184                                              TunnelEndPoints srcTep, TunnelEndPoints dstTep, BigInteger srcDpnId,
185                                              BigInteger dstDpnId, WriteTransaction transaction,
186                                              List<ListenableFuture<Void>> futures) {
187         String trunkfwdIfName = ItmUtils.getTrunkInterfaceName(idManagerService, srcTep.getInterfaceName(),
188                 new String(srcTep.getIpAddress().getValue()),
189                 new String(dstTep.getIpAddress().getValue()),
190                 srcTep.getTunnelType().getName());
191         LOG.trace("Removing forward Trunk Interface " + trunkfwdIfName);
192         InstanceIdentifier<Interface> trunkIdentifier = ItmUtils.buildId(trunkfwdIfName);
193         LOG.debug(" Removing Trunk Interface Name - {} , Id - {} from Config DS ",
194                 trunkfwdIfName, trunkIdentifier) ;
195         transaction.delete(LogicalDatastoreType.CONFIGURATION, trunkIdentifier);
196         ItmUtils.itmCache.removeInterface(trunkfwdIfName);
197         // also update itm-state ds -- Delete the forward tunnel-interface from the tunnel list
198         InstanceIdentifier<InternalTunnel> path = InstanceIdentifier.create(TunnelList.class)
199                 .child(InternalTunnel.class, new InternalTunnelKey(dstDpnId, srcDpnId, srcTep.getTunnelType()));
200         transaction.delete(LogicalDatastoreType.CONFIGURATION,path) ;
201         ItmUtils.itmCache.removeInternalTunnel(trunkfwdIfName);
202         // Release the Ids for the forward trunk interface Name
203         ItmUtils.releaseIdForTrunkInterfaceName(idManagerService,srcTep.getInterfaceName(),
204                 new String(srcTep.getIpAddress().getValue()),
205                 new String(dstTep.getIpAddress().getValue()),
206                 srcTep.getTunnelType().getName());
207         removeLogicalGroupTunnel(srcDpnId, dstDpnId, dataBroker);
208
209         String trunkRevIfName = ItmUtils.getTrunkInterfaceName(idManagerService, dstTep.getInterfaceName(),
210                 new String(dstTep.getIpAddress().getValue()),
211                 new String(srcTep.getIpAddress().getValue()),
212                 srcTep.getTunnelType().getName());
213         LOG.trace("Removing Reverse Trunk Interface {}", trunkRevIfName);
214         trunkIdentifier = ItmUtils.buildId(trunkRevIfName);
215         LOG.debug(" Removing Trunk Interface Name - {} , Id - {} from Config DS ",
216                 trunkRevIfName, trunkIdentifier) ;
217         transaction.delete(LogicalDatastoreType.CONFIGURATION, trunkIdentifier);
218         ItmUtils.itmCache.removeInternalTunnel(trunkRevIfName);
219         // also update itm-state ds -- Delete the reverse tunnel-interface from the tunnel list
220         path = InstanceIdentifier.create(TunnelList.class)
221                 .child(InternalTunnel.class, new InternalTunnelKey(srcDpnId, dstDpnId, dstTep.getTunnelType()));
222         transaction.delete(LogicalDatastoreType.CONFIGURATION,path) ;
223
224         // Release the Ids for the reverse trunk interface Name
225         ItmUtils.releaseIdForTrunkInterfaceName(idManagerService, dstTep.getInterfaceName(),
226                 new String(dstTep.getIpAddress().getValue()),
227                 new String(srcTep.getIpAddress().getValue()),
228                 dstTep.getTunnelType().getName());
229         removeLogicalGroupTunnel(dstDpnId, srcDpnId, dataBroker);
230     }
231
232     private static boolean checkIfTrunkExists(BigInteger srcDpnId, BigInteger dstDpnId,
233                                               Class<? extends TunnelTypeBase> tunType, DataBroker dataBroker) {
234         InstanceIdentifier<InternalTunnel> path = InstanceIdentifier.create(TunnelList.class)
235                 .child(InternalTunnel.class, new InternalTunnelKey(dstDpnId, srcDpnId, tunType));
236         return ItmUtils.read(LogicalDatastoreType.CONFIGURATION,path, dataBroker).isPresent();
237     }
238
239     private static void removeLogicalGroupTunnel(BigInteger srcDpnId, BigInteger dstDpnId,
240                                                  DataBroker dataBroker) {
241         boolean tunnelAggregationEnabled = ItmTunnelAggregationHelper.isTunnelAggregationEnabled();
242         if (!tunnelAggregationEnabled) {
243             return;
244         }
245         String logicTunnelName = ItmUtils.getLogicalTunnelGroupName(srcDpnId, dstDpnId);
246         DataStoreJobCoordinator coordinator = DataStoreJobCoordinator.getInstance();
247         ItmTunnelAggregationDeleteWorker addWorker =
248                 new ItmTunnelAggregationDeleteWorker(logicTunnelName, srcDpnId, dstDpnId, dataBroker);
249         coordinator.enqueueJob(logicTunnelName, addWorker);
250     }
251
252     private static class ItmTunnelAggregationDeleteWorker implements Callable<List<ListenableFuture<Void>>> {
253
254         private final String logicTunnelName;
255         private final BigInteger srcDpnId;
256         private final BigInteger dstDpnId;
257         private final DataBroker dataBroker;
258
259         ItmTunnelAggregationDeleteWorker(String groupName, BigInteger srcDpnId, BigInteger dstDpnId, DataBroker db) {
260             this.logicTunnelName = groupName;
261             this.srcDpnId = srcDpnId;
262             this.dstDpnId = dstDpnId;
263             this.dataBroker = db;
264         }
265
266         @Override
267         public List<ListenableFuture<Void>> call() throws Exception {
268             Collection<InternalTunnel> tunnels = ItmUtils.itmCache.getAllInternalTunnel();
269             if (tunnels == null) {
270                 return Collections.emptyList();
271             }
272             //The logical tunnel interface be removed only when the last tunnel interface on each OVS is deleted
273             boolean emptyTunnelGroup = true;
274             boolean foundLogicGroupIface = false;
275             for (InternalTunnel tunl : tunnels) {
276                 if (tunl.getSourceDPN().equals(srcDpnId) && tunl.getDestinationDPN().equals(dstDpnId)) {
277                     if (tunl.getTransportType().isAssignableFrom(TunnelTypeVxlan.class)
278                             && tunl.getTunnelInterfaceNames() != null && !tunl.getTunnelInterfaceNames().isEmpty()) {
279                         emptyTunnelGroup = false;
280                         break;
281                     } else if (tunl.getTransportType().isAssignableFrom(TunnelTypeLogicalGroup.class)) {
282                         foundLogicGroupIface = true;
283                     }
284                 }
285             }
286             if (emptyTunnelGroup && foundLogicGroupIface) {
287                 WriteTransaction tx = dataBroker.newWriteOnlyTransaction();
288                 LOG.debug("MULTIPLE_VxLAN_TUNNELS: remove the logical tunnel group {} because a last tunnel"
289                     + " interface on srcDpnId {} dstDpnId {} is removed", logicTunnelName, srcDpnId, dstDpnId);
290                 InstanceIdentifier<Interface> trunkIdentifier = ItmUtils.buildId(logicTunnelName);
291                 tx.delete(LogicalDatastoreType.CONFIGURATION, trunkIdentifier);
292                 ItmUtils.itmCache.removeInterface(logicTunnelName);
293                 InstanceIdentifier<InternalTunnel> path = InstanceIdentifier.create(TunnelList.class)
294                         .child(InternalTunnel.class,
295                                 new InternalTunnelKey(dstDpnId, srcDpnId, TunnelTypeLogicalGroup.class));
296                 tx.delete(LogicalDatastoreType.CONFIGURATION, path);
297                 ItmUtils.itmCache.removeInternalTunnel(logicTunnelName);
298                 return Collections.singletonList(tx.submit());
299             } else if (!emptyTunnelGroup) {
300                 LOG.debug("MULTIPLE_VxLAN_TUNNELS: not last tunnel in logical tunnel group {}", logicTunnelName);
301             }
302             return Collections.emptyList();
303         }
304     }
305 }