本章将写一个在实际工作中的项目案例,来更好的说明KubeBuilder一些技术细节
项目需求
将K8s中的ConfigMap定时备份到阿里云的OSS
通过脚手架快速创建项目
script1 2 3 4
| mkdir configmap cd configmap kubebuilder init --repo=configmap --domain xinyu.com kubebuilder create api --group configmap --version v1 --kind ConfigMapWatcher
|
定义CRD资源
这里,你可以写一个demo案例,里面包含所有的配置项
script1 2 3 4 5 6 7 8 9 10 11 12 13 14
| apiVersion: configmap.xinyu.com/v1 kind: ConfigMapWatcher metadata: name: demo namespace: test spec: ossConfig: endpoint: oss-cn-qingdao.aliyuncs.com accessKey: ********* accessSecret: ********* bucket: configmapbackup directory: test scheduler: "*/1 * * * *"
|
根据上面的demo.yaml,我们需要去修改脚手架生成的类型文件
写Controller的逻辑
因为要用到oss以及定时任务,我们这里需要先引入两个包
script1 2
| go get github.com/robfig/cron/v3 go get github.com/aliyun/aliyun-oss-go-sdk
|
由于 Reconcile 只有在初始化、创建以及更新crd资源的时候,才会触发,所以我们添加监听,用于处理当资源删除之后的处理
修改SetupWithManager的部分代码,添加监听对象以及相应的事件处理
script1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| // SetupWithManager sets up the controller with the Manager. func (r *ConfigMapWatcherReconciler) SetupWithManager(mgr ctrl.Manager) error { return ctrl.NewControllerManagedBy(mgr). For(&configmapv1.ConfigMapWatcher{}).Watches(&configmapv1.ConfigMapWatcher{}, &EventHandler{}). Complete(r) }
type EventHandler struct { // Create is called in response to an create event - e.g. Pod Creation. }
func (e EventHandler) Create(ctx context.Context, event event.CreateEvent, limitingInterface workqueue.RateLimitingInterface) {
}
func (e EventHandler) Update(ctx context.Context, event event.UpdateEvent, limitingInterface workqueue.RateLimitingInterface) {
}
func (e EventHandler) Delete(ctx context.Context, event event.DeleteEvent, limitingInterface workqueue.RateLimitingInterface) {
logger := log.FromContext(ctx) watcher := event.Object.DeepCopyObject().(*configmapv1.ConfigMapWatcher) key := getSchedulerKey(watcher.Name, watcher.Namespace)
scheduler, ok := syncMap.Load(key) if ok { scheduler.(*cron.Cron).Stop() syncMap.Delete(key) logger.Info("scheduler", "stop and delete", key) } }
func (e EventHandler) Generic(ctx context.Context, event event.GenericEvent, limitingInterface workqueue.RateLimitingInterface) {
}
|
接下来,在Reconcile中写创建/更新的逻辑
由于我们需要读取configmap,我们应配置下rbac注解,但执行make manifests的时候,kubebuilder会解析并生成rbac的yaml文件
编译、安装
script1 2 3 4 5 6 7 8
| # 生成Webhook配置、角色、CRD配置 make manifests # 生成深度复制文件 make generate # 安装crd make install # 调试运行 make run
|
发布
script1 2 3 4
| # 打包发布镜像 make docker-build && make docker-push # kubectl crd、rbac、deployment 相关的yaml make deploy
|
相关代码: https://github.com/123jixinyu/configmap/tree/main