4

client-go实战之六:时隔两年,刷新版本继续实战 - 程序员欣宸

 11 months ago
source link: https://www.cnblogs.com/bolingcavalry/p/17724713.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

欢迎访问我的GitHub

这里分类和汇总了欣宸的全部原创(含配套源码):https://github.com/zq2599/blog_demos

时隔两年,《client-go实战》被激活,更多内容将会继续更新

  • 时间过得真快,《client-go实战》系列已是两年前的作品,近期工作中再次用到client-go时,突然发现自己原创的内容远达不到工作要求(入门级,让您见笑了),于是打算继续更新此系列文章,重点是实用性和理解深度,既为自己补全短板,也为有同样需要的读者提供更多参考
  • 本篇的作用是为后续实战准备环境,主要有以下内容
  1. 安装kubernetes
  2. 本地安装辅助工具kubectl
  3. 确定client-go的版本
  4. 写个helloworld程序验证基本功能
  • 这里列举出实战中各软件的版本情况,供您参考
  1. go:1.19.3
  2. kubernetes:1.22.8
  3. client-go:v0.22.8
  4. 开发环境:MacBook Pro 14寸(M1 Pro芯片),macOS Ventura 13.1

安装kubernetes

本地安装辅助工具kubectl

  • 如果想在本地远程操作kubernetes,除了ssh登录到kubernetes所在服务器,还可以在本地安装kubectl工具,这样就不用远程ssh登录服务器了
  • 针对M1芯片的MacBook,执行以下命令即可安装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
  • 对于其他类型的电脑和其他版本的kubernetes,只需要修改下载路径中的参数即可,详细的参数请参考kubernetes官方文档
  • 执行kubectl version --client命令验证,如果安装成功则响应如下
➜  ~ 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"}
  • 现在虽然kubectl安装成功,但还不能远程连接kubernetes,咱们需要把配置文件搞到手

  • 登录kubernetes所在服务器,在~/.kube/目录下有个config文件,将其下载下来,放在本机的~/.kube/目录下(没有目录就新建)

  • 另外还要注意:如果您的kubernetes环境部署在阿里云,那么服务器可能有多个IP,此时x509证书上如果没有外网IP,那么在本地是无法用kubectl连接这个kubernetes的,需要把外网IP添加到证书上去,具体方法就不在本篇展开了,可以参考这位大佬的文章:https://blog.csdn.net/lwlfox/article/details/122718568

  • 现在,在本机执行kubectl命令就能访问远程kubernetes环境了

➜  ~ 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
  • 在确定了kubernetes版本后如何确定client-go的版本呢?来看client-go官方说明,如下图
    在这里插入图片描述
  • 简单解释一下如何确定版本
  1. client-go的版本一共有两类:旧版的kubernetes-1.x.y和新版v0.x.y
  2. 如果kubernetes版本大于或等于1.17.0,client-go版本请选择新版,举例:如果kubernetes版本是1.20.4,client-go版本就是v0.20.4
  3. 如果kubernetes版本小于1.17.0,client-go版本请选择旧版,举例:如果kubernetes版本是1.20.4,client-go版本就是kubernetes-1.16.3
  • 综上所述,《client-go实战》系列接下来的文章,都会使用:kubernetes:1.22.8和client-go:v0.22.8的组合

helloworld应用的运行和部署方式

  • 接下来新建一个helloworld应用,试试client-go的基本功能是否正常
  • 为了简单省事儿,这个helloworld应用就不要部署在kubernetes缓解了,直接在vscode上运行即可,远程访问kubernetes环境

开发helloworld应用

  • 新建名为basic的目录,进入此目录
  • 创建一个go项目,执行go mod init basic
  • 下载client-go依赖并指定版本
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]
  • 新建main.go文件,内容如下
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)
		}
	}

}
  • 由于config文件之前已经存放在当前电脑的~/.kube/目录下,因此无需任何额外参数,直接在vscode上运行main方法即可,控制台输出如下,可见client-go可以正常访问kubernetes,接下来的实战也能顺利展开了
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
  • 至此,新版本的client-go和新环境都已经准备就绪,接下来咱们一起深入探索client-go

欢迎关注博客园:程序员欣宸

学习路上,你不孤单,欣宸原创一路相伴...


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK