Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ public final class UpstreamIdentity {

private final String leastActiveKey;

private final String markerKey;

UpstreamIdentity(final String protocol, final String url, final String group, final String version, final String domain) {
this.protocol = protocol;
this.url = url;
Expand All @@ -46,6 +48,7 @@ public final class UpstreamIdentity {
boolean hasVariant = Objects.nonNull(group) || Objects.nonNull(version);
this.hashKey = hasVariant ? GsonUtils.getInstance().toJson(new String[]{protocol, url, group, version}) : url;
this.leastActiveKey = hasVariant ? GsonUtils.getInstance().toJson(new String[]{domain, group, version}) : domain;
this.markerKey = GsonUtils.getInstance().toJson(new String[]{protocol, url, group, version});
}

/**
Expand All @@ -65,7 +68,7 @@ public String hashKey() {
* @return the full identity marker
*/
public String markerKey() {
return GsonUtils.getInstance().toJson(new String[]{protocol, url, group, version});
return markerKey;
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,20 @@

package org.apache.shenyu.loadbalancer.spi;

import org.apache.shenyu.common.cache.WindowTinyLFUMap;
import org.apache.shenyu.common.constant.Constants;
import org.apache.shenyu.common.utils.MapUtils;
import org.apache.shenyu.loadbalancer.entity.LoadBalanceData;
import org.apache.shenyu.loadbalancer.entity.Upstream;
import org.apache.shenyu.loadbalancer.entity.UpstreamIdentity;
import org.apache.shenyu.spi.Join;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;

/**
Expand All @@ -36,19 +39,27 @@
@Join
public class RoundRobinLoadBalancer extends AbstractLoadBalancer {

private final int recyclePeriod = 60000;

private final ConcurrentMap<String, ConcurrentMap<UpstreamIdentity, WeightedRoundRobin>> methodWeightMap = new ConcurrentHashMap<>(16);

private final AtomicBoolean updateLock = new AtomicBoolean();
/**
* State is keyed by the full ordered upstream identity set together with the
* configured weights (#8441): selectors whose upstream lists share an address
* never share smooth weighted round-robin counters, and the bounded cache
* evicts pools orphaned by reorders or weight changes.
*/
private final Map<List<String>, ConcurrentMap<UpstreamIdentity, WeightedRoundRobin>> methodWeightMap =
new WindowTinyLFUMap<>(Constants.CACHE_MAX_COUNT);

@Override
public Upstream doSelect(final List<Upstream> upstreamList, final LoadBalanceData data) {
String key = upstreamList.get(0).getUrl();
ConcurrentMap<UpstreamIdentity, WeightedRoundRobin> map = MapUtils.computeIfAbsent(methodWeightMap, key, k -> new ConcurrentHashMap<>(16));
List<String> stateKey = new ArrayList<>(upstreamList.size());
for (Upstream upstream : upstreamList) {
// the configured weight, not the warm-up adjusted one, so warm-up
// ramping does not rotate pools and reset the counters each call
stateKey.add(upstream.identity().markerKey() + ':' + upstream.getWeight());
}
ConcurrentMap<UpstreamIdentity, WeightedRoundRobin> map =
methodWeightMap.computeIfAbsent(List.copyOf(stateKey), k -> new ConcurrentHashMap<>(16));

Check warning on line 60 in shenyu-loadbalancer/src/main/java/org/apache/shenyu/loadbalancer/spi/RoundRobinLoadBalancer.java

View workflow job for this annotation

GitHub Actions / added-lines

New code quality Q1

[Q1] '16' is a magic number. Reuse an existing constant or declare a named constant with its unit.
long totalWeight = 0;
long maxCurrent = Long.MIN_VALUE;
long now = System.currentTimeMillis();
Upstream selectedInvoker = null;
WeightedRoundRobin selectedWeightedRoundRobin = null;
for (Upstream upstream : upstreamList) {
Expand All @@ -59,28 +70,17 @@
return roundRobin;
});
if (weight != weightedRoundRobin.getWeight()) {
// weight changed.
// weight changed (warm-up ramping or configuration update).
weightedRoundRobin.setWeight(weight);
}
long cur = weightedRoundRobin.increaseCurrent();
weightedRoundRobin.setLastUpdate(now);
if (cur > maxCurrent) {
maxCurrent = cur;
selectedInvoker = upstream;
selectedWeightedRoundRobin = weightedRoundRobin;
}
totalWeight += weight;
}
if (!updateLock.get() && upstreamList.size() != map.size() && updateLock.compareAndSet(false, true)) {
try {
// copy -> modify -> update reference.
ConcurrentMap<UpstreamIdentity, WeightedRoundRobin> newMap = new ConcurrentHashMap<>(map);
newMap.entrySet().removeIf(item -> now - item.getValue().getLastUpdate() > recyclePeriod);
methodWeightMap.put(key, newMap);
} finally {
updateLock.set(false);
}
}
if (Objects.nonNull(selectedInvoker)) {
selectedWeightedRoundRobin.sel(totalWeight);
return selectedInvoker;
Expand All @@ -98,8 +98,6 @@

private final AtomicLong current = new AtomicLong(0);

private long lastUpdate;

/**
* Gets weight.
*
Expand Down Expand Up @@ -136,23 +134,5 @@
void sel(final long total) {
current.addAndGet(-total);
}

/**
* Gets last update.
*
* @return the last update
*/
long getLastUpdate() {
return lastUpdate;
}

/**
* Sets last update.
*
* @param lastUpdate the last update
*/
void setLastUpdate(final long lastUpdate) {
this.lastUpdate = lastUpdate;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -169,4 +169,132 @@ public void roundRobinLoadBalanceTest() {
countMap.values().forEach(count ->
assertTrue(count >= 8 && count <= 12, "Distribution should be roughly equal for equal weights"));
}

/**
* Issue #8441: two selectors whose upstream lists share the first upstream's
* URL must not share smooth weighted round-robin counters. With isolated
* state each selector's sequence is deterministic, so the exact counts of a
* smooth cycle hold; on the shared state of the old implementation the
* shared upstream's weight flips 1↔9 between calls and the ratios deviate.
*/
@Test
public void sharedFirstUpstreamStaysIsolatedPerSelector() {
Upstream sharedLight = Upstream.builder().url("shared-a:8080").weight(1).status(true).build();
Upstream sharedHeavy = Upstream.builder().url("shared-a:8080").weight(9).status(true).build();
Upstream b = Upstream.builder().url("b:8080").weight(9).status(true).build();
Upstream c = Upstream.builder().url("c:8080").weight(1).status(true).build();
List<Upstream> selectorOne = List.of(sharedLight, b);
List<Upstream> selectorTwo = List.of(sharedHeavy, c);
RoundRobinLoadBalancer loadBalancer = new RoundRobinLoadBalancer();
Map<String, Integer> firstCounts = new HashMap<>();
Map<String, Integer> secondCounts = new HashMap<>();
IntStream.range(0, 10000).forEach(i -> {
firstCounts.merge(loadBalancer.select(selectorOne, new LoadBalanceData()).getUrl(), 1, Integer::sum);
secondCounts.merge(loadBalancer.select(selectorTwo, new LoadBalanceData()).getUrl(), 1, Integer::sum);
});
assertEquals(1000, firstCounts.get("shared-a:8080").intValue());
assertEquals(9000, firstCounts.get("b:8080").intValue());
assertEquals(9000, secondCounts.get("shared-a:8080").intValue());
assertEquals(1000, secondCounts.get("c:8080").intValue());
}

/**
* Issue #8441: parallel selectors sharing an upstream address keep their
* deterministic ratios, because each thread drives only its own pool.
*/
@Test
public void sharedUpstreamSelectorsStayIsolatedUnderConcurrency() throws Exception {
Upstream sharedLight = Upstream.builder().url("shared-a:8080").weight(1).status(true).build();
Upstream sharedHeavy = Upstream.builder().url("shared-a:8080").weight(9).status(true).build();
Upstream b = Upstream.builder().url("b:8080").weight(9).status(true).build();
Upstream c = Upstream.builder().url("c:8080").weight(1).status(true).build();
List<Upstream> selectorOne = List.of(sharedLight, b);
List<Upstream> selectorTwo = List.of(sharedHeavy, c);
RoundRobinLoadBalancer loadBalancer = new RoundRobinLoadBalancer();
Map<String, Integer> firstCounts = new HashMap<>();
Map<String, Integer> secondCounts = new HashMap<>();
Thread one = new Thread(() -> IntStream.range(0, 10000).forEach(i ->
firstCounts.merge(loadBalancer.select(selectorOne, new LoadBalanceData()).getUrl(), 1, Integer::sum)));
Thread two = new Thread(() -> IntStream.range(0, 10000).forEach(i ->
secondCounts.merge(loadBalancer.select(selectorTwo, new LoadBalanceData()).getUrl(), 1, Integer::sum)));
one.start();
two.start();
one.join();
two.join();
assertEquals(1000, firstCounts.get("shared-a:8080").intValue());
assertEquals(9000, firstCounts.get("b:8080").intValue());
assertEquals(9000, secondCounts.get("shared-a:8080").intValue());
assertEquals(1000, secondCounts.get("c:8080").intValue());
}

/**
* Issue #8441: two selectors over the same upstream set with opposite
* weights must each follow their own configuration, not fight over one
* pool (the old keying shared the state because the first URL matched).
*/
@Test
public void sameUpstreamSetWithDifferentWeightsStaysIsolated() {
Upstream lightA = Upstream.builder().url("set-a:8080").weight(1).status(true).build();
Upstream heavyB = Upstream.builder().url("set-b:8080").weight(9).status(true).build();
Upstream heavyA = Upstream.builder().url("set-a:8080").weight(9).status(true).build();
Upstream lightB = Upstream.builder().url("set-b:8080").weight(1).status(true).build();
List<Upstream> selectorOne = List.of(lightA, heavyB);
List<Upstream> selectorTwo = List.of(heavyA, lightB);
RoundRobinLoadBalancer loadBalancer = new RoundRobinLoadBalancer();
Map<String, Integer> firstCounts = new HashMap<>();
Map<String, Integer> secondCounts = new HashMap<>();
IntStream.range(0, 10000).forEach(i -> {
firstCounts.merge(loadBalancer.select(selectorOne, new LoadBalanceData()).getUrl(), 1, Integer::sum);
secondCounts.merge(loadBalancer.select(selectorTwo, new LoadBalanceData()).getUrl(), 1, Integer::sum);
});
assertEquals(1000, firstCounts.get("set-a:8080").intValue());
assertEquals(9000, firstCounts.get("set-b:8080").intValue());
assertEquals(9000, secondCounts.get("set-a:8080").intValue());
assertEquals(1000, secondCounts.get("set-b:8080").intValue());
}

/**
* A configured-weight change rotates the state to a fresh pool, so the new
* ratio applies from a clean counter instead of a polluted one.
*/
@Test
public void weightChangeRotatesToAFreshPool() {
Upstream a = Upstream.builder().url("wc-a:8080").weight(1).status(true).build();
Upstream heavyB = Upstream.builder().url("wc-b:8080").weight(9).status(true).build();
RoundRobinLoadBalancer loadBalancer = new RoundRobinLoadBalancer();
Map<String, Integer> counts = new HashMap<>();
List<Upstream> heavy = List.of(a, heavyB);
IntStream.range(0, 10000).forEach(i ->
counts.merge(loadBalancer.select(heavy, new LoadBalanceData()).getUrl(), 1, Integer::sum));
assertEquals(1000, counts.get("wc-a:8080").intValue());
assertEquals(9000, counts.get("wc-b:8080").intValue());
List<Upstream> lighter = List.of(a, Upstream.builder().url("wc-b:8080").weight(2).status(true).build());
IntStream.range(0, 10000).forEach(i ->
counts.merge(loadBalancer.select(lighter, new LoadBalanceData()).getUrl(), 1, Integer::sum));
final int aTotal = counts.get("wc-a:8080").intValue();
final int bTotal = counts.get("wc-b:8080").intValue();
// 1:2 over the second window of 10000 picks
assertTrue(Math.abs(aTotal - 1000 - 3333) <= 100, "a count in second window: " + aTotal);
assertTrue(Math.abs(bTotal - 9000 - 6667) <= 100, "b count in second window: " + bTotal);
}

/**
* Reordering a selector's upstream list starts a fresh pool and the old
* state never leaks into the new order.
*/
@Test
public void reorderedUpstreamListStartsFreshState() {
Upstream a = Upstream.builder().url("ro-a:8080").weight(1).status(true).build();
Upstream b = Upstream.builder().url("ro-b:8080").weight(9).status(true).build();
RoundRobinLoadBalancer loadBalancer = new RoundRobinLoadBalancer();
List<Upstream> original = List.of(a, b);
Map<String, Integer> counts = new HashMap<>();
IntStream.range(0, 10000).forEach(i ->
counts.merge(loadBalancer.select(original, new LoadBalanceData()).getUrl(), 1, Integer::sum));
assertEquals(1000, counts.get("ro-a:8080").intValue());
List<Upstream> reordered = List.of(b, a);
IntStream.range(0, 10000).forEach(i ->
counts.merge(loadBalancer.select(reordered, new LoadBalanceData()).getUrl(), 1, Integer::sum));
assertEquals(1000, counts.get("ro-a:8080").intValue() - 1000);
}
}
Loading