question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

describe pod equivalent code

See original GitHub issue

Hi, What is the equivalent java code using this library for following command

kubectl describe pod <pod name> -n <namespace>

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:12

github_iconTop GitHub Comments

1reaction
qhh0205commented, Dec 28, 2021

@rohanKanojia hi, my solution is similar to what you said. It can be calculated by myself. The calculation method is as follows:

  1. Find all pods on the node, and get the node’s total cpu and memory amount;
  2. Iterate the pods and get the sum of the container’s request and limit cpu and memory, this is equivalent to the allocated;
  3. Calculate percentage, just use the step 2 result divide the step 1 result;

The following is the code snippet that i write, share here:

Node node = fabricKbsService.getNodeDetail(KbsNode.valueOf(region.getRegionCode(), nodeQo.getNodeName()));
if (node == null) {
    return Result.fail(nodeQo.getNodeName());
}
// total cpu and memory of the node
Double nodeCpuTotal = CpuMemSizeUtil.humanReadableCpuSize2MilliCpu(node.getStatus().
        getAllocatable().get("cpu").getAmount());
Double nodeMemTotalBytes = CpuMemSizeUtil.humanReadableMemSize2BytesNum(node.getStatus()
        .getAllocatable().get("memory").getAmount() + " " + node.getStatus().getAllocatable()
        .get("memory").getFormat());
Double cpuRequestUsage = 0.0;
Double cpuLimitUsage = 0.0;
Double memRequestUsage = 0.0;
Double memLimitUsage = 0.0;

// 1. first get the pods list on the node.
List<Pod> podsOnNode = fabricKbsService.getNodePodList(KbsNode.valueOf(region.getRegionCode(),
        nodeQo.getNodeName()));
List<KbsPod> kbsPods = new ArrayList<>();
if (!CollectionUtils.isEmpty(podsOnNode)) {
    // 2. iterate the pods on the node, caculate the sum of the pod container's cpu and memory allocated.
    for (Pod pod : podsOnNode) {
        KbsPod kbsPod = new KbsPod();
        kbsPod.setPodInNamespace(pod.getMetadata().getNamespace());
        kbsPod.setPodName(pod.getMetadata().getName());
        kbsPods.add(kbsPod);
        logger.info("pod name: " + pod.getMetadata().getName() + ", namespace: "
                + pod.getMetadata().getNamespace());
        for (Container container : pod.getSpec().getContainers()) {
            // CPU/Memory Request
            if (container.getResources() != null && container.getResources().getRequests() != null) {
                if (container.getResources().getRequests().get("cpu") != null) {
                    String podCpuRequestAmount = container.getResources()
                            .getRequests().get("cpu").getAmount();
                    String podCpuRequestFormat = container.getResources()
                            .getRequests().get("cpu").getFormat();
                    logger.info("=== CPU Request Amount====:" + podCpuRequestAmount);
                    logger.info("=== CPU Request Format====:" + podCpuRequestFormat);
                    String cpuHumanReadable = StringUtils.isEmpty(podCpuRequestFormat) ?
                            podCpuRequestAmount : podCpuRequestAmount + " " + podCpuRequestFormat;
                    cpuRequestUsage += CpuMemSizeUtil.humanReadableCpuSize2MilliCpu(cpuHumanReadable);
                }
                if (container.getResources().getRequests().get("memory") != null) {
                    String podMemRequestAmount = container.getResources()
                            .getRequests().get("memory").getAmount();
                    String podMemRequestFormat = container.getResources()
                            .getRequests().get("memory").getFormat();
                    logger.info("=== Memory Request Amount====:" + podMemRequestAmount);
                    logger.info("=== Memory Request Format====:" + podMemRequestFormat);
                    String memHumanReadable = podMemRequestAmount + " " + podMemRequestFormat;
                    memRequestUsage += CpuMemSizeUtil.humanReadableMemSize2BytesNum(memHumanReadable);
                }
            }

            // CPU/Memory Limit
            if (container.getResources() != null && container.getResources().getLimits() != null) {
                if (container.getResources().getLimits().get("cpu") != null) {
                    String podCpuLimitAmount = container.getResources().getLimits().get("cpu").getAmount();
                    String podCpuLimitFormat = container.getResources().getLimits().get("cpu").getFormat();
                    logger.info("=== CPU Limit Amount====:" + podCpuLimitAmount);
                    logger.info("=== CPU Limit Format====:" + podCpuLimitFormat);
                    String cpuHumanReadable = StringUtils.isEmpty(podCpuLimitFormat) ?
                            podCpuLimitAmount : podCpuLimitAmount + " " + podCpuLimitFormat;
                    cpuLimitUsage += CpuMemSizeUtil.humanReadableCpuSize2MilliCpu(cpuHumanReadable);
                }
                if (container.getResources().getLimits().get("memory") != null) {
                    String podMemLimitAmount = container.getResources()
                            .getLimits().get("memory").getAmount();
                    String podMemLimitFormat = container.getResources()
                            .getLimits().get("memory").getFormat();
                    logger.info("=== Memory Limit Amount====:" + podMemLimitAmount);
                    logger.info("=== Memory Limit Format====:" + podMemLimitFormat);
                    String memHumanReadable = podMemLimitAmount + " " + podMemLimitFormat;
                    memLimitUsage += CpuMemSizeUtil.humanReadableMemSize2BytesNum(memHumanReadable);
                }
            }
        }
    }
}

