簡體   English   中英

如何從 kubectl describe pods 中檢索所有數據<namespace>來自集群內客戶端-go api 調用</namespace>

[英]How to retrieve all the data from kubectl describe pods <namespace> from an in-cluster client-go api call

我需要獲取一些 pod 信息,這些信息將用於一些將在集群內運行的單元測試。 我需要 kubectl describe po 提供的所有信息,但來自集群 api 調用。

我有一些工作代碼可以調用 api 調用 apis/metrics.k8s.io/v1beta1/pods,並在 minikube 上安裝了 metrics-server 進行測試,這一切正常,給我 output 像這樣:

Namespace: kube-system
Pod name: heapster-rgnlj
SelfLink: /apis/metrics.k8s.io/v1beta1/namespaces/kube-system/pods/heapster-rgnlj
CreationTimestamp: 2019-09-10 12:27:13 +0000 UTC
Window: 30s
Timestamp: 2019-09-10 12:26:23 +0000 UTC
Name: heapster
Cpu usage: 82166n
Mem usage: 19420Ki 
...
func getMetrics(clientset *kubernetes.Clientset, pods *PodMetricsList) error {
    data, err := clientset.RESTClient().Get().AbsPath("apis/metrics.k8s.io/v1beta1/pods").DoRaw()
    if err != nil {
        return err
    }
    err = json.Unmarshal(data, &pods)
    return err
}

