首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用java io.fabric8 kubernetes-客户端库获得节点CPU%和内存%值

如何使用java io.fabric8 kubernetes-客户端库获得节点CPU%和内存%值
EN

Stack Overflow用户
提问于 2021-05-24 14:19:12
回答 1查看 869关注 0票数 1

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%和内存%值。

代码语言:javascript
复制
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

如何获得百分比值?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-05-25 14:34:24

最近我不得不实现同样的特性,不幸的是,我没有找到仅仅通过使用top() API获得百分比的方法,我不得不执行两个调用,一个调用nodes()以检索总容量,另一个调用top()检索已使用的容量。这只是一个计算百分比的问题。

工作代码的片段:

代码语言:javascript
复制
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;
    }
  }
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67673662

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档