如何使用 Kubernetes go-client 库找到 Pod 的控制器 (Deployment/DaemonSet)?

How can I find a Pod's Controller (Deployment/DaemonSet) using the Kubernetes go-client library?

使用以下代码,我可以获取集群中的所有 Pods 运行。如何使用 Kubernetes go-client 库找到 Pod 控制器 (Deployment/DaemonSet)?

var kubeconfig *string
if home := homedir.HomeDir(); home != "" {
    kubeconfig = flag.String("kubeconfig", filepath.Join(home, ".kube", "config"), "(optional) absolute path to the kubeconfig file")
} else {
    kubeconfig = flag.String("kubeconfig", "", "absolute path to the kubeconfig file")
}
flag.Parse()
// use the current context in kubeconfig
config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
if err != nil {
    panic(err.Error())
}

// create the kubeClient
kubeClient, err := kubernetes.NewForConfig(config)
metricsClient, err := metricsv.NewForConfig(config)

if err != nil {
    panic(err.Error())
}

pods, err := kubeClient.CoreV1().Pods("").List(context.TODO(), metav1.ListOptions{})

if err != nil {
    panic(err.Error())
}

for _, pod := range pods.Items {
    fmt.Println(pod.Name)
    // how can I get the Pod controller? (Deployment/DaemonSet)
    // e.g. fmt.Println(pod.Controller.Name)
}

您通常可以在元数据部分的 ownerReference: 字段中看到管理 Pod 的内容。

示例:

  ownerReferences:
  - apiVersion: apps/v1
    blockOwnerDeletion: true
    controller: true
    kind: ReplicaSet
    name: my-app-6b94f5f96
    uid: 46493c9e-f264-49b8-9f52-d1d919aedbf2

按照@Jonas 的建议,我找到了 Pod 的经理。这是一个完整的示例:

package main

import (
    "context"
    "flag"
    "fmt"
    metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    "k8s.io/client-go/kubernetes"
    "k8s.io/client-go/tools/clientcmd"
    "k8s.io/client-go/util/homedir"
    "path/filepath"
)

func main() {
    var kubeconfig *string
    if home := homedir.HomeDir(); home != "" {
        kubeconfig = flag.String("kubeconfig", filepath.Join(home, ".kube", "config"), "(optional) absolute path to the kubeconfig file")
    } else {
        kubeconfig = flag.String("kubeconfig", "", "absolute path to the kubeconfig file")
    }
    flag.Parse()
    // use the current context in kubeconfig
    config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
    if err != nil {
        panic(err.Error())
    }

    // create the kubeClient
    kubeClient, err := kubernetes.NewForConfig(config)

    if err != nil {
        panic(err.Error())
    }

    pods, err := kubeClient.CoreV1().Pods("").List(context.TODO(), metav1.ListOptions{})

    if err != nil {
        panic(err.Error())
    }

    for _, pod := range pods.Items {
        if len(pod.OwnerReferences) == 0 {
            fmt.Printf("Pod %s has no owner", pod.Name)
            continue
        }

        var ownerName, ownerKind string

        switch pod.OwnerReferences[0].Kind {
        case "ReplicaSet":
            replica, repErr := kubeClient.AppsV1().ReplicaSets(pod.Namespace).Get(context.TODO(), pod.OwnerReferences[0].Name, metav1.GetOptions{})
            if repErr != nil {
                panic(repErr.Error())
            }

            ownerName = replica.OwnerReferences[0].Name
            ownerKind = "Deployment"
        case "DaemonSet", "StatefulSet":
            ownerName = pod.OwnerReferences[0].Name
            ownerKind = pod.OwnerReferences[0].Kind
        default:
            fmt.Printf("Could not find resource manager for type %s\n", pod.OwnerReferences[0].Kind)
            continue
        }

        fmt.Printf("POD %s is managed by %s %s\n", pod.Name, ownerName, ownerKind)
    }
}