NETVIRT-1630 migrate to md-sal APIs
[netvirt.git] / natservice / impl / src / main / java / org / opendaylight / netvirt / natservice / internal / NAPTSwitchSelector.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.netvirt.natservice.internal;
9
10 import java.util.HashMap;
11 import java.util.List;
12 import java.util.Map;
13 import java.util.Optional;
14 import java.util.Set;
15 import java.util.TreeSet;
16 import java.util.concurrent.ExecutionException;
17 import javax.inject.Inject;
18 import javax.inject.Singleton;
19 import org.eclipse.jdt.annotation.NonNull;
20 import org.opendaylight.genius.cloudscaler.api.TombstonedNodeManager;
21 import org.opendaylight.genius.datastoreutils.SingleTransactionDataBroker;
22 import org.opendaylight.genius.mdsalutil.MDSALUtil;
23 import org.opendaylight.mdsal.binding.api.DataBroker;
24 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
25 import org.opendaylight.mdsal.common.api.ReadFailedException;
26 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.NaptSwitches;
27 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.napt.switches.RouterToNaptSwitch;
28 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.napt.switches.RouterToNaptSwitchBuilder;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.napt.switches.RouterToNaptSwitchKey;
30 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
31 import org.opendaylight.yangtools.yang.common.Uint32;
32 import org.opendaylight.yangtools.yang.common.Uint64;
33 import org.slf4j.Logger;
34 import org.slf4j.LoggerFactory;
35
36 @Singleton
37 public class NAPTSwitchSelector {
38     private static final Logger LOG = LoggerFactory.getLogger(NAPTSwitchSelector.class);
39     private final DataBroker dataBroker;
40     private final TombstonedNodeManager tombstonedNodeManager;
41
42     @Inject
43     public NAPTSwitchSelector(final DataBroker dataBroker, final TombstonedNodeManager tombstonedNodeManager) {
44         this.dataBroker = dataBroker;
45         this.tombstonedNodeManager = tombstonedNodeManager;
46     }
47
48     Uint64 selectNewNAPTSwitch(String routerName, List<Uint64> excludeDpns) {
49         LOG.info("selectNewNAPTSwitch : Select a new NAPT switch for router {}", routerName);
50         Map<Uint64, Integer> naptSwitchWeights = constructNAPTSwitches();
51         List<Uint64> routerSwitches = getDpnsForVpn(routerName);
52         if (routerSwitches.isEmpty()) {
53             LOG.warn("selectNewNAPTSwitch : Delaying NAPT switch selection due to no dpns scenario for router {}",
54                     routerName);
55             return Uint64.ZERO;
56         }
57         try {
58             if (excludeDpns != null) {
59                 routerSwitches.removeAll(excludeDpns);
60             }
61             LOG.debug("selectNewNAPTSwitch : routerSwitches before filtering : {}", routerSwitches);
62             routerSwitches = tombstonedNodeManager.filterTombStoned(routerSwitches);
63             LOG.debug("selectNewNAPTSwitch : routerSwitches after filtering : {}", routerSwitches);
64         } catch (ReadFailedException ex) {
65             LOG.error("selectNewNAPTSwitch : filterTombStoned Exception thrown", ex);
66         }
67         Set<SwitchWeight> switchWeights = new TreeSet<>();
68         for (Uint64 dpn : routerSwitches) {
69             if (naptSwitchWeights.get(dpn) != null) {
70                 switchWeights.add(new SwitchWeight(dpn, naptSwitchWeights.get(dpn)));
71             } else {
72                 switchWeights.add(new SwitchWeight(dpn, 0));
73             }
74         }
75
76         Uint64 primarySwitch;
77
78         if (!switchWeights.isEmpty()) {
79
80             LOG.debug("selectNewNAPTSwitch : Current switch weights for router {} - {}", routerName, switchWeights);
81
82             RouterToNaptSwitchBuilder routerToNaptSwitchBuilder =
83                 new RouterToNaptSwitchBuilder().setRouterName(routerName);
84             SwitchWeight firstSwitchWeight = switchWeights.iterator().next();
85             primarySwitch = firstSwitchWeight.getSwitch();
86             RouterToNaptSwitch id = routerToNaptSwitchBuilder.setPrimarySwitchId(primarySwitch).build();
87
88             MDSALUtil.syncWrite(dataBroker, LogicalDatastoreType.CONFIGURATION,
89                 getNaptSwitchesIdentifier(routerName), id);
90
91             LOG.debug("selectNewNAPTSwitch : successful addition of RouterToNaptSwitch to napt-switches container");
92             return primarySwitch;
93         } else {
94             primarySwitch = Uint64.ZERO;
95
96             LOG.debug("selectNewNAPTSwitch : switchWeights empty, primarySwitch: {} ", primarySwitch);
97             return primarySwitch;
98         }
99     }
100
101     private Map<Uint64, Integer> constructNAPTSwitches() {
102         Optional<NaptSwitches> optNaptSwitches = Optional.empty();
103         try {
104             optNaptSwitches = SingleTransactionDataBroker.syncReadOptional(dataBroker,
105                     LogicalDatastoreType.CONFIGURATION, getNaptSwitchesIdentifier());
106         } catch (ExecutionException | InterruptedException e) {
107             LOG.error("constructNAPTSwitches: Exception while reading the NaptSwitches DS", e);
108         }
109         Map<Uint64, Integer> switchWeights = new HashMap<>();
110
111         if (optNaptSwitches.isPresent()) {
112             NaptSwitches naptSwitches = optNaptSwitches.get();
113
114             for (RouterToNaptSwitch naptSwitch : naptSwitches.nonnullRouterToNaptSwitch()) {
115                 Uint64 primarySwitch = naptSwitch.getPrimarySwitchId();
116                 //update weight
117                 Integer weight = switchWeights.get(primarySwitch);
118                 if (weight == null) {
119                     switchWeights.put(primarySwitch, 1);
120                 } else {
121                     switchWeights.put(primarySwitch, ++weight);
122                 }
123             }
124         }
125         return switchWeights;
126     }
127
128     private InstanceIdentifier<NaptSwitches> getNaptSwitchesIdentifier() {
129         return InstanceIdentifier.create(NaptSwitches.class);
130     }
131
132     private InstanceIdentifier<RouterToNaptSwitch> getNaptSwitchesIdentifier(String routerName) {
133         return InstanceIdentifier.builder(NaptSwitches.class)
134             .child(RouterToNaptSwitch.class, new RouterToNaptSwitchKey(routerName)).build();
135     }
136
137     @NonNull
138     public List<Uint64> getDpnsForVpn(String routerName) {
139         LOG.debug("getDpnsForVpn: called for RouterName {}", routerName);
140         Uint32 bgpVpnId = NatUtil.getBgpVpnId(dataBroker, routerName);
141         // TODO Why?
142         if (bgpVpnId != NatConstants.INVALID_ID) {
143             return NatUtil.getDpnsForRouter(dataBroker, routerName);
144         }
145         return NatUtil.getDpnsForRouter(dataBroker, routerName);
146     }
147
148     private static class SwitchWeight implements Comparable<SwitchWeight> {
149         private final Uint64 swich;
150         private int weight;
151
152         SwitchWeight(Uint64 swich, int weight) {
153             this.swich = swich;
154             this.weight = weight;
155         }
156
157         @Override
158         public int hashCode() {
159             final int prime = 31;
160             int result = 1;
161             result = prime * result + (swich == null ? 0 : swich.hashCode());
162             return result;
163         }
164
165         @Override
166         public boolean equals(Object obj) {
167             if (this == obj) {
168                 return true;
169             }
170             if (obj == null) {
171                 return false;
172             }
173             if (getClass() != obj.getClass()) {
174                 return false;
175             }
176             SwitchWeight other = (SwitchWeight) obj;
177             if (swich == null) {
178                 if (other.swich != null) {
179                     return false;
180                 }
181             } else if (!swich.equals(other.swich)) {
182                 return false;
183             }
184             return true;
185         }
186
187         public Uint64 getSwitch() {
188             return swich;
189         }
190
191         public int getWeight() {
192             return weight;
193         }
194
195         @Override
196         public int compareTo(@NonNull SwitchWeight switchWeight) {
197             return weight - switchWeight.getWeight();
198         }
199     }
200 }