Skip to content

Commit

Permalink
Enable to query better assignment by Web API (#610)
Browse files Browse the repository at this point in the history
  • Loading branch information
chia7712 authored Aug 23, 2022
1 parent a707a6c commit 8172942
Show file tree
Hide file tree
Showing 10 changed files with 306 additions and 25 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
import org.astraea.app.cost.HasClusterCost;
import org.astraea.app.metrics.HasBeanObject;

class BalancerUtils {
public class BalancerUtils {

/**
* Create a {@link ClusterInfo} with its log placement replaced by {@link ClusterLogAllocation}.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,11 @@

@FunctionalInterface
public interface RebalancePlanGenerator {

static RebalancePlanGenerator random(int numberOfShuffle) {
return new ShufflePlanGenerator(() -> numberOfShuffle);
}

/**
* Generate a rebalance proposal, noted that this function doesn't require proposing exactly the
* same plan for the same input argument. There can be some randomization that takes part in this
Expand Down
37 changes: 18 additions & 19 deletions app/src/main/java/org/astraea/app/cost/ReplicaLeaderCost.java
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,15 @@ public ClusterCost clusterCost(ClusterInfo clusterInfo, ClusterBean clusterBean)
return () -> dispersion.calculate(brokerScore.values());
}

Map<Integer, Integer> leaderCount(ClusterInfo ignored, ClusterBean clusterBean) {
private static Map<Integer, Integer> leaderCount(
ClusterInfo clusterInfo, ClusterBean clusterBean) {
var leaderCount = leaderCount(clusterBean);
// if there is no available metrics, we re-count the leaders based on cluster information
if (leaderCount.values().stream().mapToInt(i -> i).sum() == 0) return leaderCount(clusterInfo);
return leaderCount;
}

static Map<Integer, Integer> leaderCount(ClusterBean clusterBean) {
return clusterBean.all().entrySet().stream()
.collect(
Collectors.toMap(
Expand All @@ -60,26 +68,17 @@ Map<Integer, Integer> leaderCount(ClusterInfo ignored, ClusterBean clusterBean)
.sum()));
}

static Map<Integer, Integer> leaderCount(ClusterInfo clusterInfo) {
return clusterInfo.topics().stream()
.flatMap(t -> clusterInfo.availableReplicaLeaders(t).stream())
.collect(Collectors.groupingBy(r -> r.nodeInfo().id()))
.entrySet()
.stream()
.collect(Collectors.toUnmodifiableMap(Map.Entry::getKey, e -> e.getValue().size()));
}

@Override
public Optional<Fetcher> fetcher() {
return Optional.of(c -> List.of(ServerMetrics.ReplicaManager.LEADER_COUNT.fetch(c)));
}

public static class NoMetrics extends ReplicaLeaderCost {

@Override
Map<Integer, Integer> leaderCount(ClusterInfo clusterInfo, ClusterBean ignored) {
return clusterInfo.topics().stream()
.flatMap(t -> clusterInfo.availableReplicaLeaders(t).stream())
.collect(Collectors.groupingBy(r -> r.nodeInfo().id()))
.entrySet()
.stream()
.collect(Collectors.toUnmodifiableMap(Map.Entry::getKey, e -> e.getValue().size()));
}

@Override
public Optional<Fetcher> fetcher() {
return Optional.empty();
}
}
}
141 changes: 141 additions & 0 deletions app/src/main/java/org/astraea/app/web/BalancerHandler.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
/*
* 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.app.web;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import org.astraea.app.admin.Admin;
import org.astraea.app.admin.ClusterBean;
import org.astraea.app.balancer.BalancerUtils;
import org.astraea.app.balancer.RebalancePlanProposal;
import org.astraea.app.balancer.generator.RebalancePlanGenerator;
import org.astraea.app.balancer.log.ClusterLogAllocation;
import org.astraea.app.balancer.log.LogPlacement;
import org.astraea.app.cost.HasClusterCost;
import org.astraea.app.cost.ReplicaLeaderCost;

class BalancerHandler implements Handler {

static String LIMIT_KEY = "limit";

static int LIMIT_DEFAULT = 10000;
private final Admin admin;
private final RebalancePlanGenerator generator = RebalancePlanGenerator.random(30);
private final HasClusterCost costFunction;

BalancerHandler(Admin admin) {
this(admin, new ReplicaLeaderCost());
}

BalancerHandler(Admin admin, HasClusterCost costFunction) {
this.admin = admin;
this.costFunction = costFunction;
}

@Override
public Response get(Optional<String> target, Map<String, String> queries) {
var clusterInfo = admin.clusterInfo();
var clusterAllocation = ClusterLogAllocation.of(clusterInfo);
var cost = costFunction.clusterCost(clusterInfo, ClusterBean.EMPTY).value();
var limit = Integer.parseInt(queries.getOrDefault(LIMIT_KEY, String.valueOf(LIMIT_DEFAULT)));
var planAndCost =
generator
.generate(admin.brokerFolders(), clusterAllocation)
.limit(limit)
.map(RebalancePlanProposal::rebalancePlan)
.map(
cla ->
Map.entry(
cla,
costFunction
.clusterCost(BalancerUtils.merge(clusterInfo, cla), ClusterBean.EMPTY)
.value()))
.filter(e -> e.getValue() <= cost)
.min(Comparator.comparingDouble(Map.Entry::getValue));

return new Report(
cost,
planAndCost.map(Map.Entry::getValue).orElse(cost),
limit,
costFunction.getClass().getSimpleName(),
planAndCost
.map(
entry ->
ClusterLogAllocation.findNonFulfilledAllocation(
clusterAllocation, entry.getKey())
.stream()
.map(
tp ->
new Change(
tp.topic(),
tp.partition(),
placements(clusterAllocation.logPlacements(tp)),
placements(entry.getKey().logPlacements(tp))))
.collect(Collectors.toUnmodifiableList()))
.orElse(List.of()));
}

static List<Placement> placements(List<LogPlacement> lps) {
return lps.stream().map(Placement::new).collect(Collectors.toUnmodifiableList());
}

static class Placement {

final int brokerId;
final String directory;

Placement(LogPlacement lp) {
this.brokerId = lp.broker();
this.directory = lp.logDirectory().orElse(null);
}
}

static class Change {
final String topic;
final int partition;
final List<Placement> before;
final List<Placement> after;

Change(String topic, int partition, List<Placement> before, List<Placement> after) {
this.topic = topic;
this.partition = partition;
this.before = before;
this.after = after;
}
}

static class Report implements Response {
final double cost;
final double newCost;

final int limit;

final String function;
final List<Change> changes;

Report(double cost, double newCost, int limit, String function, List<Change> changes) {
this.cost = cost;
this.newCost = newCost;
this.limit = limit;
this.function = function;
this.changes = changes;
}
}
}
1 change: 1 addition & 0 deletions app/src/main/java/org/astraea/app/web/WebService.java
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ private static void execute(Argument arg) throws IOException {
server.createContext(
"/records", new RecordHandler(Admin.of(arg.configs()), arg.bootstrapServers()));
server.createContext("/reassignments", new ReassignmentHandler(Admin.of(arg.configs())));
server.createContext("/balancer", new BalancerHandler(Admin.of(arg.configs())));
server.start();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,10 @@ void testNoMetrics() {
ReplicaInfo.of("topic", 0, NodeInfo.of(10, "broker0", 1111), true, true, true),
ReplicaInfo.of("topic", 0, NodeInfo.of(10, "broker0", 1111), true, true, true),
ReplicaInfo.of("topic", 0, NodeInfo.of(11, "broker1", 1111), true, true, true));
var function = new ReplicaLeaderCost.NoMetrics();
var clusterInfo = Mockito.mock(ClusterInfo.class);
Mockito.when(clusterInfo.topics()).thenReturn(Set.of("topic"));
Mockito.when(clusterInfo.availableReplicaLeaders(Mockito.anyString())).thenReturn(replicas);
var cost = function.leaderCount(clusterInfo, ClusterBean.EMPTY);
var cost = ReplicaLeaderCost.leaderCount(clusterInfo);
Assertions.assertTrue(cost.containsKey(10));
Assertions.assertTrue(cost.containsKey(11));
Assertions.assertEquals(2, cost.size());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,13 +70,13 @@ void testNegativeWeight() {
IllegalArgumentException.class,
() ->
dispatcher.configure(
Configuration.of(Map.of(ReplicaLeaderCost.NoMetrics.class.getName(), "-1"))));
Configuration.of(Map.of(ReplicaLeaderCost.class.getName(), "-1"))));

// Test for cost functions configuring
dispatcher.configure(
Configuration.of(
Map.of(
ReplicaLeaderCost.NoMetrics.class.getName(),
ReplicaLeaderCost.class.getName(),
"0.1",
BrokerInputCost.class.getName(),
"2",
Expand All @@ -92,7 +92,7 @@ void testConfigureCostFunctions() {
dispatcher.configure(
Configuration.of(
Map.of(
ReplicaLeaderCost.NoMetrics.class.getName(),
ReplicaLeaderCost.class.getName(),
"0.1",
BrokerInputCost.class.getName(),
"2",
Expand Down
62 changes: 62 additions & 0 deletions app/src/test/java/org/astraea/app/web/BalancerHandlerTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
/*
* 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.app.web;

import java.time.Duration;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;
import org.astraea.app.admin.Admin;
import org.astraea.app.admin.ClusterBean;
import org.astraea.app.admin.ClusterInfo;
import org.astraea.app.common.Utils;
import org.astraea.app.cost.ClusterCost;
import org.astraea.app.cost.HasClusterCost;
import org.astraea.app.service.RequireBrokerCluster;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

public class BalancerHandlerTest extends RequireBrokerCluster {

@Test
void testReport() {
var topicName = Utils.randomString(10);
try (var admin = Admin.of(bootstrapServers())) {
admin.creator().topic(topicName).numberOfPartitions(10).numberOfReplicas((short) 3).create();
Utils.sleep(Duration.ofSeconds(3));
var handler = new BalancerHandler(admin, new MyCost());
var report =
Assertions.assertInstanceOf(
BalancerHandler.Report.class,
handler.get(Optional.empty(), Map.of(BalancerHandler.LIMIT_KEY, "30")));
Assertions.assertEquals(30, report.limit);
Assertions.assertNotEquals(0, report.changes.size());
Assertions.assertTrue(report.cost >= report.newCost);
Assertions.assertEquals(MyCost.class.getSimpleName(), report.function);
}
}

private static class MyCost implements HasClusterCost {
private final AtomicInteger count = new AtomicInteger(0);

@Override
public ClusterCost clusterCost(ClusterInfo clusterInfo, ClusterBean clusterBean) {
var cost = count.getAndIncrement() == 0 ? Double.MAX_VALUE : Math.random() * 100;
return () -> cost;
}
}
}
1 change: 1 addition & 0 deletions docs/web_server/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,4 @@ Astraea 建立了一套 Web Server 服務,使用者可以透過簡易好上手
- [/beans](./web_api_beans_chinese.md)
- [/reassignments](./web_api_reassignments_chinese.md)
- [/records](./web_api_records_chinese.md)
- [/balancer](./web_api_balancer_chinese.md)
Loading

0 comments on commit 8172942

Please sign in to comment.