为了账号安全,请及时绑定邮箱和手机立即绑定

Kubernetes go-client 列出类似于'kubectl get pods'的 pod

Kubernetes go-client 列出类似于'kubectl get pods'的 pod

Go
HUWWW 2022-08-30 21:29:00
我正在尝试使用 Kubernetes client-go 来访问集群中的 pod 详细信息。我想使用它来获取在一个特定命名空间中运行的 Pod 的详细信息,类似于 .kubectl get pods -n <my namespace>我想要的细节是 pod 的 、 、 和 。namestatusreadyrestartsage如何获取这些数据?
查看完整描述

1 回答

?
米琪卡哇伊

TA贡献1998条经验 获得超6个赞

因此,我编写了一个函数,该函数采用Kubernetes客户端(有关制作客户端的详细信息,请参阅condue-go)和一个命名空间,并返回所有可用的 pod -


func GetPods(client *meshkitkube.Client, namespace string) (*v1core.PodList, error) {

    // Create a pod interface for the given namespace

    podInterface := client.KubeClient.CoreV1().Pods(namespace)


    // List the pods in the given namespace

    podList, err := podInterface.List(context.TODO(), v1.ListOptions{})


    if err != nil {

        return nil, err

    }

    return podList, nil

}

在获得所有 Pod 后,我使用一个循环来运行每个 pod 中的所有 pod 和容器,并手动获取我需要的所有数据 -


// List all the pods similar to kubectl get pods -n <my namespace>

            for _, pod := range podList.Items {

                // Calculate the age of the pod

                podCreationTime := pod.GetCreationTimestamp()

                age := time.Since(podCreationTime.Time).Round(time.Second)


                // Get the status of each of the pods

                podStatus := pod.Status


                var containerRestarts int32

                var containerReady int

                var totalContainers int


                // If a pod has multiple containers, get the status from all

                for container := range pod.Spec.Containers {

                    containerRestarts += podStatus.ContainerStatuses[container].RestartCount

                    if podStatus.ContainerStatuses[container].Ready {

                        containerReady++

                    }

                    totalContainers++

                }


                // Get the values from the pod status

                name := pod.GetName()

                ready := fmt.Sprintf("%v/%v", containerReady, totalContainers)

                status := fmt.Sprintf("%v", podStatus.Phase)

                restarts := fmt.Sprintf("%v", containerRestarts)

                ageS := age.String()


                // Append this to data to be printed in a table

                data = append(data, []string{name, ready, status, restarts, ageS})

            }

这将导致与运行 时获得的数据完全相同。kubectl get pods -n <my namespace>


查看完整回答
反对 回复 2022-08-30
  • 1 回答
  • 0 关注
  • 214 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号