Reputation: 13283
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
Reputation: 1
You can use the Fabric8 java client for Kubernates.
Refer this link for an example implementation:
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:
Upvotes: 0
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