如何使用 java io.fabric8 kubernetes-client 库获取节点 CPU% 和 MEMORY% 值

how to get the Node CPU% and MEMORY% value using java io.fabric8 kubernetes-client library

kubectl 顶级节点
NAME CPU(核心) CPU% 内存(字节) MEMORY%

gsdjsgfhdsgfz-12345665-jisj000000 934m 24% 10439Mi 82%
gsdjsgfhdsgfz-12345665-jisj000001 717m 18% 9132Mi 72%
gsdjsgfhdsgfz-12345665-jisj000002 1099m 28% 7614Mi 60%

如何使用 java io.fabric8 kubernetes-client 库获取 CPU% 和 MEMORY% 值。

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

如何取百分比值?

我最近不得不实现同样的功能,不幸的是我没有找到一种方法来仅通过单独使用 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;
    }
  }