client-go开发k8s:列出所有pods并且判断是否存在

一、详解各模块

.
├── discovery                   # 定义DsicoveryClient客户端。作用是用于发现k8s所支持GVR(Group, Version, Resources)。
├── dynamic                     # 定义DynamicClient客户端。可以用于访问k8s Resources(如: Pod, Deploy...),也可以访问用户自定义资源(即: CRD)。
├── informers                   # k8s中各种Resources的Informer机制的实现。
├── kubernetes                  # 定义ClientSet客户端。它只能用于访问k8s Resources。每一种资源(如: Pod等)都可以看成是一个客端,而ClientSet是多个客户端的集合,它对RestClient进行了封装,引入了对Resources和Version的管理。通常来说ClientSet是client-gen来自动生成的。
├── listers                     # 提供对Resources的获取功能。对于Get()和List()而言,listers提供给二者的数据都是从缓存中读取的。
├── pkg                         
├── plugin                      # 提供第三方插件。如:GCP, OpenStack等。
├── rest                        # 定义RestClient,实现了Restful的API。同时会支持Protobuf和Json格式数据。
├── scale                       # 定义ScalClient。用于Deploy, RS, RC等的扩/缩容。
├── tools                       # 定义诸如SharedInformer、Reflector、DealtFIFO和Indexer等常用工具。实现client查询和缓存机制,减少client与api-server请求次数,减少api-server的压力。
├── transport
└── util                        # 提供诸如WorkQueue、Certificate等常用方法。

二、代码示例:

package main

import (
        "context"
        "flag"
        "fmt"
        "path/filepath"
        "time"

        "k8s.io/apimachinery/pkg/api/errors"
        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"
)

func main() {
        var kubeconfig *string
        fmt.Println(homedir.HomeDir()) 
        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", "~/.kube/config", "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 clientset
        clientset, err := kubernetes.NewForConfig(config)
        if err != nil {
                panic(err.Error())
        }
        for {
                pods, err := clientset.CoreV1().Pods("").List(context.TODO(), metav1.ListOptions{})
                if err != nil {
                        panic(err.Error())
                }
                fmt.Printf("There are %d pods in the cluster\n", len(pods.Items))

                // Examples for error handling:
                // - Use helper functions like e.g. errors.IsNotFound()
                // - And/or cast to StatusError and use its properties like e.g. ErrStatus.Message
                namespace := "default"
                pod := "example-xxxxx"
                if _, err = clientset.CoreV1().Pods(namespace).Get(context.TODO(), pod, metav1.GetOptions{}); err != nil {

                   if errors.IsNotFound(err) {
                        fmt.Printf("Pod %s in namespace %s not found\n", pod, namespace)
                   } 

                }else {
                        fmt.Printf("Found pod %s in namespace %s\n", pod, namespace)
                }

                time.Sleep(5 * time.Second)
        }
}

列出pods的单项

fmt.Println(pods.Items[1].Name)
    fmt.Println(pods.Items[1].CreationTimestamp)
    fmt.Println(pods.Items[1].Labels)
    fmt.Println(pods.Items[1].Namespace)
    fmt.Println(pods.Items[1].Status.HostIP)
    fmt.Println(pods.Items[1].Status.PodIP)
    fmt.Println(pods.Items[1].Status.StartTime)
    fmt.Println(pods.Items[1].Status.Phase)  //状态
    fmt.Println(pods.Items[1].Status.ContainerStatuses[0].RestartCount)   //重启次数
    fmt.Println(pods.Items[1].Status.ContainerStatuses[0].Image) //获取重启时间

    //获取NODE
    fmt.Println("##################")
    nodes, err := clientset.CoreV1().Nodes().List(metav1.ListOptions{})
    fmt.Println(nodes.Items[0].Name)
    fmt.Println(nodes.Items[0].CreationTimestamp)    //加入集群时间
    fmt.Println(nodes.Items[0].Status.NodeInfo)
    fmt.Println(nodes.Items[0].Status.Conditions[len(nodes.Items[0].Status.Conditions)-1].Type)
    fmt.Println(nodes.Items[0].Status.Allocatable.Memory().String())

获取所有deployment

deployment,err:=clientset.AppsV1().Deployments("default").List(context.TODO(),metav1.ListOptions{})
        if err !=nil{
           panic(err.Error())
        }

        for idx,deploy:=range deployment.Items{
           fmt.Printf("%d-%s\n",idx,deploy.Name)
        }