k8s之client-go:golang与k8s交互的桥梁

文章目录

前言

k8s是一个非常成熟且强大的容器自动化编排引擎,对于这样一个利器,k8s官方提供了clientgo用来给我们使用golang去接入k8s,通过k8s的api来对k8s中的资源进行操作

通过client-go实现对k8s集群中资源对象(包括deployment、service、ingress、replicaSet、pod、namespace、node等)的增删改查等操作

示例

我们通过一个申请K8S中cronjob资源的例子,来举例说明clientgo的使用

go 复制代码
package main

import (
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/rest"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	v1 "k8s.io/api/core/v1"
	batchv1 "k8s.io/client-go/applyconfigurations/batch/v1"
	corev1 "k8s.io/client-go/applyconfigurations/core/v1"
)

var cli *kubernetes.Clientset
var config *rest.Config

// InitK8SCli 创建clientgo客户端
func InitK8SCli() error {
	var err error
	// k8s中的Pod通过这种方式获取配置信息(需要通过给pod绑定角色,通过rbac的权限控制对资源操作的权限)
	config, err = rest.InClusterConfig()
	if err != nil {
		return err
	}

	cli, err = kubernetes.NewForConfig(config)
	if err != nil {
		return err
	}

	return nil
}

func main() {
	err := InitK8SCli()
	if err != nil {
		panic(err)
	}
	// 成功的job的最大数量
	var successfulJobsHistoryLimit int32 = 1
	// 失败的job的最大数量
	var failedJobsHistoryLimit int32 = 1
	// job执行完毕之后的存活时间
	var ttlSecondsAfterFinished int32 = 1
	cronJobInfo := K8SCronJobInfo{
		Name:                       "zuimo",
		Namespace:                  "zuimo",
		Schedule:                   "* * * * *",
		Image:                      "busybox",
		Command:                    []string{"echo", "hello world"},
		RestartPolicy:              "Never",
		SuccessfulJobsHistoryLimit: &successfulJobsHistoryLimit,
		FailedJobsHistoryLimit:     &failedJobsHistoryLimit,
		TTLSecondsAfterFinished:    &ttlSecondsAfterFinished,
	}
	err = ApplyCronJob(cronJobInfo)
	if err != nil {
		panic(err)
	}
}

type K8SCronJobInfo struct {
	Name                       string   `json:"name"`
	Namespace                  string   `json:"namespace"`
	Schedule                   string   `json:"schedule"`
	Image                      string   `json:"image"`
	Command                    []string `json:"command"`
	RestartPolicy              string   `json:"restartPolicy"`
	SuccessfulJobsHistoryLimit *int32   `json:"successfulJobsHistoryLimit"`
	FailedJobsHistoryLimit     *int32   `json:"failedJobsHistoryLimit"`
	TTLSecondsAfterFinished    *int32   `json:"ttlSecondsAfterFinished"`
}

// 申请cronjob的函数
func ApplyCronJob(cronJobInfo K8SCronJobInfo) error {
	cronJob := buildCronJob(cronJobInfo)
	result, err := cli.BatchV1().CronJobs(cronJobInfo.Namespace).Apply(context.Background(), cronJob,
		metav1.ApplyOptions{FieldManager: "data-manager"})
	if err != nil {
		fmt.Printf("cron job obj: %v\n", result)
		return err
	}

	return nil
}

// buildCronJob 构造cronjob结构体
func buildCronJob(param K8SCronJobInfo) *batchv1.CronJobApplyConfiguration {
	container := corev1.Container().WithName(param.Name).WithImage(param.Image).
		WithImagePullPolicy(v1.PullIfNotPresent).WithCommand(param.Command...)

	podSpec := corev1.PodSpec().WithContainers(container).WithRestartPolicy(v1.RestartPolicy(param.RestartPolicy))

	podTemplateSpec := corev1.PodTemplateSpec().WithSpec(podSpec)

	jobSpec := batchv1.JobSpec().WithTemplate(podTemplateSpec)

	if param.TTLSecondsAfterFinished != nil {
		jobSpec = jobSpec.WithTTLSecondsAfterFinished(*param.TTLSecondsAfterFinished)
	}

	jobTemplateSpec := batchv1.JobTemplateSpec().WithSpec(jobSpec)

	cronJobSpec := setJobsHistoryLimit(batchv1.CronJobSpec().WithSchedule(param.Schedule).
		WithJobTemplate(jobTemplateSpec), param.SuccessfulJobsHistoryLimit, param.FailedJobsHistoryLimit)

	return batchv1.CronJob(param.Name, param.Namespace).WithSpec(cronJobSpec)
}

func setJobsHistoryLimit(cronJobSpec *batchv1.CronJobSpecApplyConfiguration, successfulJobsHistoryLimit,
	failedJobsHistoryLimit *int32) *batchv1.CronJobSpecApplyConfiguration {

	if successfulJobsHistoryLimit != nil {
		cronJobSpec = cronJobSpec.WithSuccessfulJobsHistoryLimit(*successfulJobsHistoryLimit)
	}

	if failedJobsHistoryLimit != nil {
		cronJobSpec = cronJobSpec.WithFailedJobsHistoryLimit(*failedJobsHistoryLimit)
	}

	return cronJobSpec
}

总结

我们演示了一个简单的例子,来描述client-go的基本用法,希望对你有所帮助

相关推荐
pan_junbiao4 小时前
Go 语言基本数据类型
java·前端·golang
codeejun12 小时前
每日一Go·MySQL-24、死锁排查与解决方案
开发语言·mysql·golang
利威尔xu18 小时前
Go context取消传播3层:信号传不到第3层goroutine,泄漏拖垮
后端·golang
always202219 小时前
AI运行时 · 附录3 - GPU 设备插件与 MIG:K8s 上的 AI 加速器编排
人工智能·容器·kubernetes
Sakura_j_h_21 小时前
TypeScript 7.0 换 Go 编译器后,我先在 6.0 清完默认值
javascript·golang·typescript·vite·前端工程化·tsc
码途行者2 天前
每天10分钟学Go:第23课 协程(goroutine)
开发语言·后端·golang
利威尔xu2 天前
2026-11-25-Go-panic-recover面试
面试·golang
码途行者2 天前
每天10分钟学Go:第24课 通道-协程之间的传送带
开发语言·后端·golang
always20222 天前
AI运行时 · 06 - Kata 与 K8s 集成:RuntimeClass / CSI kata-directvolume / 性能开销与调优
人工智能·容器·kubernetes
赤生云电竞3 天前
GPU算力共享平台架构实践:任务分发与资源隔离——基于NVIDIA MIG与Kubernetes调度器的工程化拆解
架构·kubernetes·gpu算力