文章目录
前言
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的基本用法,希望对你有所帮助