Skip to content
Advertisement

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

kubectl top nodes
NAME                      CPU(cores)   CPU%  MEMORY(bytes)  MEMORY%

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

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

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"));
}

}

getting output is:-
node name
cpu:-1094942089n
memory:-7830672Ki

how will take the percentage values?

Advertisement

Answer

I had to implement this same feature recently, unfortunately I didn’t find a way to get the percentages just by using the top() API alone, I had to perform two calls, one to nodes() in order to retrieve total capacity and another one to top() to retrieve used capacity. Then it was just a matter of calculating percentage.

A snippet of the working code:

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;
    }
  }
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement