client-go combat 6: After two years, the refreshed version continues the actual combat

Welcome to my GitHub

Here is a classification and summary of all original works of Xinchen (including supporting source code): https://github.com/zq2599/blog_demos

Links to series of articles

  1. Client-go combat one: preparation work
  2. Client-go combat two: RESTClient
  3. Client-go combat three: Clientset
  4. Client-go combat four: dynamicClient
  5. Client-go combat five: DiscoveryClient

After two years, "client-go combat" is activated, and more content will continue to be updated

  • Time flies. The "client-go in action" series is already two years ago. When I used client-go again in my recent work, I suddenly found that my original content was far from meeting the work requirements (entry-level, let you I laughed), so I plan to continue to update this series of articles, focusing on practicality and depth of understanding, not only to make up for my shortcomings, but also to provide more references for readers who have the same needs

Overview of this article

  • The role of this article is to prepare the environment for subsequent actual combat, mainly as follows
  1. install kubernetes
  2. Local installation auxiliary tool kubectl
  3. Determine the version of client-go
  4. Write a helloworld program to verify basic functions

Version Information

  • Here is a list of the versions of each software in actual combat for your reference
  1. go:1.19.3
  2. kubernetes:1.22.8
  3. client-go:v0.22.8
  4. Development environment: MacBook Pro 14-inch (M1 Pro chip), macOS Ventura 13.1

install kubernetes

Local installation auxiliary tool kubectl

  • If you want to remotely operate kubernetes locally, in addition to ssh logging in to the server where kubernetes is located, you can also install the kubectl tool locally, so that you don’t need to log in to the server remotely with ssh
  • For MacBook with M1 chip, execute the following command to install kubectl
curl -LO "https://dl.k8s.io/release/v1.22.8/bin/darwin/arm64/kubectl" \
&& chmod +x ./kubectl \
&& sudo mv ./kubectl /usr/local/bin/kubectl \
&& sudo chown root: /usr/local/bin/kubectl
  • For other types of computers and other versions of kubernetes, you only need to modify the parameters in the download path. For detailed parameters, please refer to the official kubernetes documentation
  • Execute the kubectl version --client command to verify, if the installation is successful, the response is as follows
➜  ~ kubectl version --client
Client Version: version.Info{
    
    Major:"1", Minor:"22", GitVersion:"v1.22.8", GitCommit:"7061dbbf75f9f82e8ab21f9be7e8ffcaae8e0d44", GitTreeState:"clean", BuildDate:"2022-03-16T14:10:06Z", GoVersion:"go1.16.15", Compiler:"gc", Platform:"darwin/arm64"}
  • Now although kubectl is successfully installed, it is not possible to connect to kubernetes remotely. We need to get the configuration file

  • Log in to the server where kubernetes is located, there is a config file in the ~/.kube/ directory , download it, and put it in the ~/.kube/ directory of the local machine (create a new one if there is no directory)

  • Also note: if your kubernetes environment is deployed on Alibaba Cloud, the server may have multiple IPs. If there is no external network IP on the x509 certificate, then you cannot use kubectl to connect to this kubernetes locally. Add the IP to the certificate, the specific method will not be expanded in this article, you can refer to the article of this big guy: https://blog.csdn.net/lwlfox/article/details/122718568

  • Now, you can access the remote kubernetes environment by executing the kubectl command locally

➜  ~ kubectl get pod -A
NAMESPACE          NAME                                              READY   STATUS    RESTARTS   AGE
calico-apiserver   calico-apiserver-bf576f79d-ljtst                  1/1     Running   0          105m
calico-apiserver   calico-apiserver-bf576f79d-tmmxm                  1/1     Running   0          105m
calico-system      calico-kube-controllers-78687bb75f-86nm6          1/1     Running   0          106m
calico-system      calico-node-njxv4                                 1/1     Running   0          106m
calico-system      calico-typha-59df5f67b9-hmngq                     1/1     Running   0          106m
calico-system      csi-node-driver-5l6nk                             2/2     Running   0          106m
kube-system        coredns-78fcd69978-gvzh8                          1/1     Running   0          106m
kube-system        coredns-78fcd69978-xfftz                          1/1     Running   0          106m
kube-system        etcd-izwz9h7q9tnbtp2qnzu8prz                      1/1     Running   0          107m
kube-system        kube-apiserver-izwz9h7q9tnbtp2qnzu8prz            1/1     Running   0          107m
kube-system        kube-controller-manager-izwz9h7q9tnbtp2qnzu8prz   1/1     Running   0          107m
kube-system        kube-proxy-cqsgp                                  1/1     Running   0          106m
kube-system        kube-scheduler-izwz9h7q9tnbtp2qnzu8prz            1/1     Running   0          107m
tigera-operator    tigera-operator-6f669b6c4f-7tssg                  1/1     Running   0          106m

