首頁 > 後端開發 > Golang > 主體

如何使用 Go-client 庫從 Kubernetes 叢集檢索 Pod 詳細資訊?

DDD
發布: 2024-10-25 04:26:30
原創
727 人瀏覽過

How to Retrieve Pod Details from a Kubernetes Cluster Using the Go-client Library?

使用Kubernetes Go 用戶端檢索Pod 詳細資訊

在Kubernetes 叢集中工作時,擁有一種存取Pod 詳細資訊的方法至關重要高效。 Kubernetes client-go 庫提供了與叢集互動的接口,使開發人員能夠檢索廣泛的資訊。

一個常見的任務是列出特定命名空間中的所有 pod,類似於使用 kubectl 指令「kubectl get pods -n 」。此操作需要取得 pod 名稱、狀態、就緒情況、重啟次數和年齡等資訊。

為了實現此目的,我們利用 client-go 函式庫與 Kubernetes API 進行互動。以下程式碼片段示範如何列出給定命名空間內的pod:

<code class="go">func GetPods(client *meshkitkube.Client, namespace string) (*v1core.PodList, error) {
    podInterface := client.KubeClient.CoreV1().Pods(namespace)
    podList, err := podInterface.List(context.TODO(), v1.ListOptions{})
    if err != nil {
        return nil, err
    }
    return podList, nil
}</code>
登入後複製

檢索到pod 列表後,我們將迭代每個pod 及其容器以收集必要的詳細資訊:

<code class="go">for _, pod := range podList.Items {
    podCreationTime := pod.GetCreationTimestamp()
    age := time.Since(podCreationTime.Time).Round(time.Second)

    podStatus := pod.Status

    var containerRestarts int32
    var containerReady int
    var totalContainers int

    for container := range pod.Spec.Containers {
        containerRestarts += podStatus.ContainerStatuses[container].RestartCount
        if podStatus.ContainerStatuses[container].Ready {
            containerReady++
        }
        totalContainers++
    }

    name := pod.GetName()
    ready := fmt.Sprintf("%v/%v", containerReady, totalContainers)
    status := fmt.Sprintf("%v", podStatus.Phase)
    restarts := fmt.Sprintf("%v", containerRestarts)
    ageS := age.String()

    data = append(data, []string{name, ready, status, restarts, ageS})
}</code>
登入後複製

產生的「data」變數包含一個字串陣列的數組,表示所需的pod 詳細資料:名稱、就緒情況、狀態、重新啟動次數和年齡。然後可以根據需要輕鬆列印或操作這些數據。

以上是如何使用 Go-client 庫從 Kubernetes 叢集檢索 Pod 詳細資訊?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!