kubectl顶节点
名称 CPU(核心) CPU% 内存(字节) 内存%
gsdjsgfhdsgfz-12345665- 934m 000000 934m 24% 10439 82 82%
gsdjsgfhdsgfz-12345665- 717m 0001 717m 18% 9132 72 72%
gsdjsgfhdsgfz-12345665- 1099m 000002 1099 m 76 14 60 60%
如何使用java io.fabric8 kubernetes-客户端库获取CPU%和内存%值。
try (KubernetesClient k8s = new DefaultKubernetesClient()) {
NodeMetricsList nodeMetricsList = k8s.top().nodes().metrics();
for (NodeMetrics nodeMetrics : nodeMetricsList.getItems()) {
logger.info("{} {} {}", nodeMetrics.getMetadata().getName(),
nodeMetrics.getUsage().get("cpu"),
nodeMetrics.getUsage().get("memory"));
}}
产出是:-
节点名
cpu:-1094942089n
内存:-7830672Ki
如何获得百分比值?
发布于 2021-05-25 14:34:24
最近我不得不实现同样的特性,不幸的是,我没有找到仅仅通过使用top() API获得百分比的方法,我不得不执行两个调用,一个调用nodes()以检索总容量,另一个调用top()检索已使用的容量。这只是一个计算百分比的问题。
工作代码的片段:
public static void main(String[] args) {
KubernetesClient kubernetesClient = new DefaultKubernetesClient();
Map<String, Node> nodeMap = kubernetesClient.nodes().list().getItems()
.stream()
.collect(Collectors.toMap(node -> node.getMetadata().getName(), Function.identity()));
List<NodeUsage> usageList = kubernetesClient.top().nodes().metrics().getItems()
.stream()
.map(metric -> new NodeUsage(nodeMap.get(metric.getMetadata().getName()), metric.getUsage()))
.collect(Collectors.toList());
System.out.println(usageList);
}
private static class NodeUsage {
private final Node node;
private final BigDecimal cpuPercentage;
private final BigDecimal memoryPercentage;
private NodeUsage(Node node, Map<String, Quantity> used) {
this.node = node;
cpuPercentage = calculateUsage(used.get("cpu"), node.getStatus().getAllocatable().get("cpu"));
memoryPercentage = calculateUsage(used.get("memory"), node.getStatus().getAllocatable().get("memory"));
}
private static BigDecimal calculateUsage(Quantity used, Quantity total) {
return Quantity.getAmountInBytes(used)
.divide(Quantity.getAmountInBytes(total), 2, RoundingMode.FLOOR)
.multiply(BigDecimal.valueOf(100));
}
public Node getNode() {
return node;
}
public BigDecimal getCpuPercentage() {
return cpuPercentage;
}
public BigDecimal getMemoryPercentage() {
return memoryPercentage;
}
}https://stackoverflow.com/questions/67673662
复制相似问题