select version

  • How to determine the version of client-go after determining the kubernetes version? Look at the official description of client-go , as shown below
    insert image description here
  • Briefly explain how to determine the version
  1. There are two versions of client-go: the old version of kubernetes-1.xy and the new version of v0.xy
  2. If the kubernetes version is greater than or equal to 1.17.0 , please select a new version for the client-go version. For example: if the kubernetes version is 1.20.4 , the client-go version is v0.20.4
  3. If the kubernetes version is less than 1.17.0 , please select the old version for the client-go version. For example: if the kubernetes version is 1.20.4 , the client-go version is kubernetes-1.16.3
  • To sum up, the following articles in the "client-go combat" series will use: the combination of kubernetes:1.22.8 and client-go:v0.22.8

How to run and deploy the helloworld application

  • Next, create a helloworld application and try whether the basic functions of client-go are normal.
  • In order to save trouble, this helloworld application should not be deployed on kubernetes to alleviate it, just run it directly on vscode, and remotely access the kubernetes environment

Develop helloworld applications

  • Create a new directory named basic and enter this directory
  • Create a go project and execute go mod init basic
  • Download client-go dependencies and specify the version
go get k8s.io/[email protected]
go get k8s.io/client-go/[email protected]
go get k8s.io/client-go/tools/[email protected]
go get k8s.io/client-go/[email protected]
  • Create a new main.go file with the following content
package main

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

	"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

	// 试图取到当前账号的家目录
	if home := homedir.HomeDir(); home != "" {
    
    
		// 如果能取到,就把家目录下的.kube/config作为默认配置文件
		kubeconfig = flag.String("kubeconfig", filepath.Join(home, ".kube", "config"), "(optional) absolute path to the kubeconfig file")
	} else {
    
    
		// 如果取不到,就没有默认配置文件,必须通过kubeconfig参数来指定
		kubeconfig = flag.String("kubeconfig", "", "absolute path to the kubeconfig file")
	}
	flag.Parse()

	// 加载配置文件
	config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
	if err != nil {
    
    
		panic(err.Error())
	}

	// 用clientset类来执行后续的查询操作
	clientset, err := kubernetes.NewForConfig(config)
	if err != nil {
    
    
		panic(err.Error())
	}

	namespace := "kube-system"

	// 查询pod列表
	pods, err := clientset.CoreV1().Pods(namespace).List(context.TODO(), metav1.ListOptions{
    
    })
	if err != nil {
    
    
		panic(err.Error())
	}

	nums := len(pods.Items)

	fmt.Printf("There are %d pods in the cluster\n", nums)

	// 如果没有pod就返回了
	if nums < 1 {
    
    
		return
	}

	// 遍历列表中的每个pod
	for index, pod := range pods.Items {
    
    
		fmt.Printf("%v. pod name : %v\n", index, pod.Name)

		// 用pod name精确搜索单个pod
		podObj, err := clientset.CoreV1().Pods(namespace).Get(context.TODO(), pod.Name, metav1.GetOptions{
    
    })
		if errors.IsNotFound(err) {
    
    
			fmt.Printf("Pod %s in namespace %s not found\n", pod.Name, namespace)
		} else if statusError, isStatus := err.(*errors.StatusError); isStatus {
    
    
			fmt.Printf("Error getting pod %s in namespace %s: %v\n",
				pod.Name, namespace, statusError.ErrStatus.Message)
		} else if err != nil {
    
    
			panic(err.Error())
		} else {
    
    
			fmt.Printf("Found pod %s in namespace %s\n", podObj.Name, namespace)
		}
	}

}
  • Since the config file has been stored in the ~/.kube/ directory of the current computer before, there is no need for any additional parameters, just run the main method on vscode directly, the console output is as follows, it can be seen that client-go can access kubernetes normally, and then The actual combat can also be carried out smoothly.
There are 7 pods in the cluster
0. pod name : coredns-78fcd69978-gvzh8
Found pod coredns-78fcd69978-gvzh8 in namespace kube-system
1. pod name : coredns-78fcd69978-xfftz
Found pod coredns-78fcd69978-xfftz in namespace kube-system
2. pod name : etcd-izwz9h7q9tnbtp2qnzu8prz
Found pod etcd-izwz9h7q9tnbtp2qnzu8prz in namespace kube-system
3. pod name : kube-apiserver-izwz9h7q9tnbtp2qnzu8prz
Found pod kube-apiserver-izwz9h7q9tnbtp2qnzu8prz in namespace kube-system
4. pod name : kube-controller-manager-izwz9h7q9tnbtp2qnzu8prz
Found pod kube-controller-manager-izwz9h7q9tnbtp2qnzu8prz in namespace kube-system
5. pod name : kube-proxy-cqsgp
Found pod kube-proxy-cqsgp in namespace kube-system
6. pod name : kube-scheduler-izwz9h7q9tnbtp2qnzu8prz
Found pod kube-scheduler-izwz9h7q9tnbtp2qnzu8prz in namespace kube-system
  • So far, the new version of client-go and the new environment are ready, let's explore client-go in depth

You are not alone, Xinchen Original is with you all the way

  1. Java series
  2. Spring series
  3. Docker series
  4. kubernetes series
  5. Database + middleware series
  6. DevOps series

Guess you like

Origin blog.csdn.net/boling_cavalry/article/details/128686327