首頁  >  文章  >  後端開發  >  如何使用 Go 用戶端列出 Kubernetes 中的 Pod 詳細資訊?

如何使用 Go 用戶端列出 Kubernetes 中的 Pod 詳細資訊?

Mary-Kate Olsen
Mary-Kate Olsen原創
2024-10-24 19:04:02649瀏覽

How to List Pod Details in Kubernetes using the Go Client?

使用Kubernetes Go-Client 列出Pod 詳細資料

使用Kubernetes client-go 庫存取pod 詳細資訊可讓您以程式方式檢索類似以下內容的資訊使用kubectl get pods 指令。

要獲取給定命名空間內pod 的特定詳細信息,例如名稱、狀態、就緒狀態、重新啟動和壽命,請按照以下步驟操作:

  1. 導入必要的套件:
<code class="go">import (
    "context"
    "fmt"
    "time"

    corev1 "k8s.io/api/core/v1"
    metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)</code>
  1. 建立一個函數來列出所需命名空間中的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>
  1. 迭代檢索到的pod 擷取所需資料:
<code class="go">// List pod details similar to `kubectl get pods -n <my namespace>`
for _, pod := range podList.Items {
    podCreationTime := pod.GetCreationTimestamp()
    age := time.Since(podCreationTime.Time).Round(time.Second)
    podStatus := pod.Status
    containerRestarts := int32(0)
    containerReady := 0
    totalContainers := len(pod.Spec.Containers)
    for container := range pod.Spec.Containers {
        containerRestarts += podStatus.ContainerStatuses[container].RestartCount
        if podStatus.ContainerStatuses[container].Ready {
            containerReady++
        }
    }
    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>

以上是如何使用 Go 用戶端列出 Kubernetes 中的 Pod 詳細資訊?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn