Phani Kumar Bhamidipati
Phani Kumar Bhamidipati

Reputation: 13283

How to retrieve pod memory and cpu usage from Kubernetes using Java Api

Is there a Java API to retrieve the CPU and Memory usage of the pod? I am not looking for a complete monitoring solution like using Grafana or Prometheus or not using the kubectl top pod, but wanted to retrieve the current usage using Java API. Any example or reference documentation on how to do will be of great help.

Client libraries

https://kubernetes.io/docs/reference/using-api/client-libraries/

Examples - https://github.com/kubernetes-client/java#installation

Similar questions:

how to get max usage of mem and cpu usage of pod on kubernetes

kubernetes Pod CPU usage in % from metric server

Thanks.

Upvotes: 1

Views: 4042

Answers (2)

Meghana Srinivasulu
Meghana Srinivasulu

Reputation: 1

You can use the Fabric8 java client for Kubernates.

Refer this link for an example implementation:

https://github.com/rohanKanojia/kubernetes-client/commit/d6453e0b6a424c89d0f9e237ab818a0f456ec11f#diff-d8a58a09a3dece4f92fd5fefd1927e08

try (KubernetesClient client = new DefaultKubernetesClient()) {
      NodeMetricsList nodeMetricList = client.top().nodes().metrics();

      log("name CPU(cores) CPU(%) Memory(Bytes) Memory(%)");
      for (NodeMetrics nodeMetrics : nodeMetricList.getItems()) {
        log(nodeMetrics.toString());
        log(nodeMetrics.getUsage().toString());
        log(nodeMetrics.getMetadata().getName() +
          " " + nodeMetrics.getUsage().get("cpu") +
          " " + nodeMetrics.getUsage().get("memory"));
      }

    } catch (KubernetesClientException e) {
      logger.error(e.getMessage(), e);

For pods,

PodMetricsList podMetricList = client.top().pods().metrics();
            for(PodMetrics metrics: podMetricList.getItems())
            {
                for(ContainerMetrics containerMetric : metrics.getContainers())
                {
                    Quantity quantity = containerMetric.getUsage().get("cpu");
                    String amount = quantity.getAmount();
                }
            }

Also, pasting this link for reference:

https://developers.redhat.com/blog/2020/05/20/getting-started-with-the-fabric8-kubernetes-java-client/

Upvotes: 0

weibeld
weibeld

Reputation: 15232

You can install the Metrics Server and then fetch the resource usage of Pods with direct HTTP requests to the Resource Metrics API through the API server:

GET /apis/metrics/v1alpha1/namespaces/{namespace}/pods/{pod}

The Resource Metrics API does not seem to be included in the official Java client library. So, you probably have to make the API requests manually.

Upvotes: 1

Related Questions