func main() {

    config, err := rest.InClusterConfig()
    if err != nil {
        fmt.Println(err)
    }
    // creates the clientset
    clientset, err := kubernetes.NewForConfig(config)
    if err != nil {
        fmt.Println(err)
    }
    var pods PodMetricsList
    err = getMetrics(clientset, &pods)
    if err != nil {
        fmt.Println(err)
    }

    for _, m := range pods.Items {

        fmt.Print("Namespace: ", m.Metadata.Namespace, "\n", "Pod name: ", m.Metadata.Name, "\n", )
        fmt.Print("SelfLink: ", m.Metadata.SelfLink, "\n", "CreationTimestamp: ", m.Metadata.CreationTimestamp, "\n", )
        fmt.Print("Window: ", m.Window, "\n", "Timestamp: ", m.Timestamp, "\n", )

        for _, c := range m.Containers {
            fmt.Println("Name:", c.Name)
            fmt.Println("Cpu usage:", c.Usage.CPU)
            fmt.Println("Mem usage:", c.Usage.Memory, "\n")
...

正如我所說,我真正需要的是您通過“描述豆莢”類型調用獲得的結果。 瀏覽了 kube.netes 源代碼后,這個 NodeDescriber 看起來像 function 的正確類型,但我對如何集成/實現它以獲得所需結果有點不知所措。

kube.netes/pkg/printers/internalversion/describe.go

4f2d7b9 中的第 2451 行

func (d *NodeDescriber) Describe(命名空間、名稱字符串、描述符設置...等)

我是 Go 的新手,對 kube.netes 不是特別熟悉。 任何關於如何 go 的指示將不勝感激。

從staging / src / k8s.io / kubectl / pkg / describe / versioned / describe.go中查看describePodDescribe函數,應該可以更好地了解如何執行此操作。 並且由於DescribePodDescriber是公開的,因此您可以在用例中重用它們。

你可以用這幾個CoreV1Client具有 FUNC,返回一個PodInterface具有列表 FUNC這將返回一個列表波德對象為給定的命名空間。

這些pod對象將提供Describe函數所需的Name,Namespace是已知的以及describe.DescriberSettings只是一種結構類型,您可以內聯以啟用在Describe輸出中顯示事件。

使用“ 列表”功能只能列出一次該Pod。 如果您希望定期更新此列表,則可能需要查看Reflector和Informer模式。 兩者都主要在tools / cache包中實現,而docs在“ 有效檢測變更”部分中簡要說明了這一概念。

希望這可以幫助。

我沒有嘗試,但是我建議從以下開始:

1.使用帶有--verbosity選項的kubectl查看完整的api請求

 kubectl describe pod xxx -v=8 

喜歡:

  GET https://xx.xx.xx.xx:6443/api/v1/namespaces/default/events?fieldSelector=involvedObject.uid%3Ddd77c4aa-28e6-4bf0-8dfe-0d8610cbe9c9%2CinvolvedObject.name%3Dmy-app%2CinvolvedObject.namespace%3Ddefault

它包含與您的POD相關的字段: fieldSelector = involvedObject.uid,涉入對象.name,涉入對象.namespace

2.我覺得一個好的開始是從github func describePod開始的代碼。

希望對您有所幫助。

好吧,我最終只是寫了一個結構到 map 來自 /api/v1/pods 查詢的結果,並只是遍歷范圍以獲得我需要的東西。

這是結構,以防它為其他人節省一些時間。

type ApiV1PodMetricsList struct {
    Kind       string `json:"kind"`
    APIVersion string `json:"apiVersion"`
    Metadata   struct {
        SelfLink        string `json:"selfLink"`
        ResourceVersion string `json:"resourceVersion"`
    } `json:"metadata"`
    Items []struct {
        Metadata struct {
            Name              string    `json:"name"`
            Namespace         string    `json:"namespace"`
            SelfLink          string    `json:"selfLink"`
            UID               string    `json:"uid"`
            ResourceVersion   string    `json:"resourceVersion"`
            CreationTimestamp time.Time `json:"creationTimestamp"`
            Labels            struct {
                Run string `json:"run"`
            } `json:"labels"`
        } `json:"metadata"`
        Spec struct {
            Volumes []struct {
                Name   string `json:"name"`
                Secret struct {
                    SecretName  string `json:"secretName"`
                    DefaultMode string `json:"defaultMode"`
                } `json:"secret"`
            } `json:"volumes"`
            Containers []struct {
                Name      string `json:"name"`
                Image     string `json:"image"`
                Resources struct {
                } `json:"resources"`
                VolumeMounts []struct {
                    Name      string `json:"name"`
                    ReadOnly  string `json:"readOnly"`
                    MountPath string `json:"mountPath"`
                } `json:"volumeMounts"`
                TerminationMessagePath   string `json:"terminationMessagePath"`
                TerminationMessagePolicy string `json:"terminationMessagePolicy"`
                ImagePullPolicy          string `json:"imagePullPolicy"`
                Stdin                    string `json:"stdin"`
                StdinOnce                string `json:"stdinOnce"`
                Tty                      string `json:"tty"`
            } `json:"containers"`
            RestartPolicy                 string `json:"restartPolicy"`
            TerminationGracePeriodSeconds string `json:"terminationGracePeriodSeconds"`
            DnsPolicy                     string `json:"dnsPolicy"`
            ServiceAccountName            string `json:"serviceAccountName"`
            ServiceAccount                string `json:"serviceAccount"`
            NodeName                      string `json:"nodeName"`
            SecurityContext               struct {
            } `json:"securityContext"`
            SchedulerName string `json:"schedulerName"`
            Tolerations   []struct {
                Key               string `json:"key"`
                Operator          string `json:"operator"`
                Effect            string `json:"effect"`
                TolerationSeconds string `json:"tolerationSeconds"`
            } `json:"tolerations"`
            Priority           string `json:"priority"`
            EnableServiceLinks string `json:"enableServiceLinks"`
        } `json:"spec"`
        Status struct {
            Phase      string `json:"phase"`
            Conditions []struct {
                Type               string    `json:"type"`
                Status             string    `json:"status"`
                LastProbeTime      time.Time `json:"lastProbeTime"`
                LastTransitionTime time.Time `json:"lastTransitionTime"`
                Reason             string    `json:"reason"`
            } `json:"conditions"`
            HostIP            string `json:"hostIP"`
            PodIP             string `json:"podIP"`
            StartTime         string `json:"startTime"`
            ContainerStatuses []struct {
                Name  string `json:"name"`
                State struct {
                    Terminated struct {
                        ExitCode    string    `json:"exitCode"`
                        Reason      string    `json:"reason"`
                        StartedAt   time.Time `json:"startedAt"`
                        FinishedAt  time.Time `json:"finishedAt"`
                        ContainerID string    `json:"containerID"`
                    } `json:"terminated"`
                } `json:"state"`
                LastState struct {
                } `json:"lastState"`
                Ready        bool   `json:"ready"`
                RestartCount int64  `json:"restartCount"`
                Image        string `json:"image"`
                ImageID      string `json:"imageID"`
                ContainerID  string `json:"containerID"`
            } `json:"containerStatuses"`
            QosClass string `json:"qosClass"`
        } `json:"status"`
    } `json:"items"`
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM