2 * Copyright (c) 2017 Red Hat, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
9 package org.opendaylight.netvirt.natservice.ha;
11 import static org.opendaylight.genius.infra.Datastore.CONFIGURATION;
12 import static org.opendaylight.genius.infra.Datastore.OPERATIONAL;
14 import com.google.common.base.Optional;
15 import java.math.BigInteger;
16 import java.util.ArrayList;
17 import java.util.HashMap;
18 import java.util.Iterator;
19 import java.util.List;
21 import java.util.Map.Entry;
22 import java.util.concurrent.ConcurrentHashMap;
23 import java.util.concurrent.ExecutionException;
24 import javax.annotation.Nullable;
25 import javax.inject.Inject;
26 import javax.inject.Singleton;
27 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
28 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
29 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
30 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
31 import org.opendaylight.genius.datastoreutils.SingleTransactionDataBroker;
32 import org.opendaylight.genius.infra.ManagedNewTransactionRunner;
33 import org.opendaylight.genius.infra.ManagedNewTransactionRunnerImpl;
34 import org.opendaylight.infrautils.utils.concurrent.ListenableFutures;
35 import org.opendaylight.netvirt.natservice.api.CentralizedSwitchScheduler;
36 import org.opendaylight.netvirt.natservice.api.NatSwitchCache;
37 import org.opendaylight.netvirt.natservice.api.NatSwitchCacheListener;
38 import org.opendaylight.netvirt.natservice.api.SwitchInfo;
39 import org.opendaylight.netvirt.natservice.internal.NatUtil;
40 import org.opendaylight.netvirt.vpnmanager.api.IVpnFootprintService;
41 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.OdlInterfaceRpcService;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.config.rev170206.NatserviceConfig;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.ExtRouters;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.NaptSwitches;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.ext.routers.Routers;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.ext.routers.routers.ExternalIps;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.napt.switches.RouterToNaptSwitch;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.napt.switches.RouterToNaptSwitchBuilder;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.napt.switches.RouterToNaptSwitchKey;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.NetworkAttributes;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.Subnetmaps;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.subnetmaps.Subnetmap;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.subnetmaps.SubnetmapKey;
55 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
60 public class WeightedCentralizedSwitchScheduler implements CentralizedSwitchScheduler, NatSwitchCacheListener {
61 private static final Logger LOG = LoggerFactory.getLogger(WeightedCentralizedSwitchScheduler.class);
62 private static final Integer INITIAL_SWITCH_WEIGHT = Integer.valueOf(0);
64 private final Map<String, Map<BigInteger,Integer>> providerSwitchWeightsMap = new ConcurrentHashMap<>();
65 private final Map<String,String> subnetIdToRouterPortMap = new ConcurrentHashMap<>();
66 private final Map<String,String> subnetIdToElanInstanceMap = new ConcurrentHashMap<>();
67 private final DataBroker dataBroker;
68 private final ManagedNewTransactionRunner txRunner;
69 private final OdlInterfaceRpcService interfaceManager;
70 private final IVpnFootprintService vpnFootprintService;
71 private final NatserviceConfig.NatMode natMode;
74 public WeightedCentralizedSwitchScheduler(final DataBroker dataBroker,
75 final OdlInterfaceRpcService interfaceManager,
76 final IVpnFootprintService vpnFootprintService, final NatserviceConfig config,
77 final NatSwitchCache natSwitchCache) {
78 this.dataBroker = dataBroker;
79 this.txRunner = new ManagedNewTransactionRunnerImpl(dataBroker);
80 this.interfaceManager = interfaceManager;
81 this.vpnFootprintService = vpnFootprintService;
83 this.natMode = config.getNatMode();
85 this.natMode = NatserviceConfig.NatMode.Controller;
87 natSwitchCache.register(this);
91 public boolean scheduleCentralizedSwitch(Routers router) {
92 String providerNet = NatUtil.getElanInstancePhysicalNetwok(router.getNetworkId().getValue(),dataBroker);
93 BigInteger nextSwitchId = getSwitchWithLowestWeight(providerNet);
94 if (BigInteger.ZERO.equals(nextSwitchId)) {
95 LOG.error("In scheduleCentralizedSwitch, unable to schedule the router {} as there is no available switch.",
96 router.getRouterName());
100 LOG.info("scheduleCentralizedSwitch for router {} on switch {}", router.getRouterName(), nextSwitchId);
101 String routerName = router.getRouterName();
102 RouterToNaptSwitchBuilder routerToNaptSwitchBuilder =
103 new RouterToNaptSwitchBuilder().setRouterName(routerName);
104 RouterToNaptSwitch id = routerToNaptSwitchBuilder.setPrimarySwitchId(nextSwitchId)
105 .setEnableSnat(router.isEnableSnat()).build();
106 addToDpnMaps(routerName, router.getSubnetIds(), nextSwitchId);
108 SingleTransactionDataBroker.syncWrite(dataBroker, LogicalDatastoreType.CONFIGURATION,
109 getNaptSwitchesIdentifier(routerName), id);
110 Map<BigInteger,Integer> switchWeightMap = providerSwitchWeightsMap.get(providerNet);
111 switchWeightMap.put(nextSwitchId,switchWeightMap.get(nextSwitchId) + 1);
113 } catch (TransactionCommitFailedException e) {
114 LOG.error("ScheduleCentralizedSwitch failed for {}", routerName);
121 public boolean updateCentralizedSwitch(Routers oldRouter, Routers newRouter) {
122 LOG.info("updateCentralizedSwitch for router {}", newRouter.getRouterName());
123 String routerName = newRouter.getRouterName();
124 List<Uuid> addedSubnetIds = getUpdatedSubnetIds(newRouter.getSubnetIds(), oldRouter.getSubnetIds());
125 List<Uuid> deletedSubnetIds = getUpdatedSubnetIds(oldRouter.getSubnetIds(), newRouter.getSubnetIds());
126 BigInteger primarySwitchId = NatUtil.getPrimaryNaptfromRouterName(dataBroker, newRouter.getRouterName());
127 addToDpnMaps(routerName, addedSubnetIds, primarySwitchId);
128 deleteFromDpnMaps(routerName, deletedSubnetIds, primarySwitchId);
130 InstanceIdentifier<RouterToNaptSwitch> id = NatUtil.buildNaptSwitchIdentifier(routerName);
131 RouterToNaptSwitch routerToNaptSwitch = SingleTransactionDataBroker.syncRead(dataBroker,
132 LogicalDatastoreType.CONFIGURATION, id);
133 boolean isSnatEnabled = newRouter.isEnableSnat();
134 List<ExternalIps> updateExternalIps = newRouter.getExternalIps();
135 if (updateExternalIps == null || updateExternalIps.isEmpty()) {
136 isSnatEnabled = false;
138 if (isSnatEnabled != routerToNaptSwitch.isEnableSnat()) {
139 RouterToNaptSwitchBuilder routerToNaptSwitchBuilder =
140 new RouterToNaptSwitchBuilder(routerToNaptSwitch);
141 routerToNaptSwitchBuilder.setEnableSnat(isSnatEnabled);
142 SingleTransactionDataBroker.syncWrite(dataBroker, LogicalDatastoreType.CONFIGURATION,
143 getNaptSwitchesIdentifier(routerName), routerToNaptSwitchBuilder.build());
145 } catch (ReadFailedException e) {
146 LOG.error("updateCentralizedSwitch ReadFailedException for {}", routerName);
147 } catch (TransactionCommitFailedException e) {
148 LOG.error("updateCentralizedSwitch TransactionCommitFailedException for {}", routerName);
154 public boolean releaseCentralizedSwitch(Routers router) {
155 String providerNet = NatUtil.getElanInstancePhysicalNetwok(router.getNetworkId().getValue(),dataBroker);
156 String routerName = router.getRouterName();
157 BigInteger primarySwitchId = NatUtil.getPrimaryNaptfromRouterName(dataBroker, routerName);
158 if (primarySwitchId == null || BigInteger.ZERO.equals(primarySwitchId)) {
159 LOG.info("releaseCentralizedSwitch: NAPT Switch is not allocated for router {}", router.getRouterName());
163 LOG.info("releaseCentralizedSwitch for router {} from switch {}", router.getRouterName(), primarySwitchId);
164 deleteFromDpnMaps(routerName, router.getSubnetIds(), primarySwitchId);
166 SingleTransactionDataBroker.syncDelete(dataBroker, LogicalDatastoreType.CONFIGURATION,
167 getNaptSwitchesIdentifier(routerName));
168 Map<BigInteger,Integer> switchWeightMap = providerSwitchWeightsMap.get(providerNet);
169 switchWeightMap.put(primarySwitchId, switchWeightMap.get(primarySwitchId) - 1);
170 } catch (TransactionCommitFailedException e) {
176 private void addToDpnMaps(String routerName, List<Uuid> addedSubnetIds, BigInteger primarySwitchId) {
177 if (addedSubnetIds == null || addedSubnetIds.isEmpty()) {
178 LOG.debug("addToDpnMaps no subnets associated with {}", routerName);
181 Map<Uuid, Subnetmap> subnetMapEntries = new HashMap<>();
183 String primaryRd = txRunner.applyWithNewReadWriteTransactionAndSubmit(CONFIGURATION, tx -> {
184 for (Uuid subnetUuid : addedSubnetIds) {
185 Subnetmap subnetMapEntry = tx.read(getSubnetMapIdentifier(subnetUuid)).get().orNull();
186 subnetMapEntries.put(subnetUuid, subnetMapEntry);
187 Uuid routerPortUuid = subnetMapEntry.getRouterInterfacePortId();
188 subnetIdToRouterPortMap.put(subnetUuid.getValue(), routerPortUuid.getValue());
190 return NatUtil.getPrimaryRd(routerName, tx);
192 ListenableFutures.addErrorLogging(txRunner.callWithNewReadWriteTransactionAndSubmit(OPERATIONAL, tx -> {
193 for (Uuid subnetUuid : addedSubnetIds) {
194 Subnetmap subnetMapEntry = subnetMapEntries.get(subnetUuid);
195 Uuid routerPortUuid = subnetMapEntry.getRouterInterfacePortId();
196 vpnFootprintService.updateVpnToDpnMapping(primarySwitchId, routerName, primaryRd,
197 routerPortUuid.getValue(), null, true);
198 NatUtil.addToNeutronRouterDpnsMap(routerName, routerPortUuid.getValue(), primarySwitchId, tx);
199 NatUtil.addToDpnRoutersMap(routerName, routerPortUuid.getValue(), primarySwitchId, tx);
200 if (subnetMapEntry.getNetworkType().equals(NetworkAttributes.NetworkType.VLAN)) {
201 String elanInstanceName = subnetMapEntry.getNetworkId().getValue();
202 subnetIdToElanInstanceMap.put(subnetUuid.getValue(), elanInstanceName);
203 NatUtil.addPseudoPortToElanDpn(elanInstanceName, elanInstanceName, primarySwitchId, dataBroker);
206 }), LOG, "Error adding subnets to DPN maps for {}", routerName);
207 } catch (InterruptedException | ExecutionException e) {
208 LOG.error("Error adding subnets to DPN maps for {}", routerName);
212 private void deleteFromDpnMaps(String routerName, List<Uuid> deletedSubnetIds, BigInteger primarySwitchId) {
213 if (deletedSubnetIds == null || deletedSubnetIds.isEmpty()) {
214 LOG.debug("deleteFromDpnMaps no subnets associated with {}", routerName);
218 String primaryRd = txRunner.applyWithNewReadWriteTransactionAndSubmit(CONFIGURATION,
219 tx -> NatUtil.getPrimaryRd(routerName, tx)).get();
220 ListenableFutures.addErrorLogging(txRunner.callWithNewReadWriteTransactionAndSubmit(OPERATIONAL, tx -> {
221 for (Uuid subnetUuid : deletedSubnetIds) {
222 String routerPort = subnetIdToRouterPortMap.remove(subnetUuid.getValue());
223 if (routerPort == null) {
224 LOG.error("The router port was not found for {}", subnetUuid.getValue());
227 vpnFootprintService.updateVpnToDpnMapping(primarySwitchId, routerName, primaryRd,
228 routerPort, null, false);
229 NatUtil.removeFromNeutronRouterDpnsMap(routerName, primarySwitchId, tx);
230 NatUtil.removeFromDpnRoutersMap(dataBroker, routerName, routerName,
231 primarySwitchId, interfaceManager, tx);
232 if (subnetIdToElanInstanceMap.containsKey(subnetUuid.getValue())) {
233 String elanInstanceName = subnetIdToElanInstanceMap.remove(subnetUuid.getValue());
234 NatUtil.removePseudoPortFromElanDpn(elanInstanceName, elanInstanceName, primarySwitchId,
238 }), LOG, "Error deleting subnets from DPN maps for {}", routerName);
239 } catch (InterruptedException | ExecutionException e) {
240 LOG.error("Error deleting subnets from DPN maps for {}", routerName, e);
245 public void switchAddedToCache(SwitchInfo switchInfo) {
246 boolean scheduleRouters = (providerSwitchWeightsMap.size() == 0) ? true : false;
247 for (String providerNet : switchInfo.getProviderNets()) {
248 Map<BigInteger,Integer> switchWeightMap = providerSwitchWeightsMap.get(providerNet);
249 if (providerSwitchWeightsMap.get(providerNet) == null) {
250 switchWeightMap = new ConcurrentHashMap<>();
251 providerSwitchWeightsMap.put(providerNet, switchWeightMap);
253 LOG.info("addSwitch: Adding {} dpnId with provider mapping {} to switchWeightsMap",
254 switchInfo.getDpnId(), providerNet);
255 switchWeightMap.put(switchInfo.getDpnId(), INITIAL_SWITCH_WEIGHT);
257 if (natMode == NatserviceConfig.NatMode.Conntrack && scheduleRouters) {
258 Optional<ExtRouters> optRouters;
260 optRouters = SingleTransactionDataBroker.syncReadOptional(dataBroker,
261 LogicalDatastoreType.CONFIGURATION, InstanceIdentifier.create(ExtRouters.class));
262 } catch (ReadFailedException e) {
263 LOG.error("addSwitch: Error reading external routers", e);
267 if (optRouters.isPresent()) {
268 // Get the list of routers and verify if any routers do not have primarySwitch allocated.
269 for (Routers router : optRouters.get().getRouters()) {
270 List<ExternalIps> externalIps = router.getExternalIps();
271 if (router.isEnableSnat() && externalIps != null && !externalIps.isEmpty()) {
272 // Check if the primarySwitch is allocated for the router.
273 if (!isPrimarySwitchAllocatedForRouter(router.getRouterName())) {
274 scheduleCentralizedSwitch(router);
283 private boolean isPrimarySwitchAllocatedForRouter(String routerName) {
284 InstanceIdentifier<RouterToNaptSwitch> routerToNaptSwitch =
285 NatUtil.buildNaptSwitchRouterIdentifier(routerName);
287 RouterToNaptSwitch rtrToNapt = SingleTransactionDataBroker.syncRead(dataBroker,
288 LogicalDatastoreType.CONFIGURATION, routerToNaptSwitch);
289 BigInteger dpnId = rtrToNapt.getPrimarySwitchId();
290 if (dpnId == null || dpnId.equals(BigInteger.ZERO)) {
293 } catch (ReadFailedException e) {
294 LOG.error("isPrimarySwitchAllocatedForRouter: Error reading RouterToNaptSwitch model", e);
301 public void switchRemovedFromCache(SwitchInfo switchInfo) {
302 BigInteger dpnId = switchInfo.getDpnId();
303 LOG.info("removeSwitch: Removing {} dpnId to switchWeightsMap", dpnId);
304 for (Map.Entry<String,Map<BigInteger,Integer>> providerNet : providerSwitchWeightsMap.entrySet()) {
305 Map<BigInteger,Integer> switchWeightMap = providerNet.getValue();
306 if (natMode == NatserviceConfig.NatMode.Conntrack
307 && !INITIAL_SWITCH_WEIGHT.equals(switchWeightMap.get(dpnId))) {
308 NaptSwitches naptSwitches = getNaptSwitches();
309 for (RouterToNaptSwitch routerToNaptSwitch : naptSwitches.getRouterToNaptSwitch()) {
310 if (dpnId.equals(routerToNaptSwitch.getPrimarySwitchId())) {
311 Routers router = NatUtil.getRoutersFromConfigDS(dataBroker, routerToNaptSwitch.getRouterName());
312 releaseCentralizedSwitch(router);
313 scheduleCentralizedSwitch(router);
318 switchWeightMap.remove(dpnId);
323 private NaptSwitches getNaptSwitches() {
324 InstanceIdentifier<NaptSwitches> id = InstanceIdentifier.builder(NaptSwitches.class).build();
325 return SingleTransactionDataBroker.syncReadOptionalAndTreatReadFailedExceptionAsAbsentOptional(dataBroker,
326 LogicalDatastoreType.CONFIGURATION, id).orNull();
329 private BigInteger getSwitchWithLowestWeight(String providerNet) {
330 int lowestWeight = Integer.MAX_VALUE;
331 BigInteger nextSwitchId = BigInteger.valueOf(0);
332 Map<BigInteger,Integer> switchWeightMap = providerSwitchWeightsMap.get(providerNet);
333 if (null == switchWeightMap) {
334 LOG.error("No switch have the provider mapping {}", providerNet);
337 for (Entry<BigInteger, Integer> entry : switchWeightMap.entrySet()) {
338 BigInteger dpnId = entry.getKey();
339 Integer weight = entry.getValue();
340 if (lowestWeight > weight) {
341 lowestWeight = weight;
342 nextSwitchId = dpnId;
345 LOG.info("getSwitchWithLowestWeight: switchWeightsMap {}, returning nextSwitchId {} ",
346 providerSwitchWeightsMap, nextSwitchId);
350 private InstanceIdentifier<RouterToNaptSwitch> getNaptSwitchesIdentifier(String routerName) {
351 return InstanceIdentifier.builder(NaptSwitches.class)
352 .child(RouterToNaptSwitch.class, new RouterToNaptSwitchKey(routerName)).build();
355 private InstanceIdentifier<Subnetmap> getSubnetMapIdentifier(Uuid subnetId) {
356 return InstanceIdentifier.builder(Subnetmaps.class).child(Subnetmap.class,
357 new SubnetmapKey(subnetId)).build();
361 public BigInteger getCentralizedSwitch(String routerName) {
363 Optional<RouterToNaptSwitch> naptSwitches = SingleTransactionDataBroker
364 .syncReadOptional(dataBroker, LogicalDatastoreType.CONFIGURATION,
365 getNaptSwitchesIdentifier(routerName));
366 if (!naptSwitches.isPresent()) {
367 LOG.info("No Napt switch is scheduled for {}", routerName);
370 return naptSwitches.get().getPrimarySwitchId();
371 } catch (ReadFailedException e) {
372 LOG.error("Error reading RouterToNaptSwitch model", e);
378 private static List<Uuid> getUpdatedSubnetIds(List<Uuid> updatedSubnetIds, List<Uuid> currentSubnetIds) {
379 if (updatedSubnetIds == null) {
382 List<Uuid> newSubnetIds = new ArrayList<>(updatedSubnetIds);
383 if (currentSubnetIds == null) {
386 List<Uuid> origSubnetIds = new ArrayList<>(currentSubnetIds);
387 for (Iterator<Uuid> iterator = newSubnetIds.iterator(); iterator.hasNext();) {
388 Uuid updatedSubnetId = iterator.next();
389 for (Uuid currentSubnetId : origSubnetIds) {
390 if (updatedSubnetId.getValue().equals(currentSubnetId.getValue())) {