kubernetes源码阅读(1):clientSet

本文深入探讨了Kubernetes client-go中的clientSet,从官方示例出发,解析了restClient.Config的构建,clientSet的定义和构建过程,以及如何使用clientSet对资源进行操作。clientSet是一个client的集合,它封装了对Resource和Version的管理,便于对Kubernetes资源进行便捷操作。
摘要由CSDN通过智能技术生成

client-go中的client - clientSet

从官方的demo说起

先看一下官方给到的example
流程比较明确

  1. 获取配置文件路径
  2. 构造配置文件
  3. 通过配置文件生成clientset
  4. 通过clientset对pod进行list、get等操作
func main() {
   
	var kubeconfig *string
	if home := 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 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"
		_, err = clientset.CoreV1().Pods(namespace).Get(context.TODO(), pod, metav1.GetOptions{
   })
		if errors.IsNotFound(err) {
   
			fmt.Printf("Pod %s in namespace %s not found\n", pod, namespace)
		} else if statusError, isStatus := err.(*errors.StatusError); isStatus {
   
			fmt.Printf("Error getting pod %s in namespace %s: %v\n",
				pod, namespace, statusError.ErrStatus.Message)
		} else if err != nil {
   
			panic(err.Error())
		} else {
   
			fmt.Printf("Found pod %s in namespace %s\n", pod, namespace)
		}

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

restClient.Config

BuildConfigFromFlags通过配置文件生成了一个*restclient.Config

// BuildConfigFromFlags is a helper function that builds configs from a master
// url or a kubeconfig filepath. These are passed in as command line flags for cluster
// components. Warnings should reflect this usage. If neither masterUrl or kubeconfigPath
// are passed in we fallback to inClusterConfig. If inClusterConfig fails, we fallback
// to the default config.
func BuildConfigFromFlags(masterUrl, kubeconfigPath string) (*restclient.Config, error) {
   
	if kubeconfigPath == "" && masterUrl 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值