-
Notifications
You must be signed in to change notification settings - Fork 61
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[DISPATCHER] Maintenance of smooth weight round robin #1396
Merged
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
2acb2ce
make SmoothRoundRobin share
wycccccc 78a8b74
adjust code logic
wycccccc aac1d83
resolve conflict
wycccccc b575b70
fix test
wycccccc 34a1c29
parameterized test of dispatcher
wycccccc 010c9fb
spotless
wycccccc 0de2bef
remove sout dispatch class name
wycccccc e64842f
resolve conflict
wycccccc 410a6ec
package-private
wycccccc 0ca7b04
resolve conflict
wycccccc File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
59 changes: 59 additions & 0 deletions
59
common/src/main/java/org/astraea/common/partitioner/RoundRobinKeeper.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,59 @@ | ||
/* | ||
* Licensed to the Apache Software Foundation (ASF) under one or more | ||
* contributor license agreements. See the NOTICE file distributed with | ||
* this work for additional information regarding copyright ownership. | ||
* The ASF licenses this file to You under the Apache License, Version 2.0 | ||
* (the "License"); you may not use this file except in compliance with | ||
* the License. You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
package org.astraea.common.partitioner; | ||
|
||
import java.time.Duration; | ||
import java.util.Map; | ||
import java.util.concurrent.atomic.AtomicInteger; | ||
import java.util.stream.Collectors; | ||
import java.util.stream.IntStream; | ||
import org.astraea.common.Lazy; | ||
import org.astraea.common.admin.ClusterInfo; | ||
import org.astraea.common.admin.NodeInfo; | ||
|
||
public class RoundRobinKeeper { | ||
private final AtomicInteger next = new AtomicInteger(0); | ||
final int[] roundRobin; | ||
final Duration roundRobinLease; | ||
volatile long timeToUpdateRoundRobin = -1; | ||
|
||
private RoundRobinKeeper(int preLength, Duration roundRobinLease) { | ||
this.roundRobin = new int[preLength]; | ||
this.roundRobinLease = roundRobinLease; | ||
} | ||
|
||
static RoundRobinKeeper of(int preLength, Duration roundRobinLease) { | ||
return new RoundRobinKeeper(preLength, roundRobinLease); | ||
} | ||
|
||
synchronized void tryToUpdate(ClusterInfo clusterInfo, Lazy<Map<Integer, Double>> costToScore) { | ||
if (System.currentTimeMillis() >= timeToUpdateRoundRobin) { | ||
var roundRobin = RoundRobin.smooth(costToScore.get()); | ||
var ids = | ||
clusterInfo.nodes().stream().map(NodeInfo::id).collect(Collectors.toUnmodifiableSet()); | ||
// TODO: make ROUND_ROBIN_LENGTH configurable ??? | ||
IntStream.range(0, this.roundRobin.length) | ||
.forEach(index -> this.roundRobin[index] = roundRobin.next(ids).orElse(-1)); | ||
timeToUpdateRoundRobin = System.currentTimeMillis() + roundRobinLease.toMillis(); | ||
} | ||
} | ||
|
||
int next() { | ||
return roundRobin[ | ||
next.getAndUpdate(previous -> previous >= roundRobin.length - 1 ? 0 : previous + 1)]; | ||
} | ||
} |
79 changes: 79 additions & 0 deletions
79
common/src/main/java/org/astraea/common/partitioner/SmoothWeightCal.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,79 @@ | ||
/* | ||
* Licensed to the Apache Software Foundation (ASF) under one or more | ||
* contributor license agreements. See the NOTICE file distributed with | ||
* this work for additional information regarding copyright ownership. | ||
* The ASF licenses this file to You under the Apache License, Version 2.0 | ||
* (the "License"); you may not use this file except in compliance with | ||
* the License. You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
package org.astraea.common.partitioner; | ||
|
||
import java.util.ArrayList; | ||
import java.util.Map; | ||
import java.util.function.Supplier; | ||
import java.util.stream.Collectors; | ||
import org.astraea.common.Lazy; | ||
import org.astraea.common.cost.Dispersion; | ||
|
||
public final class SmoothWeightCal<E> { | ||
private final double UPPER_LIMIT_OFFSET_RATIO = 0.1; | ||
private final Dispersion dispersion = Dispersion.standardDeviation(); | ||
private Map<E, Double> currentEffectiveWeightResult; | ||
Lazy<Map<E, Double>> effectiveWeightResult = Lazy.of(); | ||
|
||
SmoothWeightCal(Map<E, Double> effectiveWeight) { | ||
this.effectiveWeightResult.get( | ||
() -> | ||
effectiveWeight.entrySet().stream() | ||
.collect(Collectors.toMap(Map.Entry::getKey, ignored -> 1.0))); | ||
this.currentEffectiveWeightResult = effectiveWeightResult.get(); | ||
} | ||
|
||
/** | ||
* Update effective weight. | ||
* | ||
* @param brokerScore Broker Score. | ||
*/ | ||
synchronized void refresh(Supplier<Map<E, Double>> brokerScore) { | ||
this.effectiveWeightResult = | ||
Lazy.of( | ||
() -> { | ||
var score = brokerScore.get(); | ||
var avgScore = score.values().stream().mapToDouble(i -> i).average().orElse(1.0); | ||
var offsetRatioOfBroker = | ||
score.entrySet().stream() | ||
.collect( | ||
Collectors.toMap( | ||
Map.Entry::getKey, | ||
entry -> (entry.getValue() - avgScore) / avgScore)); | ||
// If the average offset of all brokers from the cluster is greater than 0.1, it is | ||
// unbalanced. | ||
var balance = | ||
dispersion.calculate(new ArrayList<>(score.values())) | ||
> UPPER_LIMIT_OFFSET_RATIO * avgScore; | ||
this.currentEffectiveWeightResult = | ||
this.currentEffectiveWeightResult.entrySet().stream() | ||
.collect( | ||
Collectors.toUnmodifiableMap( | ||
Map.Entry::getKey, | ||
entry -> { | ||
var offsetRatio = offsetRatioOfBroker.get(entry.getKey()); | ||
var weight = | ||
balance | ||
? entry.getValue() * (1 - offsetRatio) | ||
: entry.getValue(); | ||
return Math.max(weight, 0.1); | ||
})); | ||
|
||
return this.currentEffectiveWeightResult; | ||
}); | ||
} | ||
} |
130 changes: 130 additions & 0 deletions
130
common/src/main/java/org/astraea/common/partitioner/SmoothWeightRoundRobinDispatcher.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,130 @@ | ||
/* | ||
* Licensed to the Apache Software Foundation (ASF) under one or more | ||
* contributor license agreements. See the NOTICE file distributed with | ||
* this work for additional information regarding copyright ownership. | ||
* The ASF licenses this file to You under the Apache License, Version 2.0 | ||
* (the "License"); you may not use this file except in compliance with | ||
* the License. You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
package org.astraea.common.partitioner; | ||
|
||
import java.net.InetSocketAddress; | ||
import java.time.Duration; | ||
import java.util.Map; | ||
import java.util.Optional; | ||
import java.util.concurrent.ConcurrentLinkedDeque; | ||
import java.util.function.Function; | ||
import java.util.function.Supplier; | ||
import java.util.stream.Collectors; | ||
import org.astraea.common.Configuration; | ||
import org.astraea.common.Utils; | ||
import org.astraea.common.admin.BrokerTopic; | ||
import org.astraea.common.admin.ClusterInfo; | ||
import org.astraea.common.cost.NeutralIntegratedCost; | ||
import org.astraea.common.metrics.collector.MetricCollector; | ||
|
||
public class SmoothWeightRoundRobinDispatcher extends Dispatcher { | ||
private static final int ROUND_ROBIN_LENGTH = 400; | ||
private static final String JMX_PORT = "jmx.port"; | ||
public static final String ROUND_ROBIN_LEASE_KEY = "round.robin.lease"; | ||
private final ConcurrentLinkedDeque<Integer> unusedPartitions = new ConcurrentLinkedDeque<>(); | ||
private final MetricCollector metricCollector = | ||
MetricCollector.builder().interval(Duration.ofMillis(1500)).build(); | ||
private final NeutralIntegratedCost neutralIntegratedCost = new NeutralIntegratedCost(); | ||
private SmoothWeightCal<Integer> smoothWeightCal; | ||
private RoundRobinKeeper roundRobinKeeper; | ||
private Function<Integer, Optional<Integer>> jmxPortGetter = (id) -> Optional.empty(); | ||
|
||
@Override | ||
public int partition(String topic, byte[] key, byte[] value, ClusterInfo clusterInfo) { | ||
var partitionLeaders = clusterInfo.replicaLeaders(topic); | ||
// just return first partition if there is no available partitions | ||
if (partitionLeaders.isEmpty()) return 0; | ||
|
||
// just return the only one available partition | ||
if (partitionLeaders.size() == 1) return partitionLeaders.get(0).partition(); | ||
|
||
var targetPartition = unusedPartitions.poll(); | ||
refreshPartitionMetaData(clusterInfo, topic); | ||
Supplier<Map<Integer, Double>> supplier = | ||
() -> | ||
// fetch the latest beans for each node | ||
neutralIntegratedCost.brokerCost(clusterInfo, metricCollector.clusterBean()).value(); | ||
|
||
smoothWeightCal.refresh(supplier); | ||
|
||
if (targetPartition == null) { | ||
roundRobinKeeper.tryToUpdate(clusterInfo, smoothWeightCal.effectiveWeightResult); | ||
var target = roundRobinKeeper.next(); | ||
|
||
var candidate = | ||
target < 0 ? partitionLeaders : clusterInfo.replicaLeaders(BrokerTopic.of(target, topic)); | ||
candidate = candidate.isEmpty() ? partitionLeaders : candidate; | ||
|
||
targetPartition = candidate.get((int) (Math.random() * candidate.size())).partition(); | ||
} | ||
|
||
return targetPartition; | ||
} | ||
|
||
@Override | ||
public void close() { | ||
metricCollector.close(); | ||
} | ||
|
||
@Override | ||
public void configure(Configuration configuration) { | ||
configure( | ||
configuration.integer(JMX_PORT), | ||
PartitionerUtils.parseIdJMXPort(configuration), | ||
configuration | ||
.string(ROUND_ROBIN_LEASE_KEY) | ||
.map(Utils::toDuration) | ||
// The duration of updating beans is 4 seconds, so | ||
// the default duration of updating RR is 4 seconds. | ||
.orElse(Duration.ofSeconds(4))); | ||
} | ||
|
||
void configure( | ||
Optional<Integer> jmxPortDefault, | ||
Map<Integer, Integer> customJmxPort, | ||
Duration roundRobinLease) { | ||
this.jmxPortGetter = id -> Optional.ofNullable(customJmxPort.get(id)).or(() -> jmxPortDefault); | ||
this.neutralIntegratedCost.fetcher().ifPresent(metricCollector::addFetcher); | ||
this.roundRobinKeeper = RoundRobinKeeper.of(ROUND_ROBIN_LENGTH, roundRobinLease); | ||
this.smoothWeightCal = | ||
new SmoothWeightCal<>( | ||
customJmxPort.entrySet().stream() | ||
.collect(Collectors.toMap(Map.Entry::getKey, ignore -> 1.0))); | ||
} | ||
|
||
@Override | ||
public void onNewBatch(String topic, int prevPartition) { | ||
unusedPartitions.add(prevPartition); | ||
} | ||
|
||
private void refreshPartitionMetaData(ClusterInfo clusterInfo, String topic) { | ||
clusterInfo.availableReplicas(topic).stream() | ||
.filter(p -> !metricCollector.listIdentities().contains(p.nodeInfo().id())) | ||
.forEach( | ||
node -> { | ||
if (!metricCollector.listIdentities().contains(node.nodeInfo().id())) { | ||
jmxPortGetter | ||
.apply(node.nodeInfo().id()) | ||
.ifPresent( | ||
port -> | ||
metricCollector.registerJmx( | ||
node.nodeInfo().id(), | ||
InetSocketAddress.createUnresolved(node.nodeInfo().host(), port))); | ||
} | ||
}); | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
這個註解很棒