// 3. Calculate percentage, just use the step 2 result divide the total node's cpu and memory;
NodeResourceUsageVo nodeResourceUsageVo = new NodeResourceUsageVo();
DecimalFormat df = new DecimalFormat("0");
nodeResourceUsageVo.setCpuRequestAllocatedMill(cpuRequestUsage + "m");
nodeResourceUsageVo.setCpuRequestAllocatedPercentage(
        df.format((cpuRequestUsage / nodeCpuTotal) * 100) + "%");
nodeResourceUsageVo.setMemRequestAllocated(PrettyMemoryUtil.prettyByteSize(memRequestUsage.longValue()));
nodeResourceUsageVo.setMemRequestAllocatedPercentage(
        df.format((memRequestUsage / nodeMemTotalBytes) * 100) + "%");
nodeResourceUsageVo.setCpuLimitAllocatedMill(cpuLimitUsage + "m");
nodeResourceUsageVo.setCpuLimitAllocatedPercentage(
        df.format((cpuLimitUsage / nodeCpuTotal) * 100) + "%");
nodeResourceUsageVo.setMemLimitAllocated(PrettyMemoryUtil.prettyByteSize(memLimitUsage.longValue()));
nodeResourceUsageVo.setMemLimitAllocatedPercentage(
        df.format((memLimitUsage / nodeMemTotalBytes) * 100) + "%");

The following is the result : image

1reaction
rohanKanojiacommented, Dec 27, 2021

@sauravmndl : I think you can get events by applying fieldselectors like this;

try (KubernetesClient client = new DefaultKubernetesClient()) {
  Map<String, String> fields = new HashMap<>();
  fields.put("involvedObject.name", "minikube");
  fields.put("involvedObject.kind", "Node");
  fields.put("involvedObject.uid", "minikube");
  client.v1().events()
      .withFields(fields)
      .list().getItems()
      .forEach(e -> System.out.println(e.getType() + " " + e.getReason() + " " + e.getMessage()));
}
Read more comments on GitHub >

github_iconTop Results From Across the Web

Pods - Kubernetes
A Pod is similar to a set of containers with shared namespaces and shared filesystem volumes. Using Pods. The following is an example...
Read more >
Using Kubectl Describe | Tutorial and Example - ContainIQ
In this guide, we highlight the `kubectl describe` command and provide an ... Common resource types include pods, services, nodes, events, and more....
Read more >
How to get pod info like use "kubectl describe pod xxxxx" and ...
It integrates a bunch of different API calls. If you are interested in the events, then yes, that code is the best way...
Read more >
How to get log and describe of pods in kubernetes by python ...
You can read the logs of a pod using the following code: from kubernetes.client.rest import ApiException from kubernetes import client, ...
Read more >
kubectl Cheat Sheet - Kubernetes
... kubectl describe nodes <node-name> $ kubectl describe pods <pod-name> $ kubectl describe pods/<pod-name> # Equivalent to previous $ kubectl describe ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found